SemaDecl.cpp revision 6aa52ec6b969faabf3764baf79d89810b8249a7e
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/APValue.h" 22#include "clang/AST/ASTConsumer.h" 23#include "clang/AST/ASTContext.h" 24#include "clang/AST/CXXInheritance.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/Basic/SourceManager.h" 37#include "clang/Basic/TargetInfo.h" 38// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's) 39#include "clang/Lex/Preprocessor.h" 40#include "clang/Lex/HeaderSearch.h" 41#include "clang/Lex/ModuleLoader.h" 42#include "llvm/ADT/Triple.h" 43#include <algorithm> 44#include <cstring> 45#include <functional> 46using namespace clang; 47using namespace sema; 48 49Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 50 if (OwnedType) { 51 Decl *Group[2] = { OwnedType, Ptr }; 52 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 53 } 54 55 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 56} 57 58/// \brief If the identifier refers to a type name within this scope, 59/// return the declaration of that type. 60/// 61/// This routine performs ordinary name lookup of the identifier II 62/// within the given scope, with optional C++ scope specifier SS, to 63/// determine whether the name refers to a type. If so, returns an 64/// opaque pointer (actually a QualType) corresponding to that 65/// type. Otherwise, returns NULL. 66/// 67/// If name lookup results in an ambiguity, this routine will complain 68/// and then return NULL. 69ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 70 Scope *S, CXXScopeSpec *SS, 71 bool isClassName, bool HasTrailingDot, 72 ParsedType ObjectTypePtr, 73 bool WantNontrivialTypeSourceInfo) { 74 // Determine where we will perform name lookup. 75 DeclContext *LookupCtx = 0; 76 if (ObjectTypePtr) { 77 QualType ObjectType = ObjectTypePtr.get(); 78 if (ObjectType->isRecordType()) 79 LookupCtx = computeDeclContext(ObjectType); 80 } else if (SS && SS->isNotEmpty()) { 81 LookupCtx = computeDeclContext(*SS, false); 82 83 if (!LookupCtx) { 84 if (isDependentScopeSpecifier(*SS)) { 85 // C++ [temp.res]p3: 86 // A qualified-id that refers to a type and in which the 87 // nested-name-specifier depends on a template-parameter (14.6.2) 88 // shall be prefixed by the keyword typename to indicate that the 89 // qualified-id denotes a type, forming an 90 // elaborated-type-specifier (7.1.5.3). 91 // 92 // We therefore do not perform any name lookup if the result would 93 // refer to a member of an unknown specialization. 94 if (!isClassName) 95 return ParsedType(); 96 97 // We know from the grammar that this name refers to a type, 98 // so build a dependent node to describe the type. 99 if (WantNontrivialTypeSourceInfo) 100 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 101 102 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 103 QualType T = 104 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 105 II, NameLoc); 106 107 return ParsedType::make(T); 108 } 109 110 return ParsedType(); 111 } 112 113 if (!LookupCtx->isDependentContext() && 114 RequireCompleteDeclContext(*SS, LookupCtx)) 115 return ParsedType(); 116 } 117 118 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 119 // lookup for class-names. 120 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 121 LookupOrdinaryName; 122 LookupResult Result(*this, &II, NameLoc, Kind); 123 if (LookupCtx) { 124 // Perform "qualified" name lookup into the declaration context we 125 // computed, which is either the type of the base of a member access 126 // expression or the declaration context associated with a prior 127 // nested-name-specifier. 128 LookupQualifiedName(Result, LookupCtx); 129 130 if (ObjectTypePtr && Result.empty()) { 131 // C++ [basic.lookup.classref]p3: 132 // If the unqualified-id is ~type-name, the type-name is looked up 133 // in the context of the entire postfix-expression. If the type T of 134 // the object expression is of a class type C, the type-name is also 135 // looked up in the scope of class C. At least one of the lookups shall 136 // find a name that refers to (possibly cv-qualified) T. 137 LookupName(Result, S); 138 } 139 } else { 140 // Perform unqualified name lookup. 141 LookupName(Result, S); 142 } 143 144 NamedDecl *IIDecl = 0; 145 switch (Result.getResultKind()) { 146 case LookupResult::NotFound: 147 case LookupResult::NotFoundInCurrentInstantiation: 148 case LookupResult::FoundOverloaded: 149 case LookupResult::FoundUnresolvedValue: 150 Result.suppressDiagnostics(); 151 return ParsedType(); 152 153 case LookupResult::Ambiguous: 154 // Recover from type-hiding ambiguities by hiding the type. We'll 155 // do the lookup again when looking for an object, and we can 156 // diagnose the error then. If we don't do this, then the error 157 // about hiding the type will be immediately followed by an error 158 // that only makes sense if the identifier was treated like a type. 159 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 160 Result.suppressDiagnostics(); 161 return ParsedType(); 162 } 163 164 // Look to see if we have a type anywhere in the list of results. 165 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 166 Res != ResEnd; ++Res) { 167 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 168 if (!IIDecl || 169 (*Res)->getLocation().getRawEncoding() < 170 IIDecl->getLocation().getRawEncoding()) 171 IIDecl = *Res; 172 } 173 } 174 175 if (!IIDecl) { 176 // None of the entities we found is a type, so there is no way 177 // to even assume that the result is a type. In this case, don't 178 // complain about the ambiguity. The parser will either try to 179 // perform this lookup again (e.g., as an object name), which 180 // will produce the ambiguity, or will complain that it expected 181 // a type name. 182 Result.suppressDiagnostics(); 183 return ParsedType(); 184 } 185 186 // We found a type within the ambiguous lookup; diagnose the 187 // ambiguity and then return that type. This might be the right 188 // answer, or it might not be, but it suppresses any attempt to 189 // perform the name lookup again. 190 break; 191 192 case LookupResult::Found: 193 IIDecl = Result.getFoundDecl(); 194 break; 195 } 196 197 assert(IIDecl && "Didn't find decl"); 198 199 QualType T; 200 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 201 DiagnoseUseOfDecl(IIDecl, NameLoc); 202 203 if (T.isNull()) 204 T = Context.getTypeDeclType(TD); 205 206 if (SS && SS->isNotEmpty()) { 207 if (WantNontrivialTypeSourceInfo) { 208 // Construct a type with type-source information. 209 TypeLocBuilder Builder; 210 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 211 212 T = getElaboratedType(ETK_None, *SS, T); 213 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 214 ElabTL.setKeywordLoc(SourceLocation()); 215 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 216 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 217 } else { 218 T = getElaboratedType(ETK_None, *SS, T); 219 } 220 } 221 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 222 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 223 if (!HasTrailingDot) 224 T = Context.getObjCInterfaceType(IDecl); 225 } 226 227 if (T.isNull()) { 228 // If it's not plausibly a type, suppress diagnostics. 229 Result.suppressDiagnostics(); 230 return ParsedType(); 231 } 232 return ParsedType::make(T); 233} 234 235/// isTagName() - This method is called *for error recovery purposes only* 236/// to determine if the specified name is a valid tag name ("struct foo"). If 237/// so, this returns the TST for the tag corresponding to it (TST_enum, 238/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C 239/// where the user forgot to specify the tag. 240DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 241 // Do a tag name lookup in this scope. 242 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 243 LookupName(R, S, false); 244 R.suppressDiagnostics(); 245 if (R.getResultKind() == LookupResult::Found) 246 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 247 switch (TD->getTagKind()) { 248 default: return DeclSpec::TST_unspecified; 249 case TTK_Struct: return DeclSpec::TST_struct; 250 case TTK_Union: return DeclSpec::TST_union; 251 case TTK_Class: return DeclSpec::TST_class; 252 case TTK_Enum: return DeclSpec::TST_enum; 253 } 254 } 255 256 return DeclSpec::TST_unspecified; 257} 258 259/// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 260/// if a CXXScopeSpec's type is equal to the type of one of the base classes 261/// then downgrade the missing typename error to a warning. 262/// This is needed for MSVC compatibility; Example: 263/// @code 264/// template<class T> class A { 265/// public: 266/// typedef int TYPE; 267/// }; 268/// template<class T> class B : public A<T> { 269/// public: 270/// A<T>::TYPE a; // no typename required because A<T> is a base class. 271/// }; 272/// @endcode 273bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS) { 274 if (CurContext->isRecord()) { 275 const Type *Ty = SS->getScopeRep()->getAsType(); 276 277 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 278 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 279 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) 280 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType())) 281 return true; 282 } 283 return false; 284} 285 286bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II, 287 SourceLocation IILoc, 288 Scope *S, 289 CXXScopeSpec *SS, 290 ParsedType &SuggestedType) { 291 // We don't have anything to suggest (yet). 292 SuggestedType = ParsedType(); 293 294 // There may have been a typo in the name of the type. Look up typo 295 // results, in case we have something that we can suggest. 296 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc), 297 LookupOrdinaryName, S, SS, NULL, 298 false, CTC_Type)) { 299 std::string CorrectedStr(Corrected.getAsString(getLangOptions())); 300 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions())); 301 302 if (Corrected.isKeyword()) { 303 // We corrected to a keyword. 304 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it. 305 Diag(IILoc, diag::err_unknown_typename_suggest) 306 << &II << CorrectedQuotedStr; 307 return true; 308 } else { 309 NamedDecl *Result = Corrected.getCorrectionDecl(); 310 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) && 311 !Result->isInvalidDecl()) { 312 // We found a similarly-named type or interface; suggest that. 313 if (!SS || !SS->isSet()) 314 Diag(IILoc, diag::err_unknown_typename_suggest) 315 << &II << CorrectedQuotedStr 316 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 317 else if (DeclContext *DC = computeDeclContext(*SS, false)) 318 Diag(IILoc, diag::err_unknown_nested_typename_suggest) 319 << &II << DC << CorrectedQuotedStr << SS->getRange() 320 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 321 else 322 llvm_unreachable("could not have corrected a typo here"); 323 324 Diag(Result->getLocation(), diag::note_previous_decl) 325 << CorrectedQuotedStr; 326 327 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS, 328 false, false, ParsedType(), 329 /*NonTrivialTypeSourceInfo=*/true); 330 return true; 331 } 332 } 333 } 334 335 if (getLangOptions().CPlusPlus) { 336 // See if II is a class template that the user forgot to pass arguments to. 337 UnqualifiedId Name; 338 Name.setIdentifier(&II, IILoc); 339 CXXScopeSpec EmptySS; 340 TemplateTy TemplateResult; 341 bool MemberOfUnknownSpecialization; 342 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 343 Name, ParsedType(), true, TemplateResult, 344 MemberOfUnknownSpecialization) == TNK_Type_template) { 345 TemplateName TplName = TemplateResult.getAsVal<TemplateName>(); 346 Diag(IILoc, diag::err_template_missing_args) << TplName; 347 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 348 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 349 << TplDecl->getTemplateParameters()->getSourceRange(); 350 } 351 return true; 352 } 353 } 354 355 // FIXME: Should we move the logic that tries to recover from a missing tag 356 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 357 358 if (!SS || (!SS->isSet() && !SS->isInvalid())) 359 Diag(IILoc, diag::err_unknown_typename) << &II; 360 else if (DeclContext *DC = computeDeclContext(*SS, false)) 361 Diag(IILoc, diag::err_typename_nested_not_found) 362 << &II << DC << SS->getRange(); 363 else if (isDependentScopeSpecifier(*SS)) { 364 unsigned DiagID = diag::err_typename_missing; 365 if (getLangOptions().Microsoft && isMicrosoftMissingTypename(SS)) 366 DiagID = diag::warn_typename_missing; 367 368 Diag(SS->getRange().getBegin(), DiagID) 369 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName() 370 << SourceRange(SS->getRange().getBegin(), IILoc) 371 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 372 SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc).get(); 373 } else { 374 assert(SS && SS->isInvalid() && 375 "Invalid scope specifier has already been diagnosed"); 376 } 377 378 return true; 379} 380 381/// \brief Determine whether the given result set contains either a type name 382/// or 383static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 384 bool CheckTemplate = R.getSema().getLangOptions().CPlusPlus && 385 NextToken.is(tok::less); 386 387 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 388 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 389 return true; 390 391 if (CheckTemplate && isa<TemplateDecl>(*I)) 392 return true; 393 } 394 395 return false; 396} 397 398Sema::NameClassification Sema::ClassifyName(Scope *S, 399 CXXScopeSpec &SS, 400 IdentifierInfo *&Name, 401 SourceLocation NameLoc, 402 const Token &NextToken) { 403 DeclarationNameInfo NameInfo(Name, NameLoc); 404 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 405 406 if (NextToken.is(tok::coloncolon)) { 407 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 408 QualType(), false, SS, 0, false); 409 410 } 411 412 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 413 LookupParsedName(Result, S, &SS, !CurMethod); 414 415 // Perform lookup for Objective-C instance variables (including automatically 416 // synthesized instance variables), if we're in an Objective-C method. 417 // FIXME: This lookup really, really needs to be folded in to the normal 418 // unqualified lookup mechanism. 419 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 420 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 421 if (E.get() || E.isInvalid()) 422 return E; 423 424 // Synthesize ivars lazily. 425 if (getLangOptions().ObjCDefaultSynthProperties && 426 getLangOptions().ObjCNonFragileABI2) { 427 if (SynthesizeProvisionalIvar(Result, Name, NameLoc)) { 428 if (const ObjCPropertyDecl *Property = 429 canSynthesizeProvisionalIvar(Name)) { 430 Diag(NameLoc, diag::warn_synthesized_ivar_access) << Name; 431 Diag(Property->getLocation(), diag::note_property_declare); 432 } 433 434 // FIXME: This is strange. Shouldn't we just take the ivar returned 435 // from SynthesizeProvisionalIvar and continue with that? 436 E = LookupInObjCMethod(Result, S, Name, true); 437 if (E.get() || E.isInvalid()) 438 return E; 439 } 440 } 441 } 442 443 bool SecondTry = false; 444 bool IsFilteredTemplateName = false; 445 446Corrected: 447 switch (Result.getResultKind()) { 448 case LookupResult::NotFound: 449 // If an unqualified-id is followed by a '(', then we have a function 450 // call. 451 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 452 // In C++, this is an ADL-only call. 453 // FIXME: Reference? 454 if (getLangOptions().CPlusPlus) 455 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 456 457 // C90 6.3.2.2: 458 // If the expression that precedes the parenthesized argument list in a 459 // function call consists solely of an identifier, and if no 460 // declaration is visible for this identifier, the identifier is 461 // implicitly declared exactly as if, in the innermost block containing 462 // the function call, the declaration 463 // 464 // extern int identifier (); 465 // 466 // appeared. 467 // 468 // We also allow this in C99 as an extension. 469 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 470 Result.addDecl(D); 471 Result.resolveKind(); 472 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 473 } 474 } 475 476 // In C, we first see whether there is a tag type by the same name, in 477 // which case it's likely that the user just forget to write "enum", 478 // "struct", or "union". 479 if (!getLangOptions().CPlusPlus && !SecondTry) { 480 Result.clear(LookupTagName); 481 LookupParsedName(Result, S, &SS); 482 if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) { 483 const char *TagName = 0; 484 const char *FixItTagName = 0; 485 switch (Tag->getTagKind()) { 486 case TTK_Class: 487 TagName = "class"; 488 FixItTagName = "class "; 489 break; 490 491 case TTK_Enum: 492 TagName = "enum"; 493 FixItTagName = "enum "; 494 break; 495 496 case TTK_Struct: 497 TagName = "struct"; 498 FixItTagName = "struct "; 499 break; 500 501 case TTK_Union: 502 TagName = "union"; 503 FixItTagName = "union "; 504 break; 505 } 506 507 Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 508 << Name << TagName << getLangOptions().CPlusPlus 509 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 510 break; 511 } 512 513 Result.clear(LookupOrdinaryName); 514 } 515 516 // Perform typo correction to determine if there is another name that is 517 // close to this name. 518 if (!SecondTry) { 519 SecondTry = true; 520 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 521 Result.getLookupKind(), S, &SS)) { 522 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 523 unsigned QualifiedDiag = diag::err_no_member_suggest; 524 std::string CorrectedStr(Corrected.getAsString(getLangOptions())); 525 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions())); 526 527 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 528 NamedDecl *UnderlyingFirstDecl 529 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 530 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) && 531 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 532 UnqualifiedDiag = diag::err_no_template_suggest; 533 QualifiedDiag = diag::err_no_member_template_suggest; 534 } else if (UnderlyingFirstDecl && 535 (isa<TypeDecl>(UnderlyingFirstDecl) || 536 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 537 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 538 UnqualifiedDiag = diag::err_unknown_typename_suggest; 539 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 540 } 541 542 if (SS.isEmpty()) 543 Diag(NameLoc, UnqualifiedDiag) 544 << Name << CorrectedQuotedStr 545 << FixItHint::CreateReplacement(NameLoc, CorrectedStr); 546 else 547 Diag(NameLoc, QualifiedDiag) 548 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 549 << SS.getRange() 550 << FixItHint::CreateReplacement(NameLoc, CorrectedStr); 551 552 // Update the name, so that the caller has the new name. 553 Name = Corrected.getCorrectionAsIdentifierInfo(); 554 555 // Also update the LookupResult... 556 // FIXME: This should probably go away at some point 557 Result.clear(); 558 Result.setLookupName(Corrected.getCorrection()); 559 if (FirstDecl) Result.addDecl(FirstDecl); 560 561 // Typo correction corrected to a keyword. 562 if (Corrected.isKeyword()) 563 return Corrected.getCorrectionAsIdentifierInfo(); 564 565 if (FirstDecl) 566 Diag(FirstDecl->getLocation(), diag::note_previous_decl) 567 << CorrectedQuotedStr; 568 569 // If we found an Objective-C instance variable, let 570 // LookupInObjCMethod build the appropriate expression to 571 // reference the ivar. 572 // FIXME: This is a gross hack. 573 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 574 Result.clear(); 575 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 576 return move(E); 577 } 578 579 goto Corrected; 580 } 581 } 582 583 // We failed to correct; just fall through and let the parser deal with it. 584 Result.suppressDiagnostics(); 585 return NameClassification::Unknown(); 586 587 case LookupResult::NotFoundInCurrentInstantiation: 588 // We performed name lookup into the current instantiation, and there were 589 // dependent bases, so we treat this result the same way as any other 590 // dependent nested-name-specifier. 591 592 // C++ [temp.res]p2: 593 // A name used in a template declaration or definition and that is 594 // dependent on a template-parameter is assumed not to name a type 595 // unless the applicable name lookup finds a type name or the name is 596 // qualified by the keyword typename. 597 // 598 // FIXME: If the next token is '<', we might want to ask the parser to 599 // perform some heroics to see if we actually have a 600 // template-argument-list, which would indicate a missing 'template' 601 // keyword here. 602 return BuildDependentDeclRefExpr(SS, NameInfo, /*TemplateArgs=*/0); 603 604 case LookupResult::Found: 605 case LookupResult::FoundOverloaded: 606 case LookupResult::FoundUnresolvedValue: 607 break; 608 609 case LookupResult::Ambiguous: 610 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) && 611 hasAnyAcceptableTemplateNames(Result)) { 612 // C++ [temp.local]p3: 613 // A lookup that finds an injected-class-name (10.2) can result in an 614 // ambiguity in certain cases (for example, if it is found in more than 615 // one base class). If all of the injected-class-names that are found 616 // refer to specializations of the same class template, and if the name 617 // is followed by a template-argument-list, the reference refers to the 618 // class template itself and not a specialization thereof, and is not 619 // ambiguous. 620 // 621 // This filtering can make an ambiguous result into an unambiguous one, 622 // so try again after filtering out template names. 623 FilterAcceptableTemplateNames(Result); 624 if (!Result.isAmbiguous()) { 625 IsFilteredTemplateName = true; 626 break; 627 } 628 } 629 630 // Diagnose the ambiguity and return an error. 631 return NameClassification::Error(); 632 } 633 634 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) && 635 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 636 // C++ [temp.names]p3: 637 // After name lookup (3.4) finds that a name is a template-name or that 638 // an operator-function-id or a literal- operator-id refers to a set of 639 // overloaded functions any member of which is a function template if 640 // this is followed by a <, the < is always taken as the delimiter of a 641 // template-argument-list and never as the less-than operator. 642 if (!IsFilteredTemplateName) 643 FilterAcceptableTemplateNames(Result); 644 645 if (!Result.empty()) { 646 bool IsFunctionTemplate; 647 TemplateName Template; 648 if (Result.end() - Result.begin() > 1) { 649 IsFunctionTemplate = true; 650 Template = Context.getOverloadedTemplateName(Result.begin(), 651 Result.end()); 652 } else { 653 TemplateDecl *TD 654 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 655 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 656 657 if (SS.isSet() && !SS.isInvalid()) 658 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 659 /*TemplateKeyword=*/false, 660 TD); 661 else 662 Template = TemplateName(TD); 663 } 664 665 if (IsFunctionTemplate) { 666 // Function templates always go through overload resolution, at which 667 // point we'll perform the various checks (e.g., accessibility) we need 668 // to based on which function we selected. 669 Result.suppressDiagnostics(); 670 671 return NameClassification::FunctionTemplate(Template); 672 } 673 674 return NameClassification::TypeTemplate(Template); 675 } 676 } 677 678 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 679 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 680 DiagnoseUseOfDecl(Type, NameLoc); 681 QualType T = Context.getTypeDeclType(Type); 682 return ParsedType::make(T); 683 } 684 685 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 686 if (!Class) { 687 // FIXME: It's unfortunate that we don't have a Type node for handling this. 688 if (ObjCCompatibleAliasDecl *Alias 689 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 690 Class = Alias->getClassInterface(); 691 } 692 693 if (Class) { 694 DiagnoseUseOfDecl(Class, NameLoc); 695 696 if (NextToken.is(tok::period)) { 697 // Interface. <something> is parsed as a property reference expression. 698 // Just return "unknown" as a fall-through for now. 699 Result.suppressDiagnostics(); 700 return NameClassification::Unknown(); 701 } 702 703 QualType T = Context.getObjCInterfaceType(Class); 704 return ParsedType::make(T); 705 } 706 707 if (!Result.empty() && (*Result.begin())->isCXXClassMember()) 708 return BuildPossibleImplicitMemberExpr(SS, Result, 0); 709 710 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 711 return BuildDeclarationNameExpr(SS, Result, ADL); 712} 713 714// Determines the context to return to after temporarily entering a 715// context. This depends in an unnecessarily complicated way on the 716// exact ordering of callbacks from the parser. 717DeclContext *Sema::getContainingDC(DeclContext *DC) { 718 719 // Functions defined inline within classes aren't parsed until we've 720 // finished parsing the top-level class, so the top-level class is 721 // the context we'll need to return to. 722 if (isa<FunctionDecl>(DC)) { 723 DC = DC->getLexicalParent(); 724 725 // A function not defined within a class will always return to its 726 // lexical context. 727 if (!isa<CXXRecordDecl>(DC)) 728 return DC; 729 730 // A C++ inline method/friend is parsed *after* the topmost class 731 // it was declared in is fully parsed ("complete"); the topmost 732 // class is the context we need to return to. 733 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 734 DC = RD; 735 736 // Return the declaration context of the topmost class the inline method is 737 // declared in. 738 return DC; 739 } 740 741 return DC->getLexicalParent(); 742} 743 744void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 745 assert(getContainingDC(DC) == CurContext && 746 "The next DeclContext should be lexically contained in the current one."); 747 CurContext = DC; 748 S->setEntity(DC); 749} 750 751void Sema::PopDeclContext() { 752 assert(CurContext && "DeclContext imbalance!"); 753 754 CurContext = getContainingDC(CurContext); 755 assert(CurContext && "Popped translation unit!"); 756} 757 758/// EnterDeclaratorContext - Used when we must lookup names in the context 759/// of a declarator's nested name specifier. 760/// 761void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 762 // C++0x [basic.lookup.unqual]p13: 763 // A name used in the definition of a static data member of class 764 // X (after the qualified-id of the static member) is looked up as 765 // if the name was used in a member function of X. 766 // C++0x [basic.lookup.unqual]p14: 767 // If a variable member of a namespace is defined outside of the 768 // scope of its namespace then any name used in the definition of 769 // the variable member (after the declarator-id) is looked up as 770 // if the definition of the variable member occurred in its 771 // namespace. 772 // Both of these imply that we should push a scope whose context 773 // is the semantic context of the declaration. We can't use 774 // PushDeclContext here because that context is not necessarily 775 // lexically contained in the current context. Fortunately, 776 // the containing scope should have the appropriate information. 777 778 assert(!S->getEntity() && "scope already has entity"); 779 780#ifndef NDEBUG 781 Scope *Ancestor = S->getParent(); 782 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 783 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 784#endif 785 786 CurContext = DC; 787 S->setEntity(DC); 788} 789 790void Sema::ExitDeclaratorContext(Scope *S) { 791 assert(S->getEntity() == CurContext && "Context imbalance!"); 792 793 // Switch back to the lexical context. The safety of this is 794 // enforced by an assert in EnterDeclaratorContext. 795 Scope *Ancestor = S->getParent(); 796 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 797 CurContext = (DeclContext*) Ancestor->getEntity(); 798 799 // We don't need to do anything with the scope, which is going to 800 // disappear. 801} 802 803/// \brief Determine whether we allow overloading of the function 804/// PrevDecl with another declaration. 805/// 806/// This routine determines whether overloading is possible, not 807/// whether some new function is actually an overload. It will return 808/// true in C++ (where we can always provide overloads) or, as an 809/// extension, in C when the previous function is already an 810/// overloaded function declaration or has the "overloadable" 811/// attribute. 812static bool AllowOverloadingOfFunction(LookupResult &Previous, 813 ASTContext &Context) { 814 if (Context.getLangOptions().CPlusPlus) 815 return true; 816 817 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 818 return true; 819 820 return (Previous.getResultKind() == LookupResult::Found 821 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 822} 823 824/// Add this decl to the scope shadowed decl chains. 825void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 826 // Move up the scope chain until we find the nearest enclosing 827 // non-transparent context. The declaration will be introduced into this 828 // scope. 829 while (S->getEntity() && 830 ((DeclContext *)S->getEntity())->isTransparentContext()) 831 S = S->getParent(); 832 833 // Add scoped declarations into their context, so that they can be 834 // found later. Declarations without a context won't be inserted 835 // into any context. 836 if (AddToContext) 837 CurContext->addDecl(D); 838 839 // Out-of-line definitions shouldn't be pushed into scope in C++. 840 // Out-of-line variable and function definitions shouldn't even in C. 841 if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) && 842 D->isOutOfLine()) 843 return; 844 845 // Template instantiations should also not be pushed into scope. 846 if (isa<FunctionDecl>(D) && 847 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 848 return; 849 850 // If this replaces anything in the current scope, 851 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 852 IEnd = IdResolver.end(); 853 for (; I != IEnd; ++I) { 854 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 855 S->RemoveDecl(*I); 856 IdResolver.RemoveDecl(*I); 857 858 // Should only need to replace one decl. 859 break; 860 } 861 } 862 863 S->AddDecl(D); 864 865 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 866 // Implicitly-generated labels may end up getting generated in an order that 867 // isn't strictly lexical, which breaks name lookup. Be careful to insert 868 // the label at the appropriate place in the identifier chain. 869 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 870 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 871 if (IDC == CurContext) { 872 if (!S->isDeclScope(*I)) 873 continue; 874 } else if (IDC->Encloses(CurContext)) 875 break; 876 } 877 878 IdResolver.InsertDeclAfter(I, D); 879 } else { 880 IdResolver.AddDecl(D); 881 } 882} 883 884bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S, 885 bool ExplicitInstantiationOrSpecialization) { 886 return IdResolver.isDeclInScope(D, Ctx, Context, S, 887 ExplicitInstantiationOrSpecialization); 888} 889 890Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 891 DeclContext *TargetDC = DC->getPrimaryContext(); 892 do { 893 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity()) 894 if (ScopeDC->getPrimaryContext() == TargetDC) 895 return S; 896 } while ((S = S->getParent())); 897 898 return 0; 899} 900 901static bool isOutOfScopePreviousDeclaration(NamedDecl *, 902 DeclContext*, 903 ASTContext&); 904 905/// Filters out lookup results that don't fall within the given scope 906/// as determined by isDeclInScope. 907void Sema::FilterLookupForScope(LookupResult &R, 908 DeclContext *Ctx, Scope *S, 909 bool ConsiderLinkage, 910 bool ExplicitInstantiationOrSpecialization) { 911 LookupResult::Filter F = R.makeFilter(); 912 while (F.hasNext()) { 913 NamedDecl *D = F.next(); 914 915 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization)) 916 continue; 917 918 if (ConsiderLinkage && 919 isOutOfScopePreviousDeclaration(D, Ctx, Context)) 920 continue; 921 922 F.erase(); 923 } 924 925 F.done(); 926} 927 928static bool isUsingDecl(NamedDecl *D) { 929 return isa<UsingShadowDecl>(D) || 930 isa<UnresolvedUsingTypenameDecl>(D) || 931 isa<UnresolvedUsingValueDecl>(D); 932} 933 934/// Removes using shadow declarations from the lookup results. 935static void RemoveUsingDecls(LookupResult &R) { 936 LookupResult::Filter F = R.makeFilter(); 937 while (F.hasNext()) 938 if (isUsingDecl(F.next())) 939 F.erase(); 940 941 F.done(); 942} 943 944/// \brief Check for this common pattern: 945/// @code 946/// class S { 947/// S(const S&); // DO NOT IMPLEMENT 948/// void operator=(const S&); // DO NOT IMPLEMENT 949/// }; 950/// @endcode 951static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 952 // FIXME: Should check for private access too but access is set after we get 953 // the decl here. 954 if (D->doesThisDeclarationHaveABody()) 955 return false; 956 957 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 958 return CD->isCopyConstructor(); 959 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 960 return Method->isCopyAssignmentOperator(); 961 return false; 962} 963 964bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 965 assert(D); 966 967 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 968 return false; 969 970 // Ignore class templates. 971 if (D->getDeclContext()->isDependentContext() || 972 D->getLexicalDeclContext()->isDependentContext()) 973 return false; 974 975 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 976 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 977 return false; 978 979 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 980 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 981 return false; 982 } else { 983 // 'static inline' functions are used in headers; don't warn. 984 if (FD->getStorageClass() == SC_Static && 985 FD->isInlineSpecified()) 986 return false; 987 } 988 989 if (FD->doesThisDeclarationHaveABody() && 990 Context.DeclMustBeEmitted(FD)) 991 return false; 992 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 993 if (!VD->isFileVarDecl() || 994 VD->getType().isConstant(Context) || 995 Context.DeclMustBeEmitted(VD)) 996 return false; 997 998 if (VD->isStaticDataMember() && 999 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1000 return false; 1001 1002 } else { 1003 return false; 1004 } 1005 1006 // Only warn for unused decls internal to the translation unit. 1007 if (D->getLinkage() == ExternalLinkage) 1008 return false; 1009 1010 return true; 1011} 1012 1013void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1014 if (!D) 1015 return; 1016 1017 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1018 const FunctionDecl *First = FD->getFirstDeclaration(); 1019 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1020 return; // First should already be in the vector. 1021 } 1022 1023 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1024 const VarDecl *First = VD->getFirstDeclaration(); 1025 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1026 return; // First should already be in the vector. 1027 } 1028 1029 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1030 UnusedFileScopedDecls.push_back(D); 1031 } 1032 1033static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1034 if (D->isInvalidDecl()) 1035 return false; 1036 1037 if (D->isUsed() || D->hasAttr<UnusedAttr>()) 1038 return false; 1039 1040 if (isa<LabelDecl>(D)) 1041 return true; 1042 1043 // White-list anything that isn't a local variable. 1044 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1045 !D->getDeclContext()->isFunctionOrMethod()) 1046 return false; 1047 1048 // Types of valid local variables should be complete, so this should succeed. 1049 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 1050 1051 // White-list anything with an __attribute__((unused)) type. 1052 QualType Ty = VD->getType(); 1053 1054 // Only look at the outermost level of typedef. 1055 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) { 1056 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1057 return false; 1058 } 1059 1060 // If we failed to complete the type for some reason, or if the type is 1061 // dependent, don't diagnose the variable. 1062 if (Ty->isIncompleteType() || Ty->isDependentType()) 1063 return false; 1064 1065 if (const TagType *TT = Ty->getAs<TagType>()) { 1066 const TagDecl *Tag = TT->getDecl(); 1067 if (Tag->hasAttr<UnusedAttr>()) 1068 return false; 1069 1070 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1071 // FIXME: Checking for the presence of a user-declared constructor 1072 // isn't completely accurate; we'd prefer to check that the initializer 1073 // has no side effects. 1074 if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor()) 1075 return false; 1076 } 1077 } 1078 1079 // TODO: __attribute__((unused)) templates? 1080 } 1081 1082 return true; 1083} 1084 1085static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1086 FixItHint &Hint) { 1087 if (isa<LabelDecl>(D)) { 1088 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1089 tok::colon, Ctx.getSourceManager(), Ctx.getLangOptions(), true); 1090 if (AfterColon.isInvalid()) 1091 return; 1092 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1093 getCharRange(D->getLocStart(), AfterColon)); 1094 } 1095 return; 1096} 1097 1098/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1099/// unless they are marked attr(unused). 1100void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1101 FixItHint Hint; 1102 if (!ShouldDiagnoseUnusedDecl(D)) 1103 return; 1104 1105 GenerateFixForUnusedDecl(D, Context, Hint); 1106 1107 unsigned DiagID; 1108 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1109 DiagID = diag::warn_unused_exception_param; 1110 else if (isa<LabelDecl>(D)) 1111 DiagID = diag::warn_unused_label; 1112 else 1113 DiagID = diag::warn_unused_variable; 1114 1115 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1116} 1117 1118static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1119 // Verify that we have no forward references left. If so, there was a goto 1120 // or address of a label taken, but no definition of it. Label fwd 1121 // definitions are indicated with a null substmt. 1122 if (L->getStmt() == 0) 1123 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1124} 1125 1126void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1127 if (S->decl_empty()) return; 1128 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1129 "Scope shouldn't contain decls!"); 1130 1131 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 1132 I != E; ++I) { 1133 Decl *TmpD = (*I); 1134 assert(TmpD && "This decl didn't get pushed??"); 1135 1136 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1137 NamedDecl *D = cast<NamedDecl>(TmpD); 1138 1139 if (!D->getDeclName()) continue; 1140 1141 // Diagnose unused variables in this scope. 1142 if (!S->hasErrorOccurred()) 1143 DiagnoseUnusedDecl(D); 1144 1145 // If this was a forward reference to a label, verify it was defined. 1146 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1147 CheckPoppedLabel(LD, *this); 1148 1149 // Remove this name from our lexical scope. 1150 IdResolver.RemoveDecl(D); 1151 } 1152} 1153 1154/// \brief Look for an Objective-C class in the translation unit. 1155/// 1156/// \param Id The name of the Objective-C class we're looking for. If 1157/// typo-correction fixes this name, the Id will be updated 1158/// to the fixed name. 1159/// 1160/// \param IdLoc The location of the name in the translation unit. 1161/// 1162/// \param TypoCorrection If true, this routine will attempt typo correction 1163/// if there is no class with the given name. 1164/// 1165/// \returns The declaration of the named Objective-C class, or NULL if the 1166/// class could not be found. 1167ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1168 SourceLocation IdLoc, 1169 bool DoTypoCorrection) { 1170 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1171 // creation from this context. 1172 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1173 1174 if (!IDecl && DoTypoCorrection) { 1175 // Perform typo correction at the given location, but only if we 1176 // find an Objective-C class name. 1177 TypoCorrection C; 1178 if ((C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1179 TUScope, NULL, NULL, false, CTC_NoKeywords)) && 1180 (IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>())) { 1181 Diag(IdLoc, diag::err_undef_interface_suggest) 1182 << Id << IDecl->getDeclName() 1183 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString()); 1184 Diag(IDecl->getLocation(), diag::note_previous_decl) 1185 << IDecl->getDeclName(); 1186 1187 Id = IDecl->getIdentifier(); 1188 } 1189 } 1190 1191 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1192} 1193 1194/// getNonFieldDeclScope - Retrieves the innermost scope, starting 1195/// from S, where a non-field would be declared. This routine copes 1196/// with the difference between C and C++ scoping rules in structs and 1197/// unions. For example, the following code is well-formed in C but 1198/// ill-formed in C++: 1199/// @code 1200/// struct S6 { 1201/// enum { BAR } e; 1202/// }; 1203/// 1204/// void test_S6() { 1205/// struct S6 a; 1206/// a.e = BAR; 1207/// } 1208/// @endcode 1209/// For the declaration of BAR, this routine will return a different 1210/// scope. The scope S will be the scope of the unnamed enumeration 1211/// within S6. In C++, this routine will return the scope associated 1212/// with S6, because the enumeration's scope is a transparent 1213/// context but structures can contain non-field names. In C, this 1214/// routine will return the translation unit scope, since the 1215/// enumeration's scope is a transparent context and structures cannot 1216/// contain non-field names. 1217Scope *Sema::getNonFieldDeclScope(Scope *S) { 1218 while (((S->getFlags() & Scope::DeclScope) == 0) || 1219 (S->getEntity() && 1220 ((DeclContext *)S->getEntity())->isTransparentContext()) || 1221 (S->isClassScope() && !getLangOptions().CPlusPlus)) 1222 S = S->getParent(); 1223 return S; 1224} 1225 1226/// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1227/// file scope. lazily create a decl for it. ForRedeclaration is true 1228/// if we're creating this built-in in anticipation of redeclaring the 1229/// built-in. 1230NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1231 Scope *S, bool ForRedeclaration, 1232 SourceLocation Loc) { 1233 Builtin::ID BID = (Builtin::ID)bid; 1234 1235 ASTContext::GetBuiltinTypeError Error; 1236 QualType R = Context.GetBuiltinType(BID, Error); 1237 switch (Error) { 1238 case ASTContext::GE_None: 1239 // Okay 1240 break; 1241 1242 case ASTContext::GE_Missing_stdio: 1243 if (ForRedeclaration) 1244 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1245 << Context.BuiltinInfo.GetName(BID); 1246 return 0; 1247 1248 case ASTContext::GE_Missing_setjmp: 1249 if (ForRedeclaration) 1250 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1251 << Context.BuiltinInfo.GetName(BID); 1252 return 0; 1253 } 1254 1255 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1256 Diag(Loc, diag::ext_implicit_lib_function_decl) 1257 << Context.BuiltinInfo.GetName(BID) 1258 << R; 1259 if (Context.BuiltinInfo.getHeaderName(BID) && 1260 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1261 != Diagnostic::Ignored) 1262 Diag(Loc, diag::note_please_include_header) 1263 << Context.BuiltinInfo.getHeaderName(BID) 1264 << Context.BuiltinInfo.GetName(BID); 1265 } 1266 1267 FunctionDecl *New = FunctionDecl::Create(Context, 1268 Context.getTranslationUnitDecl(), 1269 Loc, Loc, II, R, /*TInfo=*/0, 1270 SC_Extern, 1271 SC_None, false, 1272 /*hasPrototype=*/true); 1273 New->setImplicit(); 1274 1275 // Create Decl objects for each parameter, adding them to the 1276 // FunctionDecl. 1277 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1278 SmallVector<ParmVarDecl*, 16> Params; 1279 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) { 1280 ParmVarDecl *parm = 1281 ParmVarDecl::Create(Context, New, SourceLocation(), 1282 SourceLocation(), 0, 1283 FT->getArgType(i), /*TInfo=*/0, 1284 SC_None, SC_None, 0); 1285 parm->setScopeInfo(0, i); 1286 Params.push_back(parm); 1287 } 1288 New->setParams(Params.data(), Params.size()); 1289 } 1290 1291 AddKnownFunctionAttributes(New); 1292 1293 // TUScope is the translation-unit scope to insert this function into. 1294 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1295 // relate Scopes to DeclContexts, and probably eliminate CurContext 1296 // entirely, but we're not there yet. 1297 DeclContext *SavedContext = CurContext; 1298 CurContext = Context.getTranslationUnitDecl(); 1299 PushOnScopeChains(New, TUScope); 1300 CurContext = SavedContext; 1301 return New; 1302} 1303 1304/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1305/// same name and scope as a previous declaration 'Old'. Figure out 1306/// how to resolve this situation, merging decls or emitting 1307/// diagnostics as appropriate. If there was an error, set New to be invalid. 1308/// 1309void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1310 // If the new decl is known invalid already, don't bother doing any 1311 // merging checks. 1312 if (New->isInvalidDecl()) return; 1313 1314 // Allow multiple definitions for ObjC built-in typedefs. 1315 // FIXME: Verify the underlying types are equivalent! 1316 if (getLangOptions().ObjC1) { 1317 const IdentifierInfo *TypeID = New->getIdentifier(); 1318 switch (TypeID->getLength()) { 1319 default: break; 1320 case 2: 1321 if (!TypeID->isStr("id")) 1322 break; 1323 Context.setObjCIdRedefinitionType(New->getUnderlyingType()); 1324 // Install the built-in type for 'id', ignoring the current definition. 1325 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1326 return; 1327 case 5: 1328 if (!TypeID->isStr("Class")) 1329 break; 1330 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1331 // Install the built-in type for 'Class', ignoring the current definition. 1332 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1333 return; 1334 case 3: 1335 if (!TypeID->isStr("SEL")) 1336 break; 1337 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1338 // Install the built-in type for 'SEL', ignoring the current definition. 1339 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1340 return; 1341 } 1342 // Fall through - the typedef name was not a builtin type. 1343 } 1344 1345 // Verify the old decl was also a type. 1346 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1347 if (!Old) { 1348 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1349 << New->getDeclName(); 1350 1351 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1352 if (OldD->getLocation().isValid()) 1353 Diag(OldD->getLocation(), diag::note_previous_definition); 1354 1355 return New->setInvalidDecl(); 1356 } 1357 1358 // If the old declaration is invalid, just give up here. 1359 if (Old->isInvalidDecl()) 1360 return New->setInvalidDecl(); 1361 1362 // Determine the "old" type we'll use for checking and diagnostics. 1363 QualType OldType; 1364 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1365 OldType = OldTypedef->getUnderlyingType(); 1366 else 1367 OldType = Context.getTypeDeclType(Old); 1368 1369 // If the typedef types are not identical, reject them in all languages and 1370 // with any extensions enabled. 1371 1372 if (OldType != New->getUnderlyingType() && 1373 Context.getCanonicalType(OldType) != 1374 Context.getCanonicalType(New->getUnderlyingType())) { 1375 int Kind = 0; 1376 if (isa<TypeAliasDecl>(Old)) 1377 Kind = 1; 1378 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1379 << Kind << New->getUnderlyingType() << OldType; 1380 if (Old->getLocation().isValid()) 1381 Diag(Old->getLocation(), diag::note_previous_definition); 1382 return New->setInvalidDecl(); 1383 } 1384 1385 // The types match. Link up the redeclaration chain if the old 1386 // declaration was a typedef. 1387 // FIXME: this is a potential source of weirdness if the type 1388 // spellings don't match exactly. 1389 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) 1390 New->setPreviousDeclaration(Typedef); 1391 1392 if (getLangOptions().Microsoft) 1393 return; 1394 1395 if (getLangOptions().CPlusPlus) { 1396 // C++ [dcl.typedef]p2: 1397 // In a given non-class scope, a typedef specifier can be used to 1398 // redefine the name of any type declared in that scope to refer 1399 // to the type to which it already refers. 1400 if (!isa<CXXRecordDecl>(CurContext)) 1401 return; 1402 1403 // C++0x [dcl.typedef]p4: 1404 // In a given class scope, a typedef specifier can be used to redefine 1405 // any class-name declared in that scope that is not also a typedef-name 1406 // to refer to the type to which it already refers. 1407 // 1408 // This wording came in via DR424, which was a correction to the 1409 // wording in DR56, which accidentally banned code like: 1410 // 1411 // struct S { 1412 // typedef struct A { } A; 1413 // }; 1414 // 1415 // in the C++03 standard. We implement the C++0x semantics, which 1416 // allow the above but disallow 1417 // 1418 // struct S { 1419 // typedef int I; 1420 // typedef int I; 1421 // }; 1422 // 1423 // since that was the intent of DR56. 1424 if (!isa<TypedefNameDecl>(Old)) 1425 return; 1426 1427 Diag(New->getLocation(), diag::err_redefinition) 1428 << New->getDeclName(); 1429 Diag(Old->getLocation(), diag::note_previous_definition); 1430 return New->setInvalidDecl(); 1431 } 1432 1433 // If we have a redefinition of a typedef in C, emit a warning. This warning 1434 // is normally mapped to an error, but can be controlled with 1435 // -Wtypedef-redefinition. If either the original or the redefinition is 1436 // in a system header, don't emit this for compatibility with GCC. 1437 if (getDiagnostics().getSuppressSystemWarnings() && 1438 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1439 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1440 return; 1441 1442 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1443 << New->getDeclName(); 1444 Diag(Old->getLocation(), diag::note_previous_definition); 1445 return; 1446} 1447 1448/// DeclhasAttr - returns true if decl Declaration already has the target 1449/// attribute. 1450static bool 1451DeclHasAttr(const Decl *D, const Attr *A) { 1452 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1453 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 1454 if ((*i)->getKind() == A->getKind()) { 1455 // FIXME: Don't hardcode this check 1456 if (OA && isa<OwnershipAttr>(*i)) 1457 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 1458 return true; 1459 } 1460 1461 return false; 1462} 1463 1464/// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 1465static void mergeDeclAttributes(Decl *newDecl, const Decl *oldDecl, 1466 ASTContext &C, bool mergeDeprecation = true) { 1467 if (!oldDecl->hasAttrs()) 1468 return; 1469 1470 bool foundAny = newDecl->hasAttrs(); 1471 1472 // Ensure that any moving of objects within the allocated map is done before 1473 // we process them. 1474 if (!foundAny) newDecl->setAttrs(AttrVec()); 1475 1476 for (specific_attr_iterator<InheritableAttr> 1477 i = oldDecl->specific_attr_begin<InheritableAttr>(), 1478 e = oldDecl->specific_attr_end<InheritableAttr>(); i != e; ++i) { 1479 // Ignore deprecated and unavailable attributes if requested. 1480 if (!mergeDeprecation && 1481 (isa<DeprecatedAttr>(*i) || isa<UnavailableAttr>(*i))) 1482 continue; 1483 1484 if (!DeclHasAttr(newDecl, *i)) { 1485 InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(C)); 1486 newAttr->setInherited(true); 1487 newDecl->addAttr(newAttr); 1488 foundAny = true; 1489 } 1490 } 1491 1492 if (!foundAny) newDecl->dropAttrs(); 1493} 1494 1495/// mergeParamDeclAttributes - Copy attributes from the old parameter 1496/// to the new one. 1497static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 1498 const ParmVarDecl *oldDecl, 1499 ASTContext &C) { 1500 if (!oldDecl->hasAttrs()) 1501 return; 1502 1503 bool foundAny = newDecl->hasAttrs(); 1504 1505 // Ensure that any moving of objects within the allocated map is 1506 // done before we process them. 1507 if (!foundAny) newDecl->setAttrs(AttrVec()); 1508 1509 for (specific_attr_iterator<InheritableParamAttr> 1510 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 1511 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 1512 if (!DeclHasAttr(newDecl, *i)) { 1513 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C)); 1514 newAttr->setInherited(true); 1515 newDecl->addAttr(newAttr); 1516 foundAny = true; 1517 } 1518 } 1519 1520 if (!foundAny) newDecl->dropAttrs(); 1521} 1522 1523namespace { 1524 1525/// Used in MergeFunctionDecl to keep track of function parameters in 1526/// C. 1527struct GNUCompatibleParamWarning { 1528 ParmVarDecl *OldParm; 1529 ParmVarDecl *NewParm; 1530 QualType PromotedType; 1531}; 1532 1533} 1534 1535/// getSpecialMember - get the special member enum for a method. 1536Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 1537 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 1538 if (Ctor->isDefaultConstructor()) 1539 return Sema::CXXDefaultConstructor; 1540 1541 if (Ctor->isCopyConstructor()) 1542 return Sema::CXXCopyConstructor; 1543 1544 if (Ctor->isMoveConstructor()) 1545 return Sema::CXXMoveConstructor; 1546 } else if (isa<CXXDestructorDecl>(MD)) { 1547 return Sema::CXXDestructor; 1548 } else if (MD->isCopyAssignmentOperator()) { 1549 return Sema::CXXCopyAssignment; 1550 } 1551 1552 return Sema::CXXInvalid; 1553} 1554 1555/// canRedefineFunction - checks if a function can be redefined. Currently, 1556/// only extern inline functions can be redefined, and even then only in 1557/// GNU89 mode. 1558static bool canRedefineFunction(const FunctionDecl *FD, 1559 const LangOptions& LangOpts) { 1560 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 1561 !LangOpts.CPlusPlus && 1562 FD->isInlineSpecified() && 1563 FD->getStorageClass() == SC_Extern); 1564} 1565 1566/// MergeFunctionDecl - We just parsed a function 'New' from 1567/// declarator D which has the same name and scope as a previous 1568/// declaration 'Old'. Figure out how to resolve this situation, 1569/// merging decls or emitting diagnostics as appropriate. 1570/// 1571/// In C++, New and Old must be declarations that are not 1572/// overloaded. Use IsOverload to determine whether New and Old are 1573/// overloaded, and to select the Old declaration that New should be 1574/// merged with. 1575/// 1576/// Returns true if there was an error, false otherwise. 1577bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) { 1578 // Verify the old decl was also a function. 1579 FunctionDecl *Old = 0; 1580 if (FunctionTemplateDecl *OldFunctionTemplate 1581 = dyn_cast<FunctionTemplateDecl>(OldD)) 1582 Old = OldFunctionTemplate->getTemplatedDecl(); 1583 else 1584 Old = dyn_cast<FunctionDecl>(OldD); 1585 if (!Old) { 1586 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 1587 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 1588 Diag(Shadow->getTargetDecl()->getLocation(), 1589 diag::note_using_decl_target); 1590 Diag(Shadow->getUsingDecl()->getLocation(), 1591 diag::note_using_decl) << 0; 1592 return true; 1593 } 1594 1595 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1596 << New->getDeclName(); 1597 Diag(OldD->getLocation(), diag::note_previous_definition); 1598 return true; 1599 } 1600 1601 // Determine whether the previous declaration was a definition, 1602 // implicit declaration, or a declaration. 1603 diag::kind PrevDiag; 1604 if (Old->isThisDeclarationADefinition()) 1605 PrevDiag = diag::note_previous_definition; 1606 else if (Old->isImplicit()) 1607 PrevDiag = diag::note_previous_implicit_declaration; 1608 else 1609 PrevDiag = diag::note_previous_declaration; 1610 1611 QualType OldQType = Context.getCanonicalType(Old->getType()); 1612 QualType NewQType = Context.getCanonicalType(New->getType()); 1613 1614 // Don't complain about this if we're in GNU89 mode and the old function 1615 // is an extern inline function. 1616 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 1617 New->getStorageClass() == SC_Static && 1618 Old->getStorageClass() != SC_Static && 1619 !canRedefineFunction(Old, getLangOptions())) { 1620 if (getLangOptions().Microsoft) { 1621 Diag(New->getLocation(), diag::warn_static_non_static) << New; 1622 Diag(Old->getLocation(), PrevDiag); 1623 } else { 1624 Diag(New->getLocation(), diag::err_static_non_static) << New; 1625 Diag(Old->getLocation(), PrevDiag); 1626 return true; 1627 } 1628 } 1629 1630 // If a function is first declared with a calling convention, but is 1631 // later declared or defined without one, the second decl assumes the 1632 // calling convention of the first. 1633 // 1634 // For the new decl, we have to look at the NON-canonical type to tell the 1635 // difference between a function that really doesn't have a calling 1636 // convention and one that is declared cdecl. That's because in 1637 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away 1638 // because it is the default calling convention. 1639 // 1640 // Note also that we DO NOT return at this point, because we still have 1641 // other tests to run. 1642 const FunctionType *OldType = cast<FunctionType>(OldQType); 1643 const FunctionType *NewType = New->getType()->getAs<FunctionType>(); 1644 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 1645 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 1646 bool RequiresAdjustment = false; 1647 if (OldTypeInfo.getCC() != CC_Default && 1648 NewTypeInfo.getCC() == CC_Default) { 1649 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 1650 RequiresAdjustment = true; 1651 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(), 1652 NewTypeInfo.getCC())) { 1653 // Calling conventions really aren't compatible, so complain. 1654 Diag(New->getLocation(), diag::err_cconv_change) 1655 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 1656 << (OldTypeInfo.getCC() == CC_Default) 1657 << (OldTypeInfo.getCC() == CC_Default ? "" : 1658 FunctionType::getNameForCallConv(OldTypeInfo.getCC())); 1659 Diag(Old->getLocation(), diag::note_previous_declaration); 1660 return true; 1661 } 1662 1663 // FIXME: diagnose the other way around? 1664 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 1665 NewTypeInfo = NewTypeInfo.withNoReturn(true); 1666 RequiresAdjustment = true; 1667 } 1668 1669 // Merge regparm attribute. 1670 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 1671 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 1672 if (NewTypeInfo.getHasRegParm()) { 1673 Diag(New->getLocation(), diag::err_regparm_mismatch) 1674 << NewType->getRegParmType() 1675 << OldType->getRegParmType(); 1676 Diag(Old->getLocation(), diag::note_previous_declaration); 1677 return true; 1678 } 1679 1680 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 1681 RequiresAdjustment = true; 1682 } 1683 1684 if (RequiresAdjustment) { 1685 NewType = Context.adjustFunctionType(NewType, NewTypeInfo); 1686 New->setType(QualType(NewType, 0)); 1687 NewQType = Context.getCanonicalType(New->getType()); 1688 } 1689 1690 if (getLangOptions().CPlusPlus) { 1691 // (C++98 13.1p2): 1692 // Certain function declarations cannot be overloaded: 1693 // -- Function declarations that differ only in the return type 1694 // cannot be overloaded. 1695 QualType OldReturnType = OldType->getResultType(); 1696 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType(); 1697 QualType ResQT; 1698 if (OldReturnType != NewReturnType) { 1699 if (NewReturnType->isObjCObjectPointerType() 1700 && OldReturnType->isObjCObjectPointerType()) 1701 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 1702 if (ResQT.isNull()) { 1703 if (New->isCXXClassMember() && New->isOutOfLine()) 1704 Diag(New->getLocation(), 1705 diag::err_member_def_does_not_match_ret_type) << New; 1706 else 1707 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 1708 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1709 return true; 1710 } 1711 else 1712 NewQType = ResQT; 1713 } 1714 1715 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 1716 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 1717 if (OldMethod && NewMethod) { 1718 // Preserve triviality. 1719 NewMethod->setTrivial(OldMethod->isTrivial()); 1720 1721 // MSVC allows explicit template specialization at class scope: 1722 // 2 CXMethodDecls referring to the same function will be injected. 1723 // We don't want a redeclartion error. 1724 bool IsClassScopeExplicitSpecialization = 1725 OldMethod->isFunctionTemplateSpecialization() && 1726 NewMethod->isFunctionTemplateSpecialization(); 1727 bool isFriend = NewMethod->getFriendObjectKind(); 1728 1729 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 1730 !IsClassScopeExplicitSpecialization) { 1731 // -- Member function declarations with the same name and the 1732 // same parameter types cannot be overloaded if any of them 1733 // is a static member function declaration. 1734 if (OldMethod->isStatic() || NewMethod->isStatic()) { 1735 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 1736 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1737 return true; 1738 } 1739 1740 // C++ [class.mem]p1: 1741 // [...] A member shall not be declared twice in the 1742 // member-specification, except that a nested class or member 1743 // class template can be declared and then later defined. 1744 unsigned NewDiag; 1745 if (isa<CXXConstructorDecl>(OldMethod)) 1746 NewDiag = diag::err_constructor_redeclared; 1747 else if (isa<CXXDestructorDecl>(NewMethod)) 1748 NewDiag = diag::err_destructor_redeclared; 1749 else if (isa<CXXConversionDecl>(NewMethod)) 1750 NewDiag = diag::err_conv_function_redeclared; 1751 else 1752 NewDiag = diag::err_member_redeclared; 1753 1754 Diag(New->getLocation(), NewDiag); 1755 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1756 1757 // Complain if this is an explicit declaration of a special 1758 // member that was initially declared implicitly. 1759 // 1760 // As an exception, it's okay to befriend such methods in order 1761 // to permit the implicit constructor/destructor/operator calls. 1762 } else if (OldMethod->isImplicit()) { 1763 if (isFriend) { 1764 NewMethod->setImplicit(); 1765 } else { 1766 Diag(NewMethod->getLocation(), 1767 diag::err_definition_of_implicitly_declared_member) 1768 << New << getSpecialMember(OldMethod); 1769 return true; 1770 } 1771 } else if (OldMethod->isExplicitlyDefaulted()) { 1772 Diag(NewMethod->getLocation(), 1773 diag::err_definition_of_explicitly_defaulted_member) 1774 << getSpecialMember(OldMethod); 1775 return true; 1776 } 1777 } 1778 1779 // (C++98 8.3.5p3): 1780 // All declarations for a function shall agree exactly in both the 1781 // return type and the parameter-type-list. 1782 // We also want to respect all the extended bits except noreturn. 1783 1784 // noreturn should now match unless the old type info didn't have it. 1785 QualType OldQTypeForComparison = OldQType; 1786 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 1787 assert(OldQType == QualType(OldType, 0)); 1788 const FunctionType *OldTypeForComparison 1789 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 1790 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 1791 assert(OldQTypeForComparison.isCanonical()); 1792 } 1793 1794 if (OldQTypeForComparison == NewQType) 1795 return MergeCompatibleFunctionDecls(New, Old); 1796 1797 // Fall through for conflicting redeclarations and redefinitions. 1798 } 1799 1800 // C: Function types need to be compatible, not identical. This handles 1801 // duplicate function decls like "void f(int); void f(enum X);" properly. 1802 if (!getLangOptions().CPlusPlus && 1803 Context.typesAreCompatible(OldQType, NewQType)) { 1804 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 1805 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 1806 const FunctionProtoType *OldProto = 0; 1807 if (isa<FunctionNoProtoType>(NewFuncType) && 1808 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 1809 // The old declaration provided a function prototype, but the 1810 // new declaration does not. Merge in the prototype. 1811 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 1812 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 1813 OldProto->arg_type_end()); 1814 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 1815 ParamTypes.data(), ParamTypes.size(), 1816 OldProto->getExtProtoInfo()); 1817 New->setType(NewQType); 1818 New->setHasInheritedPrototype(); 1819 1820 // Synthesize a parameter for each argument type. 1821 SmallVector<ParmVarDecl*, 16> Params; 1822 for (FunctionProtoType::arg_type_iterator 1823 ParamType = OldProto->arg_type_begin(), 1824 ParamEnd = OldProto->arg_type_end(); 1825 ParamType != ParamEnd; ++ParamType) { 1826 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 1827 SourceLocation(), 1828 SourceLocation(), 0, 1829 *ParamType, /*TInfo=*/0, 1830 SC_None, SC_None, 1831 0); 1832 Param->setScopeInfo(0, Params.size()); 1833 Param->setImplicit(); 1834 Params.push_back(Param); 1835 } 1836 1837 New->setParams(Params.data(), Params.size()); 1838 } 1839 1840 return MergeCompatibleFunctionDecls(New, Old); 1841 } 1842 1843 // GNU C permits a K&R definition to follow a prototype declaration 1844 // if the declared types of the parameters in the K&R definition 1845 // match the types in the prototype declaration, even when the 1846 // promoted types of the parameters from the K&R definition differ 1847 // from the types in the prototype. GCC then keeps the types from 1848 // the prototype. 1849 // 1850 // If a variadic prototype is followed by a non-variadic K&R definition, 1851 // the K&R definition becomes variadic. This is sort of an edge case, but 1852 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 1853 // C99 6.9.1p8. 1854 if (!getLangOptions().CPlusPlus && 1855 Old->hasPrototype() && !New->hasPrototype() && 1856 New->getType()->getAs<FunctionProtoType>() && 1857 Old->getNumParams() == New->getNumParams()) { 1858 SmallVector<QualType, 16> ArgTypes; 1859 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 1860 const FunctionProtoType *OldProto 1861 = Old->getType()->getAs<FunctionProtoType>(); 1862 const FunctionProtoType *NewProto 1863 = New->getType()->getAs<FunctionProtoType>(); 1864 1865 // Determine whether this is the GNU C extension. 1866 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 1867 NewProto->getResultType()); 1868 bool LooseCompatible = !MergedReturn.isNull(); 1869 for (unsigned Idx = 0, End = Old->getNumParams(); 1870 LooseCompatible && Idx != End; ++Idx) { 1871 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 1872 ParmVarDecl *NewParm = New->getParamDecl(Idx); 1873 if (Context.typesAreCompatible(OldParm->getType(), 1874 NewProto->getArgType(Idx))) { 1875 ArgTypes.push_back(NewParm->getType()); 1876 } else if (Context.typesAreCompatible(OldParm->getType(), 1877 NewParm->getType(), 1878 /*CompareUnqualified=*/true)) { 1879 GNUCompatibleParamWarning Warn 1880 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 1881 Warnings.push_back(Warn); 1882 ArgTypes.push_back(NewParm->getType()); 1883 } else 1884 LooseCompatible = false; 1885 } 1886 1887 if (LooseCompatible) { 1888 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 1889 Diag(Warnings[Warn].NewParm->getLocation(), 1890 diag::ext_param_promoted_not_compatible_with_prototype) 1891 << Warnings[Warn].PromotedType 1892 << Warnings[Warn].OldParm->getType(); 1893 if (Warnings[Warn].OldParm->getLocation().isValid()) 1894 Diag(Warnings[Warn].OldParm->getLocation(), 1895 diag::note_previous_declaration); 1896 } 1897 1898 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0], 1899 ArgTypes.size(), 1900 OldProto->getExtProtoInfo())); 1901 return MergeCompatibleFunctionDecls(New, Old); 1902 } 1903 1904 // Fall through to diagnose conflicting types. 1905 } 1906 1907 // A function that has already been declared has been redeclared or defined 1908 // with a different type- show appropriate diagnostic 1909 if (unsigned BuiltinID = Old->getBuiltinID()) { 1910 // The user has declared a builtin function with an incompatible 1911 // signature. 1912 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 1913 // The function the user is redeclaring is a library-defined 1914 // function like 'malloc' or 'printf'. Warn about the 1915 // redeclaration, then pretend that we don't know about this 1916 // library built-in. 1917 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 1918 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 1919 << Old << Old->getType(); 1920 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 1921 Old->setInvalidDecl(); 1922 return false; 1923 } 1924 1925 PrevDiag = diag::note_previous_builtin_declaration; 1926 } 1927 1928 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 1929 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1930 return true; 1931} 1932 1933/// \brief Completes the merge of two function declarations that are 1934/// known to be compatible. 1935/// 1936/// This routine handles the merging of attributes and other 1937/// properties of function declarations form the old declaration to 1938/// the new declaration, once we know that New is in fact a 1939/// redeclaration of Old. 1940/// 1941/// \returns false 1942bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) { 1943 // Merge the attributes 1944 mergeDeclAttributes(New, Old, Context); 1945 1946 // Merge the storage class. 1947 if (Old->getStorageClass() != SC_Extern && 1948 Old->getStorageClass() != SC_None) 1949 New->setStorageClass(Old->getStorageClass()); 1950 1951 // Merge "pure" flag. 1952 if (Old->isPure()) 1953 New->setPure(); 1954 1955 // Merge attributes from the parameters. These can mismatch with K&R 1956 // declarations. 1957 if (New->getNumParams() == Old->getNumParams()) 1958 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 1959 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 1960 Context); 1961 1962 if (getLangOptions().CPlusPlus) 1963 return MergeCXXFunctionDecl(New, Old); 1964 1965 return false; 1966} 1967 1968 1969void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 1970 const ObjCMethodDecl *oldMethod) { 1971 // We don't want to merge unavailable and deprecated attributes 1972 // except from interface to implementation. 1973 bool mergeDeprecation = isa<ObjCImplDecl>(newMethod->getDeclContext()); 1974 1975 // Merge the attributes. 1976 mergeDeclAttributes(newMethod, oldMethod, Context, mergeDeprecation); 1977 1978 // Merge attributes from the parameters. 1979 for (ObjCMethodDecl::param_iterator oi = oldMethod->param_begin(), 1980 ni = newMethod->param_begin(), ne = newMethod->param_end(); 1981 ni != ne; ++ni, ++oi) 1982 mergeParamDeclAttributes(*ni, *oi, Context); 1983 1984 CheckObjCMethodOverride(newMethod, oldMethod, true); 1985} 1986 1987/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 1988/// scope as a previous declaration 'Old'. Figure out how to merge their types, 1989/// emitting diagnostics as appropriate. 1990/// 1991/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 1992/// to here in AddInitializerToDecl and AddCXXDirectInitializerToDecl. We can't 1993/// check them before the initializer is attached. 1994/// 1995void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) { 1996 if (New->isInvalidDecl() || Old->isInvalidDecl()) 1997 return; 1998 1999 QualType MergedT; 2000 if (getLangOptions().CPlusPlus) { 2001 AutoType *AT = New->getType()->getContainedAutoType(); 2002 if (AT && !AT->isDeduced()) { 2003 // We don't know what the new type is until the initializer is attached. 2004 return; 2005 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2006 // These could still be something that needs exception specs checked. 2007 return MergeVarDeclExceptionSpecs(New, Old); 2008 } 2009 // C++ [basic.link]p10: 2010 // [...] the types specified by all declarations referring to a given 2011 // object or function shall be identical, except that declarations for an 2012 // array object can specify array types that differ by the presence or 2013 // absence of a major array bound (8.3.4). 2014 else if (Old->getType()->isIncompleteArrayType() && 2015 New->getType()->isArrayType()) { 2016 CanQual<ArrayType> OldArray 2017 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 2018 CanQual<ArrayType> NewArray 2019 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 2020 if (OldArray->getElementType() == NewArray->getElementType()) 2021 MergedT = New->getType(); 2022 } else if (Old->getType()->isArrayType() && 2023 New->getType()->isIncompleteArrayType()) { 2024 CanQual<ArrayType> OldArray 2025 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 2026 CanQual<ArrayType> NewArray 2027 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 2028 if (OldArray->getElementType() == NewArray->getElementType()) 2029 MergedT = Old->getType(); 2030 } else if (New->getType()->isObjCObjectPointerType() 2031 && Old->getType()->isObjCObjectPointerType()) { 2032 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2033 Old->getType()); 2034 } 2035 } else { 2036 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2037 } 2038 if (MergedT.isNull()) { 2039 Diag(New->getLocation(), diag::err_redefinition_different_type) 2040 << New->getDeclName(); 2041 Diag(Old->getLocation(), diag::note_previous_definition); 2042 return New->setInvalidDecl(); 2043 } 2044 New->setType(MergedT); 2045} 2046 2047/// MergeVarDecl - We just parsed a variable 'New' which has the same name 2048/// and scope as a previous declaration 'Old'. Figure out how to resolve this 2049/// situation, merging decls or emitting diagnostics as appropriate. 2050/// 2051/// Tentative definition rules (C99 6.9.2p2) are checked by 2052/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2053/// definitions here, since the initializer hasn't been attached. 2054/// 2055void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2056 // If the new decl is already invalid, don't do any other checking. 2057 if (New->isInvalidDecl()) 2058 return; 2059 2060 // Verify the old decl was also a variable. 2061 VarDecl *Old = 0; 2062 if (!Previous.isSingleResult() || 2063 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 2064 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2065 << New->getDeclName(); 2066 Diag(Previous.getRepresentativeDecl()->getLocation(), 2067 diag::note_previous_definition); 2068 return New->setInvalidDecl(); 2069 } 2070 2071 // C++ [class.mem]p1: 2072 // A member shall not be declared twice in the member-specification [...] 2073 // 2074 // Here, we need only consider static data members. 2075 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 2076 Diag(New->getLocation(), diag::err_duplicate_member) 2077 << New->getIdentifier(); 2078 Diag(Old->getLocation(), diag::note_previous_declaration); 2079 New->setInvalidDecl(); 2080 } 2081 2082 mergeDeclAttributes(New, Old, Context); 2083 // Warn if an already-declared variable is made a weak_import in a subsequent declaration 2084 if (New->getAttr<WeakImportAttr>() && 2085 Old->getStorageClass() == SC_None && 2086 !Old->getAttr<WeakImportAttr>()) { 2087 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 2088 Diag(Old->getLocation(), diag::note_previous_definition); 2089 // Remove weak_import attribute on new declaration. 2090 New->dropAttr<WeakImportAttr>(); 2091 } 2092 2093 // Merge the types. 2094 MergeVarDeclTypes(New, Old); 2095 if (New->isInvalidDecl()) 2096 return; 2097 2098 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 2099 if (New->getStorageClass() == SC_Static && 2100 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) { 2101 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 2102 Diag(Old->getLocation(), diag::note_previous_definition); 2103 return New->setInvalidDecl(); 2104 } 2105 // C99 6.2.2p4: 2106 // For an identifier declared with the storage-class specifier 2107 // extern in a scope in which a prior declaration of that 2108 // identifier is visible,23) if the prior declaration specifies 2109 // internal or external linkage, the linkage of the identifier at 2110 // the later declaration is the same as the linkage specified at 2111 // the prior declaration. If no prior declaration is visible, or 2112 // if the prior declaration specifies no linkage, then the 2113 // identifier has external linkage. 2114 if (New->hasExternalStorage() && Old->hasLinkage()) 2115 /* Okay */; 2116 else if (New->getStorageClass() != SC_Static && 2117 Old->getStorageClass() == SC_Static) { 2118 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 2119 Diag(Old->getLocation(), diag::note_previous_definition); 2120 return New->setInvalidDecl(); 2121 } 2122 2123 // Check if extern is followed by non-extern and vice-versa. 2124 if (New->hasExternalStorage() && 2125 !Old->hasLinkage() && Old->isLocalVarDecl()) { 2126 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 2127 Diag(Old->getLocation(), diag::note_previous_definition); 2128 return New->setInvalidDecl(); 2129 } 2130 if (Old->hasExternalStorage() && 2131 !New->hasLinkage() && New->isLocalVarDecl()) { 2132 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 2133 Diag(Old->getLocation(), diag::note_previous_definition); 2134 return New->setInvalidDecl(); 2135 } 2136 2137 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 2138 2139 // FIXME: The test for external storage here seems wrong? We still 2140 // need to check for mismatches. 2141 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 2142 // Don't complain about out-of-line definitions of static members. 2143 !(Old->getLexicalDeclContext()->isRecord() && 2144 !New->getLexicalDeclContext()->isRecord())) { 2145 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 2146 Diag(Old->getLocation(), diag::note_previous_definition); 2147 return New->setInvalidDecl(); 2148 } 2149 2150 if (New->isThreadSpecified() && !Old->isThreadSpecified()) { 2151 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 2152 Diag(Old->getLocation(), diag::note_previous_definition); 2153 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) { 2154 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 2155 Diag(Old->getLocation(), diag::note_previous_definition); 2156 } 2157 2158 // C++ doesn't have tentative definitions, so go right ahead and check here. 2159 const VarDecl *Def; 2160 if (getLangOptions().CPlusPlus && 2161 New->isThisDeclarationADefinition() == VarDecl::Definition && 2162 (Def = Old->getDefinition())) { 2163 Diag(New->getLocation(), diag::err_redefinition) 2164 << New->getDeclName(); 2165 Diag(Def->getLocation(), diag::note_previous_definition); 2166 New->setInvalidDecl(); 2167 return; 2168 } 2169 // c99 6.2.2 P4. 2170 // For an identifier declared with the storage-class specifier extern in a 2171 // scope in which a prior declaration of that identifier is visible, if 2172 // the prior declaration specifies internal or external linkage, the linkage 2173 // of the identifier at the later declaration is the same as the linkage 2174 // specified at the prior declaration. 2175 // FIXME. revisit this code. 2176 if (New->hasExternalStorage() && 2177 Old->getLinkage() == InternalLinkage && 2178 New->getDeclContext() == Old->getDeclContext()) 2179 New->setStorageClass(Old->getStorageClass()); 2180 2181 // Keep a chain of previous declarations. 2182 New->setPreviousDeclaration(Old); 2183 2184 // Inherit access appropriately. 2185 New->setAccess(Old->getAccess()); 2186} 2187 2188/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2189/// no declarator (e.g. "struct foo;") is parsed. 2190Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2191 DeclSpec &DS) { 2192 return ParsedFreeStandingDeclSpec(S, AS, DS, 2193 MultiTemplateParamsArg(*this, 0, 0)); 2194} 2195 2196/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2197/// no declarator (e.g. "struct foo;") is parsed. It also accopts template 2198/// parameters to cope with template friend declarations. 2199Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2200 DeclSpec &DS, 2201 MultiTemplateParamsArg TemplateParams) { 2202 Decl *TagD = 0; 2203 TagDecl *Tag = 0; 2204 if (DS.getTypeSpecType() == DeclSpec::TST_class || 2205 DS.getTypeSpecType() == DeclSpec::TST_struct || 2206 DS.getTypeSpecType() == DeclSpec::TST_union || 2207 DS.getTypeSpecType() == DeclSpec::TST_enum) { 2208 TagD = DS.getRepAsDecl(); 2209 2210 if (!TagD) // We probably had an error 2211 return 0; 2212 2213 // Note that the above type specs guarantee that the 2214 // type rep is a Decl, whereas in many of the others 2215 // it's a Type. 2216 Tag = dyn_cast<TagDecl>(TagD); 2217 } 2218 2219 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 2220 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 2221 // or incomplete types shall not be restrict-qualified." 2222 if (TypeQuals & DeclSpec::TQ_restrict) 2223 Diag(DS.getRestrictSpecLoc(), 2224 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 2225 << DS.getSourceRange(); 2226 } 2227 2228 if (DS.isConstexprSpecified()) { 2229 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 2230 // and definitions of functions and variables. 2231 if (Tag) 2232 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 2233 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 2234 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 2235 DS.getTypeSpecType() == DeclSpec::TST_union ? 2 : 3); 2236 else 2237 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 2238 // Don't emit warnings after this error. 2239 return TagD; 2240 } 2241 2242 if (DS.isFriendSpecified()) { 2243 // If we're dealing with a decl but not a TagDecl, assume that 2244 // whatever routines created it handled the friendship aspect. 2245 if (TagD && !Tag) 2246 return 0; 2247 return ActOnFriendTypeDecl(S, DS, TemplateParams); 2248 } 2249 2250 // Track whether we warned about the fact that there aren't any 2251 // declarators. 2252 bool emittedWarning = false; 2253 2254 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 2255 ProcessDeclAttributeList(S, Record, DS.getAttributes().getList()); 2256 2257 if (!Record->getDeclName() && Record->isDefinition() && 2258 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 2259 if (getLangOptions().CPlusPlus || 2260 Record->getDeclContext()->isRecord()) 2261 return BuildAnonymousStructOrUnion(S, DS, AS, Record); 2262 2263 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators) 2264 << DS.getSourceRange(); 2265 emittedWarning = true; 2266 } 2267 } 2268 2269 // Check for Microsoft C extension: anonymous struct. 2270 if (getLangOptions().Microsoft && !getLangOptions().CPlusPlus && 2271 CurContext->isRecord() && 2272 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 2273 // Handle 2 kinds of anonymous struct: 2274 // struct STRUCT; 2275 // and 2276 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 2277 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 2278 if ((Record && Record->getDeclName() && !Record->isDefinition()) || 2279 (DS.getTypeSpecType() == DeclSpec::TST_typename && 2280 DS.getRepAsType().get()->isStructureType())) { 2281 Diag(DS.getSourceRange().getBegin(), diag::ext_ms_anonymous_struct) 2282 << DS.getSourceRange(); 2283 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 2284 } 2285 } 2286 2287 if (getLangOptions().CPlusPlus && 2288 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 2289 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 2290 if (Enum->enumerator_begin() == Enum->enumerator_end() && 2291 !Enum->getIdentifier() && !Enum->isInvalidDecl()) { 2292 Diag(Enum->getLocation(), diag::ext_no_declarators) 2293 << DS.getSourceRange(); 2294 emittedWarning = true; 2295 } 2296 2297 // Skip all the checks below if we have a type error. 2298 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD; 2299 2300 if (!DS.isMissingDeclaratorOk()) { 2301 // Warn about typedefs of enums without names, since this is an 2302 // extension in both Microsoft and GNU. 2303 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef && 2304 Tag && isa<EnumDecl>(Tag)) { 2305 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name) 2306 << DS.getSourceRange(); 2307 return Tag; 2308 } 2309 2310 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators) 2311 << DS.getSourceRange(); 2312 emittedWarning = true; 2313 } 2314 2315 // We're going to complain about a bunch of spurious specifiers; 2316 // only do this if we're declaring a tag, because otherwise we 2317 // should be getting diag::ext_no_declarators. 2318 if (emittedWarning || (TagD && TagD->isInvalidDecl())) 2319 return TagD; 2320 2321 // Note that a linkage-specification sets a storage class, but 2322 // 'extern "C" struct foo;' is actually valid and not theoretically 2323 // useless. 2324 if (DeclSpec::SCS scs = DS.getStorageClassSpec()) 2325 if (!DS.isExternInLinkageSpec()) 2326 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier) 2327 << DeclSpec::getSpecifierName(scs); 2328 2329 if (DS.isThreadSpecified()) 2330 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread"; 2331 if (DS.getTypeQualifiers()) { 2332 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2333 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const"; 2334 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 2335 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile"; 2336 // Restrict is covered above. 2337 } 2338 if (DS.isInlineSpecified()) 2339 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline"; 2340 if (DS.isVirtualSpecified()) 2341 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual"; 2342 if (DS.isExplicitSpecified()) 2343 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit"; 2344 2345 // FIXME: Warn on useless attributes 2346 2347 return TagD; 2348} 2349 2350/// ActOnVlaStmt - This rouine if finds a vla expression in a decl spec. 2351/// builds a statement for it and returns it so it is evaluated. 2352StmtResult Sema::ActOnVlaStmt(const DeclSpec &DS) { 2353 StmtResult R; 2354 if (DS.getTypeSpecType() == DeclSpec::TST_typeofExpr) { 2355 Expr *Exp = DS.getRepAsExpr(); 2356 QualType Ty = Exp->getType(); 2357 if (Ty->isPointerType()) { 2358 do 2359 Ty = Ty->getAs<PointerType>()->getPointeeType(); 2360 while (Ty->isPointerType()); 2361 } 2362 if (Ty->isVariableArrayType()) { 2363 R = ActOnExprStmt(MakeFullExpr(Exp)); 2364 } 2365 } 2366 return R; 2367} 2368 2369/// We are trying to inject an anonymous member into the given scope; 2370/// check if there's an existing declaration that can't be overloaded. 2371/// 2372/// \return true if this is a forbidden redeclaration 2373static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 2374 Scope *S, 2375 DeclContext *Owner, 2376 DeclarationName Name, 2377 SourceLocation NameLoc, 2378 unsigned diagnostic) { 2379 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 2380 Sema::ForRedeclaration); 2381 if (!SemaRef.LookupName(R, S)) return false; 2382 2383 if (R.getAsSingle<TagDecl>()) 2384 return false; 2385 2386 // Pick a representative declaration. 2387 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 2388 assert(PrevDecl && "Expected a non-null Decl"); 2389 2390 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 2391 return false; 2392 2393 SemaRef.Diag(NameLoc, diagnostic) << Name; 2394 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 2395 2396 return true; 2397} 2398 2399/// InjectAnonymousStructOrUnionMembers - Inject the members of the 2400/// anonymous struct or union AnonRecord into the owning context Owner 2401/// and scope S. This routine will be invoked just after we realize 2402/// that an unnamed union or struct is actually an anonymous union or 2403/// struct, e.g., 2404/// 2405/// @code 2406/// union { 2407/// int i; 2408/// float f; 2409/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 2410/// // f into the surrounding scope.x 2411/// @endcode 2412/// 2413/// This routine is recursive, injecting the names of nested anonymous 2414/// structs/unions into the owning context and scope as well. 2415static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 2416 DeclContext *Owner, 2417 RecordDecl *AnonRecord, 2418 AccessSpecifier AS, 2419 SmallVector<NamedDecl*, 2> &Chaining, 2420 bool MSAnonStruct) { 2421 unsigned diagKind 2422 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 2423 : diag::err_anonymous_struct_member_redecl; 2424 2425 bool Invalid = false; 2426 2427 // Look every FieldDecl and IndirectFieldDecl with a name. 2428 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 2429 DEnd = AnonRecord->decls_end(); 2430 D != DEnd; ++D) { 2431 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 2432 cast<NamedDecl>(*D)->getDeclName()) { 2433 ValueDecl *VD = cast<ValueDecl>(*D); 2434 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 2435 VD->getLocation(), diagKind)) { 2436 // C++ [class.union]p2: 2437 // The names of the members of an anonymous union shall be 2438 // distinct from the names of any other entity in the 2439 // scope in which the anonymous union is declared. 2440 Invalid = true; 2441 } else { 2442 // C++ [class.union]p2: 2443 // For the purpose of name lookup, after the anonymous union 2444 // definition, the members of the anonymous union are 2445 // considered to have been defined in the scope in which the 2446 // anonymous union is declared. 2447 unsigned OldChainingSize = Chaining.size(); 2448 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 2449 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 2450 PE = IF->chain_end(); PI != PE; ++PI) 2451 Chaining.push_back(*PI); 2452 else 2453 Chaining.push_back(VD); 2454 2455 assert(Chaining.size() >= 2); 2456 NamedDecl **NamedChain = 2457 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 2458 for (unsigned i = 0; i < Chaining.size(); i++) 2459 NamedChain[i] = Chaining[i]; 2460 2461 IndirectFieldDecl* IndirectField = 2462 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 2463 VD->getIdentifier(), VD->getType(), 2464 NamedChain, Chaining.size()); 2465 2466 IndirectField->setAccess(AS); 2467 IndirectField->setImplicit(); 2468 SemaRef.PushOnScopeChains(IndirectField, S); 2469 2470 // That includes picking up the appropriate access specifier. 2471 if (AS != AS_none) IndirectField->setAccess(AS); 2472 2473 Chaining.resize(OldChainingSize); 2474 } 2475 } 2476 } 2477 2478 return Invalid; 2479} 2480 2481/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 2482/// a VarDecl::StorageClass. Any error reporting is up to the caller: 2483/// illegal input values are mapped to SC_None. 2484static StorageClass 2485StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 2486 switch (StorageClassSpec) { 2487 case DeclSpec::SCS_unspecified: return SC_None; 2488 case DeclSpec::SCS_extern: return SC_Extern; 2489 case DeclSpec::SCS_static: return SC_Static; 2490 case DeclSpec::SCS_auto: return SC_Auto; 2491 case DeclSpec::SCS_register: return SC_Register; 2492 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 2493 // Illegal SCSs map to None: error reporting is up to the caller. 2494 case DeclSpec::SCS_mutable: // Fall through. 2495 case DeclSpec::SCS_typedef: return SC_None; 2496 } 2497 llvm_unreachable("unknown storage class specifier"); 2498} 2499 2500/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to 2501/// a StorageClass. Any error reporting is up to the caller: 2502/// illegal input values are mapped to SC_None. 2503static StorageClass 2504StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 2505 switch (StorageClassSpec) { 2506 case DeclSpec::SCS_unspecified: return SC_None; 2507 case DeclSpec::SCS_extern: return SC_Extern; 2508 case DeclSpec::SCS_static: return SC_Static; 2509 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 2510 // Illegal SCSs map to None: error reporting is up to the caller. 2511 case DeclSpec::SCS_auto: // Fall through. 2512 case DeclSpec::SCS_mutable: // Fall through. 2513 case DeclSpec::SCS_register: // Fall through. 2514 case DeclSpec::SCS_typedef: return SC_None; 2515 } 2516 llvm_unreachable("unknown storage class specifier"); 2517} 2518 2519/// BuildAnonymousStructOrUnion - Handle the declaration of an 2520/// anonymous structure or union. Anonymous unions are a C++ feature 2521/// (C++ [class.union]) and a GNU C extension; anonymous structures 2522/// are a GNU C and GNU C++ extension. 2523Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 2524 AccessSpecifier AS, 2525 RecordDecl *Record) { 2526 DeclContext *Owner = Record->getDeclContext(); 2527 2528 // Diagnose whether this anonymous struct/union is an extension. 2529 if (Record->isUnion() && !getLangOptions().CPlusPlus) 2530 Diag(Record->getLocation(), diag::ext_anonymous_union); 2531 else if (!Record->isUnion()) 2532 Diag(Record->getLocation(), diag::ext_anonymous_struct); 2533 2534 // C and C++ require different kinds of checks for anonymous 2535 // structs/unions. 2536 bool Invalid = false; 2537 if (getLangOptions().CPlusPlus) { 2538 const char* PrevSpec = 0; 2539 unsigned DiagID; 2540 // C++ [class.union]p3: 2541 // Anonymous unions declared in a named namespace or in the 2542 // global namespace shall be declared static. 2543 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 2544 (isa<TranslationUnitDecl>(Owner) || 2545 (isa<NamespaceDecl>(Owner) && 2546 cast<NamespaceDecl>(Owner)->getDeclName()))) { 2547 Diag(Record->getLocation(), diag::err_anonymous_union_not_static); 2548 Invalid = true; 2549 2550 // Recover by adding 'static'. 2551 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), 2552 PrevSpec, DiagID, getLangOptions()); 2553 } 2554 // C++ [class.union]p3: 2555 // A storage class is not allowed in a declaration of an 2556 // anonymous union in a class scope. 2557 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 2558 isa<RecordDecl>(Owner)) { 2559 Diag(DS.getStorageClassSpecLoc(), 2560 diag::err_anonymous_union_with_storage_spec); 2561 Invalid = true; 2562 2563 // Recover by removing the storage specifier. 2564 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(), 2565 PrevSpec, DiagID, getLangOptions()); 2566 } 2567 2568 // Ignore const/volatile/restrict qualifiers. 2569 if (DS.getTypeQualifiers()) { 2570 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2571 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 2572 << Record->isUnion() << 0 2573 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 2574 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 2575 Diag(DS.getVolatileSpecLoc(), diag::ext_anonymous_struct_union_qualified) 2576 << Record->isUnion() << 1 2577 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 2578 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 2579 Diag(DS.getRestrictSpecLoc(), diag::ext_anonymous_struct_union_qualified) 2580 << Record->isUnion() << 2 2581 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 2582 2583 DS.ClearTypeQualifiers(); 2584 } 2585 2586 // C++ [class.union]p2: 2587 // The member-specification of an anonymous union shall only 2588 // define non-static data members. [Note: nested types and 2589 // functions cannot be declared within an anonymous union. ] 2590 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 2591 MemEnd = Record->decls_end(); 2592 Mem != MemEnd; ++Mem) { 2593 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 2594 // C++ [class.union]p3: 2595 // An anonymous union shall not have private or protected 2596 // members (clause 11). 2597 assert(FD->getAccess() != AS_none); 2598 if (FD->getAccess() != AS_public) { 2599 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 2600 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 2601 Invalid = true; 2602 } 2603 2604 // C++ [class.union]p1 2605 // An object of a class with a non-trivial constructor, a non-trivial 2606 // copy constructor, a non-trivial destructor, or a non-trivial copy 2607 // assignment operator cannot be a member of a union, nor can an 2608 // array of such objects. 2609 if (!getLangOptions().CPlusPlus0x && CheckNontrivialField(FD)) 2610 Invalid = true; 2611 } else if ((*Mem)->isImplicit()) { 2612 // Any implicit members are fine. 2613 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 2614 // This is a type that showed up in an 2615 // elaborated-type-specifier inside the anonymous struct or 2616 // union, but which actually declares a type outside of the 2617 // anonymous struct or union. It's okay. 2618 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 2619 if (!MemRecord->isAnonymousStructOrUnion() && 2620 MemRecord->getDeclName()) { 2621 // Visual C++ allows type definition in anonymous struct or union. 2622 if (getLangOptions().Microsoft) 2623 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 2624 << (int)Record->isUnion(); 2625 else { 2626 // This is a nested type declaration. 2627 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 2628 << (int)Record->isUnion(); 2629 Invalid = true; 2630 } 2631 } 2632 } else if (isa<AccessSpecDecl>(*Mem)) { 2633 // Any access specifier is fine. 2634 } else { 2635 // We have something that isn't a non-static data 2636 // member. Complain about it. 2637 unsigned DK = diag::err_anonymous_record_bad_member; 2638 if (isa<TypeDecl>(*Mem)) 2639 DK = diag::err_anonymous_record_with_type; 2640 else if (isa<FunctionDecl>(*Mem)) 2641 DK = diag::err_anonymous_record_with_function; 2642 else if (isa<VarDecl>(*Mem)) 2643 DK = diag::err_anonymous_record_with_static; 2644 2645 // Visual C++ allows type definition in anonymous struct or union. 2646 if (getLangOptions().Microsoft && 2647 DK == diag::err_anonymous_record_with_type) 2648 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 2649 << (int)Record->isUnion(); 2650 else { 2651 Diag((*Mem)->getLocation(), DK) 2652 << (int)Record->isUnion(); 2653 Invalid = true; 2654 } 2655 } 2656 } 2657 } 2658 2659 if (!Record->isUnion() && !Owner->isRecord()) { 2660 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 2661 << (int)getLangOptions().CPlusPlus; 2662 Invalid = true; 2663 } 2664 2665 // Mock up a declarator. 2666 Declarator Dc(DS, Declarator::MemberContext); 2667 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 2668 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 2669 2670 // Create a declaration for this anonymous struct/union. 2671 NamedDecl *Anon = 0; 2672 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 2673 Anon = FieldDecl::Create(Context, OwningClass, 2674 DS.getSourceRange().getBegin(), 2675 Record->getLocation(), 2676 /*IdentifierInfo=*/0, 2677 Context.getTypeDeclType(Record), 2678 TInfo, 2679 /*BitWidth=*/0, /*Mutable=*/false, 2680 /*HasInit=*/false); 2681 Anon->setAccess(AS); 2682 if (getLangOptions().CPlusPlus) 2683 FieldCollector->Add(cast<FieldDecl>(Anon)); 2684 } else { 2685 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 2686 assert(SCSpec != DeclSpec::SCS_typedef && 2687 "Parser allowed 'typedef' as storage class VarDecl."); 2688 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 2689 if (SCSpec == DeclSpec::SCS_mutable) { 2690 // mutable can only appear on non-static class members, so it's always 2691 // an error here 2692 Diag(Record->getLocation(), diag::err_mutable_nonmember); 2693 Invalid = true; 2694 SC = SC_None; 2695 } 2696 SCSpec = DS.getStorageClassSpecAsWritten(); 2697 VarDecl::StorageClass SCAsWritten 2698 = StorageClassSpecToVarDeclStorageClass(SCSpec); 2699 2700 Anon = VarDecl::Create(Context, Owner, 2701 DS.getSourceRange().getBegin(), 2702 Record->getLocation(), /*IdentifierInfo=*/0, 2703 Context.getTypeDeclType(Record), 2704 TInfo, SC, SCAsWritten); 2705 } 2706 Anon->setImplicit(); 2707 2708 // Add the anonymous struct/union object to the current 2709 // context. We'll be referencing this object when we refer to one of 2710 // its members. 2711 Owner->addDecl(Anon); 2712 2713 // Inject the members of the anonymous struct/union into the owning 2714 // context and into the identifier resolver chain for name lookup 2715 // purposes. 2716 SmallVector<NamedDecl*, 2> Chain; 2717 Chain.push_back(Anon); 2718 2719 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 2720 Chain, false)) 2721 Invalid = true; 2722 2723 // Mark this as an anonymous struct/union type. Note that we do not 2724 // do this until after we have already checked and injected the 2725 // members of this anonymous struct/union type, because otherwise 2726 // the members could be injected twice: once by DeclContext when it 2727 // builds its lookup table, and once by 2728 // InjectAnonymousStructOrUnionMembers. 2729 Record->setAnonymousStructOrUnion(true); 2730 2731 if (Invalid) 2732 Anon->setInvalidDecl(); 2733 2734 return Anon; 2735} 2736 2737/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 2738/// Microsoft C anonymous structure. 2739/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 2740/// Example: 2741/// 2742/// struct A { int a; }; 2743/// struct B { struct A; int b; }; 2744/// 2745/// void foo() { 2746/// B var; 2747/// var.a = 3; 2748/// } 2749/// 2750Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 2751 RecordDecl *Record) { 2752 2753 // If there is no Record, get the record via the typedef. 2754 if (!Record) 2755 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 2756 2757 // Mock up a declarator. 2758 Declarator Dc(DS, Declarator::TypeNameContext); 2759 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 2760 assert(TInfo && "couldn't build declarator info for anonymous struct"); 2761 2762 // Create a declaration for this anonymous struct. 2763 NamedDecl* Anon = FieldDecl::Create(Context, 2764 cast<RecordDecl>(CurContext), 2765 DS.getSourceRange().getBegin(), 2766 DS.getSourceRange().getBegin(), 2767 /*IdentifierInfo=*/0, 2768 Context.getTypeDeclType(Record), 2769 TInfo, 2770 /*BitWidth=*/0, /*Mutable=*/false, 2771 /*HasInit=*/false); 2772 Anon->setImplicit(); 2773 2774 // Add the anonymous struct object to the current context. 2775 CurContext->addDecl(Anon); 2776 2777 // Inject the members of the anonymous struct into the current 2778 // context and into the identifier resolver chain for name lookup 2779 // purposes. 2780 SmallVector<NamedDecl*, 2> Chain; 2781 Chain.push_back(Anon); 2782 2783 if (InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 2784 Record->getDefinition(), 2785 AS_none, Chain, true)) 2786 Anon->setInvalidDecl(); 2787 2788 return Anon; 2789} 2790 2791/// GetNameForDeclarator - Determine the full declaration name for the 2792/// given Declarator. 2793DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 2794 return GetNameFromUnqualifiedId(D.getName()); 2795} 2796 2797/// \brief Retrieves the declaration name from a parsed unqualified-id. 2798DeclarationNameInfo 2799Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 2800 DeclarationNameInfo NameInfo; 2801 NameInfo.setLoc(Name.StartLocation); 2802 2803 switch (Name.getKind()) { 2804 2805 case UnqualifiedId::IK_ImplicitSelfParam: 2806 case UnqualifiedId::IK_Identifier: 2807 NameInfo.setName(Name.Identifier); 2808 NameInfo.setLoc(Name.StartLocation); 2809 return NameInfo; 2810 2811 case UnqualifiedId::IK_OperatorFunctionId: 2812 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 2813 Name.OperatorFunctionId.Operator)); 2814 NameInfo.setLoc(Name.StartLocation); 2815 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 2816 = Name.OperatorFunctionId.SymbolLocations[0]; 2817 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 2818 = Name.EndLocation.getRawEncoding(); 2819 return NameInfo; 2820 2821 case UnqualifiedId::IK_LiteralOperatorId: 2822 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 2823 Name.Identifier)); 2824 NameInfo.setLoc(Name.StartLocation); 2825 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 2826 return NameInfo; 2827 2828 case UnqualifiedId::IK_ConversionFunctionId: { 2829 TypeSourceInfo *TInfo; 2830 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 2831 if (Ty.isNull()) 2832 return DeclarationNameInfo(); 2833 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 2834 Context.getCanonicalType(Ty))); 2835 NameInfo.setLoc(Name.StartLocation); 2836 NameInfo.setNamedTypeInfo(TInfo); 2837 return NameInfo; 2838 } 2839 2840 case UnqualifiedId::IK_ConstructorName: { 2841 TypeSourceInfo *TInfo; 2842 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 2843 if (Ty.isNull()) 2844 return DeclarationNameInfo(); 2845 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 2846 Context.getCanonicalType(Ty))); 2847 NameInfo.setLoc(Name.StartLocation); 2848 NameInfo.setNamedTypeInfo(TInfo); 2849 return NameInfo; 2850 } 2851 2852 case UnqualifiedId::IK_ConstructorTemplateId: { 2853 // In well-formed code, we can only have a constructor 2854 // template-id that refers to the current context, so go there 2855 // to find the actual type being constructed. 2856 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 2857 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 2858 return DeclarationNameInfo(); 2859 2860 // Determine the type of the class being constructed. 2861 QualType CurClassType = Context.getTypeDeclType(CurClass); 2862 2863 // FIXME: Check two things: that the template-id names the same type as 2864 // CurClassType, and that the template-id does not occur when the name 2865 // was qualified. 2866 2867 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 2868 Context.getCanonicalType(CurClassType))); 2869 NameInfo.setLoc(Name.StartLocation); 2870 // FIXME: should we retrieve TypeSourceInfo? 2871 NameInfo.setNamedTypeInfo(0); 2872 return NameInfo; 2873 } 2874 2875 case UnqualifiedId::IK_DestructorName: { 2876 TypeSourceInfo *TInfo; 2877 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 2878 if (Ty.isNull()) 2879 return DeclarationNameInfo(); 2880 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 2881 Context.getCanonicalType(Ty))); 2882 NameInfo.setLoc(Name.StartLocation); 2883 NameInfo.setNamedTypeInfo(TInfo); 2884 return NameInfo; 2885 } 2886 2887 case UnqualifiedId::IK_TemplateId: { 2888 TemplateName TName = Name.TemplateId->Template.get(); 2889 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 2890 return Context.getNameForTemplate(TName, TNameLoc); 2891 } 2892 2893 } // switch (Name.getKind()) 2894 2895 assert(false && "Unknown name kind"); 2896 return DeclarationNameInfo(); 2897} 2898 2899static QualType getCoreType(QualType Ty) { 2900 do { 2901 if (Ty->isPointerType() || Ty->isReferenceType()) 2902 Ty = Ty->getPointeeType(); 2903 else if (Ty->isArrayType()) 2904 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 2905 else 2906 return Ty.withoutLocalFastQualifiers(); 2907 } while (true); 2908} 2909 2910/// isNearlyMatchingFunction - Determine whether the C++ functions 2911/// Declaration and Definition are "nearly" matching. This heuristic 2912/// is used to improve diagnostics in the case where an out-of-line 2913/// function definition doesn't match any declaration within the class 2914/// or namespace. Also sets Params to the list of indices to the 2915/// parameters that differ between the declaration and the definition. 2916static bool isNearlyMatchingFunction(ASTContext &Context, 2917 FunctionDecl *Declaration, 2918 FunctionDecl *Definition, 2919 llvm::SmallVectorImpl<unsigned> &Params) { 2920 Params.clear(); 2921 if (Declaration->param_size() != Definition->param_size()) 2922 return false; 2923 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 2924 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 2925 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 2926 2927 // The parameter types are identical 2928 if (Context.hasSameType(DefParamTy, DeclParamTy)) 2929 continue; 2930 2931 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 2932 QualType DefParamBaseTy = getCoreType(DefParamTy); 2933 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 2934 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 2935 2936 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 2937 (DeclTyName && DeclTyName == DefTyName)) 2938 Params.push_back(Idx); 2939 else // The two parameters aren't even close 2940 return false; 2941 } 2942 2943 return true; 2944} 2945 2946/// NeedsRebuildingInCurrentInstantiation - Checks whether the given 2947/// declarator needs to be rebuilt in the current instantiation. 2948/// Any bits of declarator which appear before the name are valid for 2949/// consideration here. That's specifically the type in the decl spec 2950/// and the base type in any member-pointer chunks. 2951static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 2952 DeclarationName Name) { 2953 // The types we specifically need to rebuild are: 2954 // - typenames, typeofs, and decltypes 2955 // - types which will become injected class names 2956 // Of course, we also need to rebuild any type referencing such a 2957 // type. It's safest to just say "dependent", but we call out a 2958 // few cases here. 2959 2960 DeclSpec &DS = D.getMutableDeclSpec(); 2961 switch (DS.getTypeSpecType()) { 2962 case DeclSpec::TST_typename: 2963 case DeclSpec::TST_typeofType: 2964 case DeclSpec::TST_decltype: 2965 case DeclSpec::TST_underlyingType: { 2966 // Grab the type from the parser. 2967 TypeSourceInfo *TSI = 0; 2968 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 2969 if (T.isNull() || !T->isDependentType()) break; 2970 2971 // Make sure there's a type source info. This isn't really much 2972 // of a waste; most dependent types should have type source info 2973 // attached already. 2974 if (!TSI) 2975 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 2976 2977 // Rebuild the type in the current instantiation. 2978 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 2979 if (!TSI) return true; 2980 2981 // Store the new type back in the decl spec. 2982 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 2983 DS.UpdateTypeRep(LocType); 2984 break; 2985 } 2986 2987 case DeclSpec::TST_typeofExpr: { 2988 Expr *E = DS.getRepAsExpr(); 2989 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 2990 if (Result.isInvalid()) return true; 2991 DS.UpdateExprRep(Result.get()); 2992 break; 2993 } 2994 2995 default: 2996 // Nothing to do for these decl specs. 2997 break; 2998 } 2999 3000 // It doesn't matter what order we do this in. 3001 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 3002 DeclaratorChunk &Chunk = D.getTypeObject(I); 3003 3004 // The only type information in the declarator which can come 3005 // before the declaration name is the base type of a member 3006 // pointer. 3007 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 3008 continue; 3009 3010 // Rebuild the scope specifier in-place. 3011 CXXScopeSpec &SS = Chunk.Mem.Scope(); 3012 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 3013 return true; 3014 } 3015 3016 return false; 3017} 3018 3019Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 3020 return HandleDeclarator(S, D, MultiTemplateParamsArg(*this), 3021 /*IsFunctionDefinition=*/false); 3022} 3023 3024/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 3025/// If T is the name of a class, then each of the following shall have a 3026/// name different from T: 3027/// - every static data member of class T; 3028/// - every member function of class T 3029/// - every member of class T that is itself a type; 3030/// \returns true if the declaration name violates these rules. 3031bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 3032 DeclarationNameInfo NameInfo) { 3033 DeclarationName Name = NameInfo.getName(); 3034 3035 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 3036 if (Record->getIdentifier() && Record->getDeclName() == Name) { 3037 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 3038 return true; 3039 } 3040 3041 return false; 3042} 3043 3044Decl *Sema::HandleDeclarator(Scope *S, Declarator &D, 3045 MultiTemplateParamsArg TemplateParamLists, 3046 bool IsFunctionDefinition) { 3047 // TODO: consider using NameInfo for diagnostic. 3048 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3049 DeclarationName Name = NameInfo.getName(); 3050 3051 // All of these full declarators require an identifier. If it doesn't have 3052 // one, the ParsedFreeStandingDeclSpec action should be used. 3053 if (!Name) { 3054 if (!D.isInvalidType()) // Reject this if we think it is valid. 3055 Diag(D.getDeclSpec().getSourceRange().getBegin(), 3056 diag::err_declarator_need_ident) 3057 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 3058 return 0; 3059 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 3060 return 0; 3061 3062 // The scope passed in may not be a decl scope. Zip up the scope tree until 3063 // we find one that is. 3064 while ((S->getFlags() & Scope::DeclScope) == 0 || 3065 (S->getFlags() & Scope::TemplateParamScope) != 0) 3066 S = S->getParent(); 3067 3068 DeclContext *DC = CurContext; 3069 if (D.getCXXScopeSpec().isInvalid()) 3070 D.setInvalidType(); 3071 else if (D.getCXXScopeSpec().isSet()) { 3072 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 3073 UPPC_DeclarationQualifier)) 3074 return 0; 3075 3076 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 3077 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 3078 if (!DC) { 3079 // If we could not compute the declaration context, it's because the 3080 // declaration context is dependent but does not refer to a class, 3081 // class template, or class template partial specialization. Complain 3082 // and return early, to avoid the coming semantic disaster. 3083 Diag(D.getIdentifierLoc(), 3084 diag::err_template_qualified_declarator_no_match) 3085 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 3086 << D.getCXXScopeSpec().getRange(); 3087 return 0; 3088 } 3089 bool IsDependentContext = DC->isDependentContext(); 3090 3091 if (!IsDependentContext && 3092 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 3093 return 0; 3094 3095 if (isa<CXXRecordDecl>(DC)) { 3096 if (!cast<CXXRecordDecl>(DC)->hasDefinition()) { 3097 Diag(D.getIdentifierLoc(), 3098 diag::err_member_def_undefined_record) 3099 << Name << DC << D.getCXXScopeSpec().getRange(); 3100 D.setInvalidType(); 3101 } else if (isa<CXXRecordDecl>(CurContext) && 3102 !D.getDeclSpec().isFriendSpecified()) { 3103 // The user provided a superfluous scope specifier inside a class 3104 // definition: 3105 // 3106 // class X { 3107 // void X::f(); 3108 // }; 3109 if (CurContext->Equals(DC)) 3110 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification) 3111 << Name << FixItHint::CreateRemoval(D.getCXXScopeSpec().getRange()); 3112 else 3113 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3114 << Name << D.getCXXScopeSpec().getRange(); 3115 3116 // Pretend that this qualifier was not here. 3117 D.getCXXScopeSpec().clear(); 3118 } 3119 } 3120 3121 // Check whether we need to rebuild the type of the given 3122 // declaration in the current instantiation. 3123 if (EnteringContext && IsDependentContext && 3124 TemplateParamLists.size() != 0) { 3125 ContextRAII SavedContext(*this, DC); 3126 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 3127 D.setInvalidType(); 3128 } 3129 } 3130 3131 if (DiagnoseClassNameShadow(DC, NameInfo)) 3132 // If this is a typedef, we'll end up spewing multiple diagnostics. 3133 // Just return early; it's safer. 3134 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3135 return 0; 3136 3137 NamedDecl *New; 3138 3139 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 3140 QualType R = TInfo->getType(); 3141 3142 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 3143 UPPC_DeclarationType)) 3144 D.setInvalidType(); 3145 3146 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 3147 ForRedeclaration); 3148 3149 // See if this is a redefinition of a variable in the same scope. 3150 if (!D.getCXXScopeSpec().isSet()) { 3151 bool IsLinkageLookup = false; 3152 3153 // If the declaration we're planning to build will be a function 3154 // or object with linkage, then look for another declaration with 3155 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 3156 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3157 /* Do nothing*/; 3158 else if (R->isFunctionType()) { 3159 if (CurContext->isFunctionOrMethod() || 3160 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 3161 IsLinkageLookup = true; 3162 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 3163 IsLinkageLookup = true; 3164 else if (CurContext->getRedeclContext()->isTranslationUnit() && 3165 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 3166 IsLinkageLookup = true; 3167 3168 if (IsLinkageLookup) 3169 Previous.clear(LookupRedeclarationWithLinkage); 3170 3171 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup); 3172 } else { // Something like "int foo::x;" 3173 LookupQualifiedName(Previous, DC); 3174 3175 // Don't consider using declarations as previous declarations for 3176 // out-of-line members. 3177 RemoveUsingDecls(Previous); 3178 3179 // C++ 7.3.1.2p2: 3180 // Members (including explicit specializations of templates) of a named 3181 // namespace can also be defined outside that namespace by explicit 3182 // qualification of the name being defined, provided that the entity being 3183 // defined was already declared in the namespace and the definition appears 3184 // after the point of declaration in a namespace that encloses the 3185 // declarations namespace. 3186 // 3187 // Note that we only check the context at this point. We don't yet 3188 // have enough information to make sure that PrevDecl is actually 3189 // the declaration we want to match. For example, given: 3190 // 3191 // class X { 3192 // void f(); 3193 // void f(float); 3194 // }; 3195 // 3196 // void X::f(int) { } // ill-formed 3197 // 3198 // In this case, PrevDecl will point to the overload set 3199 // containing the two f's declared in X, but neither of them 3200 // matches. 3201 3202 // First check whether we named the global scope. 3203 if (isa<TranslationUnitDecl>(DC)) { 3204 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope) 3205 << Name << D.getCXXScopeSpec().getRange(); 3206 } else { 3207 DeclContext *Cur = CurContext; 3208 while (isa<LinkageSpecDecl>(Cur)) 3209 Cur = Cur->getParent(); 3210 if (!Cur->Encloses(DC)) { 3211 // The qualifying scope doesn't enclose the original declaration. 3212 // Emit diagnostic based on current scope. 3213 SourceLocation L = D.getIdentifierLoc(); 3214 SourceRange R = D.getCXXScopeSpec().getRange(); 3215 if (isa<FunctionDecl>(Cur)) 3216 Diag(L, diag::err_invalid_declarator_in_function) << Name << R; 3217 else 3218 Diag(L, diag::err_invalid_declarator_scope) 3219 << Name << cast<NamedDecl>(DC) << R; 3220 D.setInvalidType(); 3221 } 3222 } 3223 } 3224 3225 if (Previous.isSingleResult() && 3226 Previous.getFoundDecl()->isTemplateParameter()) { 3227 // Maybe we will complain about the shadowed template parameter. 3228 if (!D.isInvalidType()) 3229 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 3230 Previous.getFoundDecl())) 3231 D.setInvalidType(); 3232 3233 // Just pretend that we didn't see the previous declaration. 3234 Previous.clear(); 3235 } 3236 3237 // In C++, the previous declaration we find might be a tag type 3238 // (class or enum). In this case, the new declaration will hide the 3239 // tag type. Note that this does does not apply if we're declaring a 3240 // typedef (C++ [dcl.typedef]p4). 3241 if (Previous.isSingleTagDecl() && 3242 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 3243 Previous.clear(); 3244 3245 bool Redeclaration = false; 3246 bool AddToScope = true; 3247 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 3248 if (TemplateParamLists.size()) { 3249 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 3250 return 0; 3251 } 3252 3253 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration); 3254 } else if (R->isFunctionType()) { 3255 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous, 3256 move(TemplateParamLists), 3257 IsFunctionDefinition, Redeclaration, 3258 AddToScope); 3259 } else { 3260 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous, 3261 move(TemplateParamLists), 3262 Redeclaration); 3263 } 3264 3265 if (New == 0) 3266 return 0; 3267 3268 // If this has an identifier and is not an invalid redeclaration or 3269 // function template specialization, add it to the scope stack. 3270 if (New->getDeclName() && AddToScope && 3271 !(Redeclaration && New->isInvalidDecl())) 3272 PushOnScopeChains(New, S); 3273 3274 return New; 3275} 3276 3277/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array 3278/// types into constant array types in certain situations which would otherwise 3279/// be errors (for GCC compatibility). 3280static QualType TryToFixInvalidVariablyModifiedType(QualType T, 3281 ASTContext &Context, 3282 bool &SizeIsNegative, 3283 llvm::APSInt &Oversized) { 3284 // This method tries to turn a variable array into a constant 3285 // array even when the size isn't an ICE. This is necessary 3286 // for compatibility with code that depends on gcc's buggy 3287 // constant expression folding, like struct {char x[(int)(char*)2];} 3288 SizeIsNegative = false; 3289 Oversized = 0; 3290 3291 if (T->isDependentType()) 3292 return QualType(); 3293 3294 QualifierCollector Qs; 3295 const Type *Ty = Qs.strip(T); 3296 3297 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 3298 QualType Pointee = PTy->getPointeeType(); 3299 QualType FixedType = 3300 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 3301 Oversized); 3302 if (FixedType.isNull()) return FixedType; 3303 FixedType = Context.getPointerType(FixedType); 3304 return Qs.apply(Context, FixedType); 3305 } 3306 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 3307 QualType Inner = PTy->getInnerType(); 3308 QualType FixedType = 3309 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 3310 Oversized); 3311 if (FixedType.isNull()) return FixedType; 3312 FixedType = Context.getParenType(FixedType); 3313 return Qs.apply(Context, FixedType); 3314 } 3315 3316 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 3317 if (!VLATy) 3318 return QualType(); 3319 // FIXME: We should probably handle this case 3320 if (VLATy->getElementType()->isVariablyModifiedType()) 3321 return QualType(); 3322 3323 Expr::EvalResult EvalResult; 3324 if (!VLATy->getSizeExpr() || 3325 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) || 3326 !EvalResult.Val.isInt()) 3327 return QualType(); 3328 3329 // Check whether the array size is negative. 3330 llvm::APSInt &Res = EvalResult.Val.getInt(); 3331 if (Res.isSigned() && Res.isNegative()) { 3332 SizeIsNegative = true; 3333 return QualType(); 3334 } 3335 3336 // Check whether the array is too large to be addressed. 3337 unsigned ActiveSizeBits 3338 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 3339 Res); 3340 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 3341 Oversized = Res; 3342 return QualType(); 3343 } 3344 3345 return Context.getConstantArrayType(VLATy->getElementType(), 3346 Res, ArrayType::Normal, 0); 3347} 3348 3349/// \brief Register the given locally-scoped external C declaration so 3350/// that it can be found later for redeclarations 3351void 3352Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, 3353 const LookupResult &Previous, 3354 Scope *S) { 3355 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 3356 "Decl is not a locally-scoped decl!"); 3357 // Note that we have a locally-scoped external with this name. 3358 LocallyScopedExternalDecls[ND->getDeclName()] = ND; 3359 3360 if (!Previous.isSingleResult()) 3361 return; 3362 3363 NamedDecl *PrevDecl = Previous.getFoundDecl(); 3364 3365 // If there was a previous declaration of this variable, it may be 3366 // in our identifier chain. Update the identifier chain with the new 3367 // declaration. 3368 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 3369 // The previous declaration was found on the identifer resolver 3370 // chain, so remove it from its scope. 3371 3372 if (S->isDeclScope(PrevDecl)) { 3373 // Special case for redeclarations in the SAME scope. 3374 // Because this declaration is going to be added to the identifier chain 3375 // later, we should temporarily take it OFF the chain. 3376 IdResolver.RemoveDecl(ND); 3377 3378 } else { 3379 // Find the scope for the original declaration. 3380 while (S && !S->isDeclScope(PrevDecl)) 3381 S = S->getParent(); 3382 } 3383 3384 if (S) 3385 S->RemoveDecl(PrevDecl); 3386 } 3387} 3388 3389llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 3390Sema::findLocallyScopedExternalDecl(DeclarationName Name) { 3391 if (ExternalSource) { 3392 // Load locally-scoped external decls from the external source. 3393 SmallVector<NamedDecl *, 4> Decls; 3394 ExternalSource->ReadLocallyScopedExternalDecls(Decls); 3395 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 3396 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 3397 = LocallyScopedExternalDecls.find(Decls[I]->getDeclName()); 3398 if (Pos == LocallyScopedExternalDecls.end()) 3399 LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I]; 3400 } 3401 } 3402 3403 return LocallyScopedExternalDecls.find(Name); 3404} 3405 3406/// \brief Diagnose function specifiers on a declaration of an identifier that 3407/// does not identify a function. 3408void Sema::DiagnoseFunctionSpecifiers(Declarator& D) { 3409 // FIXME: We should probably indicate the identifier in question to avoid 3410 // confusion for constructs like "inline int a(), b;" 3411 if (D.getDeclSpec().isInlineSpecified()) 3412 Diag(D.getDeclSpec().getInlineSpecLoc(), 3413 diag::err_inline_non_function); 3414 3415 if (D.getDeclSpec().isVirtualSpecified()) 3416 Diag(D.getDeclSpec().getVirtualSpecLoc(), 3417 diag::err_virtual_non_function); 3418 3419 if (D.getDeclSpec().isExplicitSpecified()) 3420 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3421 diag::err_explicit_non_function); 3422} 3423 3424NamedDecl* 3425Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 3426 QualType R, TypeSourceInfo *TInfo, 3427 LookupResult &Previous, bool &Redeclaration) { 3428 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 3429 if (D.getCXXScopeSpec().isSet()) { 3430 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 3431 << D.getCXXScopeSpec().getRange(); 3432 D.setInvalidType(); 3433 // Pretend we didn't see the scope specifier. 3434 DC = CurContext; 3435 Previous.clear(); 3436 } 3437 3438 if (getLangOptions().CPlusPlus) { 3439 // Check that there are no default arguments (C++ only). 3440 CheckExtraCXXDefaultArguments(D); 3441 } 3442 3443 DiagnoseFunctionSpecifiers(D); 3444 3445 if (D.getDeclSpec().isThreadSpecified()) 3446 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 3447 if (D.getDeclSpec().isConstexprSpecified()) 3448 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 3449 << 1; 3450 3451 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 3452 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 3453 << D.getName().getSourceRange(); 3454 return 0; 3455 } 3456 3457 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo); 3458 if (!NewTD) return 0; 3459 3460 // Handle attributes prior to checking for duplicates in MergeVarDecl 3461 ProcessDeclAttributes(S, NewTD, D); 3462 3463 CheckTypedefForVariablyModifiedType(S, NewTD); 3464 3465 return ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 3466} 3467 3468void 3469Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 3470 // C99 6.7.7p2: If a typedef name specifies a variably modified type 3471 // then it shall have block scope. 3472 // Note that variably modified types must be fixed before merging the decl so 3473 // that redeclarations will match. 3474 QualType T = NewTD->getUnderlyingType(); 3475 if (T->isVariablyModifiedType()) { 3476 getCurFunction()->setHasBranchProtectedScope(); 3477 3478 if (S->getFnParent() == 0) { 3479 bool SizeIsNegative; 3480 llvm::APSInt Oversized; 3481 QualType FixedTy = 3482 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 3483 Oversized); 3484 if (!FixedTy.isNull()) { 3485 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 3486 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy)); 3487 } else { 3488 if (SizeIsNegative) 3489 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 3490 else if (T->isVariableArrayType()) 3491 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 3492 else if (Oversized.getBoolValue()) 3493 Diag(NewTD->getLocation(), diag::err_array_too_large) << Oversized.toString(10); 3494 else 3495 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 3496 NewTD->setInvalidDecl(); 3497 } 3498 } 3499 } 3500} 3501 3502 3503/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 3504/// declares a typedef-name, either using the 'typedef' type specifier or via 3505/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 3506NamedDecl* 3507Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 3508 LookupResult &Previous, bool &Redeclaration) { 3509 // Merge the decl with the existing one if appropriate. If the decl is 3510 // in an outer scope, it isn't the same thing. 3511 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false, 3512 /*ExplicitInstantiationOrSpecialization=*/false); 3513 if (!Previous.empty()) { 3514 Redeclaration = true; 3515 MergeTypedefNameDecl(NewTD, Previous); 3516 } 3517 3518 // If this is the C FILE type, notify the AST context. 3519 if (IdentifierInfo *II = NewTD->getIdentifier()) 3520 if (!NewTD->isInvalidDecl() && 3521 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 3522 if (II->isStr("FILE")) 3523 Context.setFILEDecl(NewTD); 3524 else if (II->isStr("jmp_buf")) 3525 Context.setjmp_bufDecl(NewTD); 3526 else if (II->isStr("sigjmp_buf")) 3527 Context.setsigjmp_bufDecl(NewTD); 3528 else if (II->isStr("__builtin_va_list")) 3529 Context.setBuiltinVaListType(Context.getTypedefType(NewTD)); 3530 } 3531 3532 return NewTD; 3533} 3534 3535/// \brief Determines whether the given declaration is an out-of-scope 3536/// previous declaration. 3537/// 3538/// This routine should be invoked when name lookup has found a 3539/// previous declaration (PrevDecl) that is not in the scope where a 3540/// new declaration by the same name is being introduced. If the new 3541/// declaration occurs in a local scope, previous declarations with 3542/// linkage may still be considered previous declarations (C99 3543/// 6.2.2p4-5, C++ [basic.link]p6). 3544/// 3545/// \param PrevDecl the previous declaration found by name 3546/// lookup 3547/// 3548/// \param DC the context in which the new declaration is being 3549/// declared. 3550/// 3551/// \returns true if PrevDecl is an out-of-scope previous declaration 3552/// for a new delcaration with the same name. 3553static bool 3554isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 3555 ASTContext &Context) { 3556 if (!PrevDecl) 3557 return false; 3558 3559 if (!PrevDecl->hasLinkage()) 3560 return false; 3561 3562 if (Context.getLangOptions().CPlusPlus) { 3563 // C++ [basic.link]p6: 3564 // If there is a visible declaration of an entity with linkage 3565 // having the same name and type, ignoring entities declared 3566 // outside the innermost enclosing namespace scope, the block 3567 // scope declaration declares that same entity and receives the 3568 // linkage of the previous declaration. 3569 DeclContext *OuterContext = DC->getRedeclContext(); 3570 if (!OuterContext->isFunctionOrMethod()) 3571 // This rule only applies to block-scope declarations. 3572 return false; 3573 3574 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 3575 if (PrevOuterContext->isRecord()) 3576 // We found a member function: ignore it. 3577 return false; 3578 3579 // Find the innermost enclosing namespace for the new and 3580 // previous declarations. 3581 OuterContext = OuterContext->getEnclosingNamespaceContext(); 3582 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 3583 3584 // The previous declaration is in a different namespace, so it 3585 // isn't the same function. 3586 if (!OuterContext->Equals(PrevOuterContext)) 3587 return false; 3588 } 3589 3590 return true; 3591} 3592 3593static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 3594 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3595 if (!SS.isSet()) return; 3596 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 3597} 3598 3599bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 3600 QualType type = decl->getType(); 3601 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 3602 if (lifetime == Qualifiers::OCL_Autoreleasing) { 3603 // Various kinds of declaration aren't allowed to be __autoreleasing. 3604 unsigned kind = -1U; 3605 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 3606 if (var->hasAttr<BlocksAttr>()) 3607 kind = 0; // __block 3608 else if (!var->hasLocalStorage()) 3609 kind = 1; // global 3610 } else if (isa<ObjCIvarDecl>(decl)) { 3611 kind = 3; // ivar 3612 } else if (isa<FieldDecl>(decl)) { 3613 kind = 2; // field 3614 } 3615 3616 if (kind != -1U) { 3617 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 3618 << kind; 3619 } 3620 } else if (lifetime == Qualifiers::OCL_None) { 3621 // Try to infer lifetime. 3622 if (!type->isObjCLifetimeType()) 3623 return false; 3624 3625 lifetime = type->getObjCARCImplicitLifetime(); 3626 type = Context.getLifetimeQualifiedType(type, lifetime); 3627 decl->setType(type); 3628 } 3629 3630 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 3631 // Thread-local variables cannot have lifetime. 3632 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 3633 var->isThreadSpecified()) { 3634 Diag(var->getLocation(), diag::err_arc_thread_ownership) 3635 << var->getType(); 3636 return true; 3637 } 3638 } 3639 3640 return false; 3641} 3642 3643NamedDecl* 3644Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 3645 QualType R, TypeSourceInfo *TInfo, 3646 LookupResult &Previous, 3647 MultiTemplateParamsArg TemplateParamLists, 3648 bool &Redeclaration) { 3649 DeclarationName Name = GetNameForDeclarator(D).getName(); 3650 3651 // Check that there are no default arguments (C++ only). 3652 if (getLangOptions().CPlusPlus) 3653 CheckExtraCXXDefaultArguments(D); 3654 3655 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 3656 assert(SCSpec != DeclSpec::SCS_typedef && 3657 "Parser allowed 'typedef' as storage class VarDecl."); 3658 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 3659 if (SCSpec == DeclSpec::SCS_mutable) { 3660 // mutable can only appear on non-static class members, so it's always 3661 // an error here 3662 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 3663 D.setInvalidType(); 3664 SC = SC_None; 3665 } 3666 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 3667 VarDecl::StorageClass SCAsWritten 3668 = StorageClassSpecToVarDeclStorageClass(SCSpec); 3669 3670 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3671 if (!II) { 3672 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 3673 << Name.getAsString(); 3674 return 0; 3675 } 3676 3677 DiagnoseFunctionSpecifiers(D); 3678 3679 if (!DC->isRecord() && S->getFnParent() == 0) { 3680 // C99 6.9p2: The storage-class specifiers auto and register shall not 3681 // appear in the declaration specifiers in an external declaration. 3682 if (SC == SC_Auto || SC == SC_Register) { 3683 3684 // If this is a register variable with an asm label specified, then this 3685 // is a GNU extension. 3686 if (SC == SC_Register && D.getAsmLabel()) 3687 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 3688 else 3689 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 3690 D.setInvalidType(); 3691 } 3692 } 3693 3694 bool isExplicitSpecialization = false; 3695 VarDecl *NewVD; 3696 if (!getLangOptions().CPlusPlus) { 3697 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(), 3698 D.getIdentifierLoc(), II, 3699 R, TInfo, SC, SCAsWritten); 3700 3701 if (D.isInvalidType()) 3702 NewVD->setInvalidDecl(); 3703 } else { 3704 if (DC->isRecord() && !CurContext->isRecord()) { 3705 // This is an out-of-line definition of a static data member. 3706 if (SC == SC_Static) { 3707 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 3708 diag::err_static_out_of_line) 3709 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 3710 } else if (SC == SC_None) 3711 SC = SC_Static; 3712 } 3713 if (SC == SC_Static) { 3714 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 3715 if (RD->isLocalClass()) 3716 Diag(D.getIdentifierLoc(), 3717 diag::err_static_data_member_not_allowed_in_local_class) 3718 << Name << RD->getDeclName(); 3719 3720 // C++ [class.union]p1: If a union contains a static data member, 3721 // the program is ill-formed. 3722 // 3723 // We also disallow static data members in anonymous structs. 3724 if (CurContext->isRecord() && (RD->isUnion() || !RD->getDeclName())) 3725 Diag(D.getIdentifierLoc(), 3726 diag::err_static_data_member_not_allowed_in_union_or_anon_struct) 3727 << Name << RD->isUnion(); 3728 } 3729 } 3730 3731 // Match up the template parameter lists with the scope specifier, then 3732 // determine whether we have a template or a template specialization. 3733 isExplicitSpecialization = false; 3734 bool Invalid = false; 3735 if (TemplateParameterList *TemplateParams 3736 = MatchTemplateParametersToScopeSpecifier( 3737 D.getDeclSpec().getSourceRange().getBegin(), 3738 D.getIdentifierLoc(), 3739 D.getCXXScopeSpec(), 3740 TemplateParamLists.get(), 3741 TemplateParamLists.size(), 3742 /*never a friend*/ false, 3743 isExplicitSpecialization, 3744 Invalid)) { 3745 if (TemplateParams->size() > 0) { 3746 // There is no such thing as a variable template. 3747 Diag(D.getIdentifierLoc(), diag::err_template_variable) 3748 << II 3749 << SourceRange(TemplateParams->getTemplateLoc(), 3750 TemplateParams->getRAngleLoc()); 3751 return 0; 3752 } else { 3753 // There is an extraneous 'template<>' for this variable. Complain 3754 // about it, but allow the declaration of the variable. 3755 Diag(TemplateParams->getTemplateLoc(), 3756 diag::err_template_variable_noparams) 3757 << II 3758 << SourceRange(TemplateParams->getTemplateLoc(), 3759 TemplateParams->getRAngleLoc()); 3760 } 3761 } 3762 3763 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(), 3764 D.getIdentifierLoc(), II, 3765 R, TInfo, SC, SCAsWritten); 3766 3767 // If this decl has an auto type in need of deduction, make a note of the 3768 // Decl so we can diagnose uses of it in its own initializer. 3769 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 3770 R->getContainedAutoType()) 3771 ParsingInitForAutoVars.insert(NewVD); 3772 3773 if (D.isInvalidType() || Invalid) 3774 NewVD->setInvalidDecl(); 3775 3776 SetNestedNameSpecifier(NewVD, D); 3777 3778 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) { 3779 NewVD->setTemplateParameterListsInfo(Context, 3780 TemplateParamLists.size(), 3781 TemplateParamLists.release()); 3782 } 3783 3784 if (D.getDeclSpec().isConstexprSpecified()) { 3785 // FIXME: check this is a valid use of constexpr. 3786 NewVD->setConstexpr(true); 3787 } 3788 } 3789 3790 if (D.getDeclSpec().isThreadSpecified()) { 3791 if (NewVD->hasLocalStorage()) 3792 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global); 3793 else if (!Context.Target.isTLSSupported()) 3794 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported); 3795 else 3796 NewVD->setThreadSpecified(true); 3797 } 3798 3799 // Set the lexical context. If the declarator has a C++ scope specifier, the 3800 // lexical context will be different from the semantic context. 3801 NewVD->setLexicalDeclContext(CurContext); 3802 3803 // Handle attributes prior to checking for duplicates in MergeVarDecl 3804 ProcessDeclAttributes(S, NewVD, D); 3805 3806 // In auto-retain/release, infer strong retension for variables of 3807 // retainable type. 3808 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 3809 NewVD->setInvalidDecl(); 3810 3811 // Handle GNU asm-label extension (encoded as an attribute). 3812 if (Expr *E = (Expr*)D.getAsmLabel()) { 3813 // The parser guarantees this is a string. 3814 StringLiteral *SE = cast<StringLiteral>(E); 3815 StringRef Label = SE->getString(); 3816 if (S->getFnParent() != 0) { 3817 switch (SC) { 3818 case SC_None: 3819 case SC_Auto: 3820 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 3821 break; 3822 case SC_Register: 3823 if (!Context.Target.isValidGCCRegisterName(Label)) 3824 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 3825 break; 3826 case SC_Static: 3827 case SC_Extern: 3828 case SC_PrivateExtern: 3829 break; 3830 } 3831 } 3832 3833 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 3834 Context, Label)); 3835 } 3836 3837 // Diagnose shadowed variables before filtering for scope. 3838 if (!D.getCXXScopeSpec().isSet()) 3839 CheckShadow(S, NewVD, Previous); 3840 3841 // Don't consider existing declarations that are in a different 3842 // scope and are out-of-semantic-context declarations (if the new 3843 // declaration has linkage). 3844 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(), 3845 isExplicitSpecialization); 3846 3847 if (!getLangOptions().CPlusPlus) 3848 CheckVariableDeclaration(NewVD, Previous, Redeclaration); 3849 else { 3850 // Merge the decl with the existing one if appropriate. 3851 if (!Previous.empty()) { 3852 if (Previous.isSingleResult() && 3853 isa<FieldDecl>(Previous.getFoundDecl()) && 3854 D.getCXXScopeSpec().isSet()) { 3855 // The user tried to define a non-static data member 3856 // out-of-line (C++ [dcl.meaning]p1). 3857 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 3858 << D.getCXXScopeSpec().getRange(); 3859 Previous.clear(); 3860 NewVD->setInvalidDecl(); 3861 } 3862 } else if (D.getCXXScopeSpec().isSet()) { 3863 // No previous declaration in the qualifying scope. 3864 Diag(D.getIdentifierLoc(), diag::err_no_member) 3865 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 3866 << D.getCXXScopeSpec().getRange(); 3867 NewVD->setInvalidDecl(); 3868 } 3869 3870 CheckVariableDeclaration(NewVD, Previous, Redeclaration); 3871 3872 // This is an explicit specialization of a static data member. Check it. 3873 if (isExplicitSpecialization && !NewVD->isInvalidDecl() && 3874 CheckMemberSpecialization(NewVD, Previous)) 3875 NewVD->setInvalidDecl(); 3876 } 3877 3878 // attributes declared post-definition are currently ignored 3879 // FIXME: This should be handled in attribute merging, not 3880 // here. 3881 if (Previous.isSingleResult()) { 3882 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3883 if (Def && (Def = Def->getDefinition()) && 3884 Def != NewVD && D.hasAttributes()) { 3885 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition); 3886 Diag(Def->getLocation(), diag::note_previous_definition); 3887 } 3888 } 3889 3890 // If this is a locally-scoped extern C variable, update the map of 3891 // such variables. 3892 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() && 3893 !NewVD->isInvalidDecl()) 3894 RegisterLocallyScopedExternCDecl(NewVD, Previous, S); 3895 3896 // If there's a #pragma GCC visibility in scope, and this isn't a class 3897 // member, set the visibility of this variable. 3898 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord()) 3899 AddPushedVisibilityAttribute(NewVD); 3900 3901 MarkUnusedFileScopedDecl(NewVD); 3902 3903 return NewVD; 3904} 3905 3906/// \brief Diagnose variable or built-in function shadowing. Implements 3907/// -Wshadow. 3908/// 3909/// This method is called whenever a VarDecl is added to a "useful" 3910/// scope. 3911/// 3912/// \param S the scope in which the shadowing name is being declared 3913/// \param R the lookup of the name 3914/// 3915void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 3916 // Return if warning is ignored. 3917 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 3918 Diagnostic::Ignored) 3919 return; 3920 3921 // Don't diagnose declarations at file scope. 3922 if (D->hasGlobalStorage()) 3923 return; 3924 3925 DeclContext *NewDC = D->getDeclContext(); 3926 3927 // Only diagnose if we're shadowing an unambiguous field or variable. 3928 if (R.getResultKind() != LookupResult::Found) 3929 return; 3930 3931 NamedDecl* ShadowedDecl = R.getFoundDecl(); 3932 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 3933 return; 3934 3935 // Fields are not shadowed by variables in C++ static methods. 3936 if (isa<FieldDecl>(ShadowedDecl)) 3937 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 3938 if (MD->isStatic()) 3939 return; 3940 3941 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 3942 if (shadowedVar->isExternC()) { 3943 // For shadowing external vars, make sure that we point to the global 3944 // declaration, not a locally scoped extern declaration. 3945 for (VarDecl::redecl_iterator 3946 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end(); 3947 I != E; ++I) 3948 if (I->isFileVarDecl()) { 3949 ShadowedDecl = *I; 3950 break; 3951 } 3952 } 3953 3954 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 3955 3956 // Only warn about certain kinds of shadowing for class members. 3957 if (NewDC && NewDC->isRecord()) { 3958 // In particular, don't warn about shadowing non-class members. 3959 if (!OldDC->isRecord()) 3960 return; 3961 3962 // TODO: should we warn about static data members shadowing 3963 // static data members from base classes? 3964 3965 // TODO: don't diagnose for inaccessible shadowed members. 3966 // This is hard to do perfectly because we might friend the 3967 // shadowing context, but that's just a false negative. 3968 } 3969 3970 // Determine what kind of declaration we're shadowing. 3971 unsigned Kind; 3972 if (isa<RecordDecl>(OldDC)) { 3973 if (isa<FieldDecl>(ShadowedDecl)) 3974 Kind = 3; // field 3975 else 3976 Kind = 2; // static data member 3977 } else if (OldDC->isFileContext()) 3978 Kind = 1; // global 3979 else 3980 Kind = 0; // local 3981 3982 DeclarationName Name = R.getLookupName(); 3983 3984 // Emit warning and note. 3985 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 3986 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 3987} 3988 3989/// \brief Check -Wshadow without the advantage of a previous lookup. 3990void Sema::CheckShadow(Scope *S, VarDecl *D) { 3991 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 3992 Diagnostic::Ignored) 3993 return; 3994 3995 LookupResult R(*this, D->getDeclName(), D->getLocation(), 3996 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 3997 LookupName(R, S); 3998 CheckShadow(S, D, R); 3999} 4000 4001/// \brief Perform semantic checking on a newly-created variable 4002/// declaration. 4003/// 4004/// This routine performs all of the type-checking required for a 4005/// variable declaration once it has been built. It is used both to 4006/// check variables after they have been parsed and their declarators 4007/// have been translated into a declaration, and to check variables 4008/// that have been instantiated from a template. 4009/// 4010/// Sets NewVD->isInvalidDecl() if an error was encountered. 4011void Sema::CheckVariableDeclaration(VarDecl *NewVD, 4012 LookupResult &Previous, 4013 bool &Redeclaration) { 4014 // If the decl is already known invalid, don't check it. 4015 if (NewVD->isInvalidDecl()) 4016 return; 4017 4018 QualType T = NewVD->getType(); 4019 4020 if (T->isObjCObjectType()) { 4021 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 4022 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 4023 T = Context.getObjCObjectPointerType(T); 4024 NewVD->setType(T); 4025 } 4026 4027 // Emit an error if an address space was applied to decl with local storage. 4028 // This includes arrays of objects with address space qualifiers, but not 4029 // automatic variables that point to other address spaces. 4030 // ISO/IEC TR 18037 S5.1.2 4031 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 4032 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 4033 return NewVD->setInvalidDecl(); 4034 } 4035 4036 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 4037 && !NewVD->hasAttr<BlocksAttr>()) { 4038 if (getLangOptions().getGCMode() != LangOptions::NonGC) 4039 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 4040 else 4041 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 4042 } 4043 4044 bool isVM = T->isVariablyModifiedType(); 4045 if (isVM || NewVD->hasAttr<CleanupAttr>() || 4046 NewVD->hasAttr<BlocksAttr>()) 4047 getCurFunction()->setHasBranchProtectedScope(); 4048 4049 if ((isVM && NewVD->hasLinkage()) || 4050 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 4051 bool SizeIsNegative; 4052 llvm::APSInt Oversized; 4053 QualType FixedTy = 4054 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 4055 Oversized); 4056 4057 if (FixedTy.isNull() && T->isVariableArrayType()) { 4058 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 4059 // FIXME: This won't give the correct result for 4060 // int a[10][n]; 4061 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 4062 4063 if (NewVD->isFileVarDecl()) 4064 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 4065 << SizeRange; 4066 else if (NewVD->getStorageClass() == SC_Static) 4067 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 4068 << SizeRange; 4069 else 4070 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 4071 << SizeRange; 4072 return NewVD->setInvalidDecl(); 4073 } 4074 4075 if (FixedTy.isNull()) { 4076 if (NewVD->isFileVarDecl()) 4077 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 4078 else 4079 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 4080 return NewVD->setInvalidDecl(); 4081 } 4082 4083 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 4084 NewVD->setType(FixedTy); 4085 } 4086 4087 if (Previous.empty() && NewVD->isExternC()) { 4088 // Since we did not find anything by this name and we're declaring 4089 // an extern "C" variable, look for a non-visible extern "C" 4090 // declaration with the same name. 4091 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4092 = findLocallyScopedExternalDecl(NewVD->getDeclName()); 4093 if (Pos != LocallyScopedExternalDecls.end()) 4094 Previous.addDecl(Pos->second); 4095 } 4096 4097 if (T->isVoidType() && !NewVD->hasExternalStorage()) { 4098 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 4099 << T; 4100 return NewVD->setInvalidDecl(); 4101 } 4102 4103 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 4104 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 4105 return NewVD->setInvalidDecl(); 4106 } 4107 4108 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 4109 Diag(NewVD->getLocation(), diag::err_block_on_vm); 4110 return NewVD->setInvalidDecl(); 4111 } 4112 4113 // Function pointers and references cannot have qualified function type, only 4114 // function pointer-to-members can do that. 4115 QualType Pointee; 4116 unsigned PtrOrRef = 0; 4117 if (const PointerType *Ptr = T->getAs<PointerType>()) 4118 Pointee = Ptr->getPointeeType(); 4119 else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) { 4120 Pointee = Ref->getPointeeType(); 4121 PtrOrRef = 1; 4122 } 4123 if (!Pointee.isNull() && Pointee->isFunctionProtoType() && 4124 Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) { 4125 Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer) 4126 << PtrOrRef; 4127 return NewVD->setInvalidDecl(); 4128 } 4129 4130 if (!Previous.empty()) { 4131 Redeclaration = true; 4132 MergeVarDecl(NewVD, Previous); 4133 } 4134} 4135 4136/// \brief Data used with FindOverriddenMethod 4137struct FindOverriddenMethodData { 4138 Sema *S; 4139 CXXMethodDecl *Method; 4140}; 4141 4142/// \brief Member lookup function that determines whether a given C++ 4143/// method overrides a method in a base class, to be used with 4144/// CXXRecordDecl::lookupInBases(). 4145static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 4146 CXXBasePath &Path, 4147 void *UserData) { 4148 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 4149 4150 FindOverriddenMethodData *Data 4151 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 4152 4153 DeclarationName Name = Data->Method->getDeclName(); 4154 4155 // FIXME: Do we care about other names here too? 4156 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4157 // We really want to find the base class destructor here. 4158 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 4159 CanQualType CT = Data->S->Context.getCanonicalType(T); 4160 4161 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 4162 } 4163 4164 for (Path.Decls = BaseRecord->lookup(Name); 4165 Path.Decls.first != Path.Decls.second; 4166 ++Path.Decls.first) { 4167 NamedDecl *D = *Path.Decls.first; 4168 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 4169 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 4170 return true; 4171 } 4172 } 4173 4174 return false; 4175} 4176 4177/// AddOverriddenMethods - See if a method overrides any in the base classes, 4178/// and if so, check that it's a valid override and remember it. 4179bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 4180 // Look for virtual methods in base classes that this method might override. 4181 CXXBasePaths Paths; 4182 FindOverriddenMethodData Data; 4183 Data.Method = MD; 4184 Data.S = this; 4185 bool AddedAny = false; 4186 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 4187 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 4188 E = Paths.found_decls_end(); I != E; ++I) { 4189 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 4190 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 4191 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 4192 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 4193 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 4194 AddedAny = true; 4195 } 4196 } 4197 } 4198 } 4199 4200 return AddedAny; 4201} 4202 4203static void DiagnoseInvalidRedeclaration(Sema &S, FunctionDecl *NewFD, 4204 bool isFriendDecl) { 4205 DeclarationName Name = NewFD->getDeclName(); 4206 DeclContext *DC = NewFD->getDeclContext(); 4207 LookupResult Prev(S, Name, NewFD->getLocation(), 4208 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 4209 llvm::SmallVector<unsigned, 1> MismatchedParams; 4210 llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches; 4211 TypoCorrection Correction; 4212 unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend 4213 : diag::err_member_def_does_not_match; 4214 4215 NewFD->setInvalidDecl(); 4216 S.LookupQualifiedName(Prev, DC); 4217 assert(!Prev.isAmbiguous() && 4218 "Cannot have an ambiguity in previous-declaration lookup"); 4219 if (!Prev.empty()) { 4220 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 4221 Func != FuncEnd; ++Func) { 4222 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 4223 if (FD && isNearlyMatchingFunction(S.Context, FD, NewFD, 4224 MismatchedParams)) { 4225 // Add 1 to the index so that 0 can mean the mismatch didn't 4226 // involve a parameter 4227 unsigned ParamNum = 4228 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 4229 NearMatches.push_back(std::make_pair(FD, ParamNum)); 4230 } 4231 } 4232 // If the qualified name lookup yielded nothing, try typo correction 4233 } else if ((Correction = S.CorrectTypo(Prev.getLookupNameInfo(), 4234 Prev.getLookupKind(), 0, 0, DC)) && 4235 Correction.getCorrection() != Name) { 4236 DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest 4237 : diag::err_member_def_does_not_match_suggest; 4238 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 4239 CDeclEnd = Correction.end(); 4240 CDecl != CDeclEnd; ++CDecl) { 4241 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 4242 if (FD && isNearlyMatchingFunction(S.Context, FD, NewFD, 4243 MismatchedParams)) { 4244 // Add 1 to the index so that 0 can mean the mismatch didn't 4245 // involve a parameter 4246 unsigned ParamNum = 4247 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 4248 NearMatches.push_back(std::make_pair(FD, ParamNum)); 4249 } 4250 } 4251 } 4252 4253 if (Correction) 4254 S.Diag(NewFD->getLocation(), DiagMsg) 4255 << Name << DC << Correction.getQuoted(S.getLangOptions()) 4256 << FixItHint::CreateReplacement( 4257 NewFD->getLocation(), Correction.getAsString(S.getLangOptions())); 4258 else 4259 S.Diag(NewFD->getLocation(), DiagMsg) << Name << DC << NewFD->getLocation(); 4260 4261 for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator 4262 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 4263 NearMatch != NearMatchEnd; ++NearMatch) { 4264 FunctionDecl *FD = NearMatch->first; 4265 4266 if (unsigned Idx = NearMatch->second) { 4267 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 4268 S.Diag(FDParam->getTypeSpecStartLoc(), 4269 diag::note_member_def_close_param_match) 4270 << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType(); 4271 } else if (Correction) { 4272 S.Diag(FD->getLocation(), diag::note_previous_decl) 4273 << Correction.getQuoted(S.getLangOptions()); 4274 } else 4275 S.Diag(FD->getLocation(), diag::note_member_def_close_match); 4276 } 4277} 4278 4279NamedDecl* 4280Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4281 QualType R, TypeSourceInfo *TInfo, 4282 LookupResult &Previous, 4283 MultiTemplateParamsArg TemplateParamLists, 4284 bool IsFunctionDefinition, bool &Redeclaration, 4285 bool &AddToScope) { 4286 assert(R.getTypePtr()->isFunctionType()); 4287 4288 // TODO: consider using NameInfo for diagnostic. 4289 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4290 DeclarationName Name = NameInfo.getName(); 4291 FunctionDecl::StorageClass SC = SC_None; 4292 switch (D.getDeclSpec().getStorageClassSpec()) { 4293 default: assert(0 && "Unknown storage class!"); 4294 case DeclSpec::SCS_auto: 4295 case DeclSpec::SCS_register: 4296 case DeclSpec::SCS_mutable: 4297 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4298 diag::err_typecheck_sclass_func); 4299 D.setInvalidType(); 4300 break; 4301 case DeclSpec::SCS_unspecified: SC = SC_None; break; 4302 case DeclSpec::SCS_extern: SC = SC_Extern; break; 4303 case DeclSpec::SCS_static: { 4304 if (CurContext->getRedeclContext()->isFunctionOrMethod()) { 4305 // C99 6.7.1p5: 4306 // The declaration of an identifier for a function that has 4307 // block scope shall have no explicit storage-class specifier 4308 // other than extern 4309 // See also (C++ [dcl.stc]p4). 4310 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4311 diag::err_static_block_func); 4312 SC = SC_None; 4313 } else 4314 SC = SC_Static; 4315 break; 4316 } 4317 case DeclSpec::SCS_private_extern: SC = SC_PrivateExtern; break; 4318 } 4319 4320 if (D.getDeclSpec().isThreadSpecified()) 4321 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 4322 4323 // Do not allow returning a objc interface by-value. 4324 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) { 4325 Diag(D.getIdentifierLoc(), 4326 diag::err_object_cannot_be_passed_returned_by_value) << 0 4327 << R->getAs<FunctionType>()->getResultType() 4328 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*"); 4329 4330 QualType T = R->getAs<FunctionType>()->getResultType(); 4331 T = Context.getObjCObjectPointerType(T); 4332 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) { 4333 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4334 R = Context.getFunctionType(T, FPT->arg_type_begin(), 4335 FPT->getNumArgs(), EPI); 4336 } 4337 else if (isa<FunctionNoProtoType>(R)) 4338 R = Context.getFunctionNoProtoType(T); 4339 } 4340 4341 FunctionDecl *NewFD; 4342 bool isInline = D.getDeclSpec().isInlineSpecified(); 4343 bool isFriend = false; 4344 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 4345 FunctionDecl::StorageClass SCAsWritten 4346 = StorageClassSpecToFunctionDeclStorageClass(SCSpec); 4347 FunctionTemplateDecl *FunctionTemplate = 0; 4348 bool isExplicitSpecialization = false; 4349 bool isFunctionTemplateSpecialization = false; 4350 bool isDependentClassScopeExplicitSpecialization = false; 4351 4352 if (!getLangOptions().CPlusPlus) { 4353 // Determine whether the function was written with a 4354 // prototype. This true when: 4355 // - there is a prototype in the declarator, or 4356 // - the type R of the function is some kind of typedef or other reference 4357 // to a type name (which eventually refers to a function type). 4358 bool HasPrototype = 4359 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 4360 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 4361 4362 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(), 4363 NameInfo, R, TInfo, SC, SCAsWritten, isInline, 4364 HasPrototype); 4365 if (D.isInvalidType()) 4366 NewFD->setInvalidDecl(); 4367 4368 // Set the lexical context. 4369 NewFD->setLexicalDeclContext(CurContext); 4370 // Filter out previous declarations that don't match the scope. 4371 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(), 4372 /*ExplicitInstantiationOrSpecialization=*/false); 4373 } else { 4374 isFriend = D.getDeclSpec().isFriendSpecified(); 4375 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 4376 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 4377 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 4378 bool isVirtualOkay = false; 4379 4380 // Check that the return type is not an abstract class type. 4381 // For record types, this is done by the AbstractClassUsageDiagnoser once 4382 // the class has been completely parsed. 4383 if (!DC->isRecord() && 4384 RequireNonAbstractType(D.getIdentifierLoc(), 4385 R->getAs<FunctionType>()->getResultType(), 4386 diag::err_abstract_type_in_decl, 4387 AbstractReturnType)) 4388 D.setInvalidType(); 4389 4390 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 4391 // This is a C++ constructor declaration. 4392 assert(DC->isRecord() && 4393 "Constructors can only be declared in a member context"); 4394 4395 R = CheckConstructorDeclarator(D, R, SC); 4396 4397 // Create the new declaration 4398 CXXConstructorDecl *NewCD = CXXConstructorDecl::Create( 4399 Context, 4400 cast<CXXRecordDecl>(DC), 4401 D.getSourceRange().getBegin(), 4402 NameInfo, R, TInfo, 4403 isExplicit, isInline, 4404 /*isImplicitlyDeclared=*/false, 4405 isConstexpr); 4406 4407 NewFD = NewCD; 4408 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4409 // This is a C++ destructor declaration. 4410 if (DC->isRecord()) { 4411 R = CheckDestructorDeclarator(D, R, SC); 4412 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 4413 4414 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(Context, Record, 4415 D.getSourceRange().getBegin(), 4416 NameInfo, R, TInfo, 4417 isInline, 4418 /*isImplicitlyDeclared=*/false); 4419 NewFD = NewDD; 4420 isVirtualOkay = true; 4421 4422 // If the class is complete, then we now create the implicit exception 4423 // specification. If the class is incomplete or dependent, we can't do 4424 // it yet. 4425 if (getLangOptions().CPlusPlus0x && !Record->isDependentType() && 4426 Record->getDefinition() && !Record->isBeingDefined() && 4427 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 4428 AdjustDestructorExceptionSpec(Record, NewDD); 4429 } 4430 4431 } else { 4432 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 4433 4434 // Create a FunctionDecl to satisfy the function definition parsing 4435 // code path. 4436 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(), 4437 D.getIdentifierLoc(), Name, R, TInfo, 4438 SC, SCAsWritten, isInline, 4439 /*hasPrototype=*/true, isConstexpr); 4440 D.setInvalidType(); 4441 } 4442 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 4443 if (!DC->isRecord()) { 4444 Diag(D.getIdentifierLoc(), 4445 diag::err_conv_function_not_member); 4446 return 0; 4447 } 4448 4449 CheckConversionDeclarator(D, R, SC); 4450 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC), 4451 D.getSourceRange().getBegin(), 4452 NameInfo, R, TInfo, 4453 isInline, isExplicit, isConstexpr, 4454 SourceLocation()); 4455 4456 isVirtualOkay = true; 4457 } else if (DC->isRecord()) { 4458 // If the name of the function is the same as the name of the record, 4459 // then this must be an invalid constructor that has a return type. 4460 // (The parser checks for a return type and makes the declarator a 4461 // constructor if it has no return type). 4462 if (Name.getAsIdentifierInfo() && 4463 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 4464 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 4465 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 4466 << SourceRange(D.getIdentifierLoc()); 4467 return 0; 4468 } 4469 4470 bool isStatic = SC == SC_Static; 4471 4472 // [class.free]p1: 4473 // Any allocation function for a class T is a static member 4474 // (even if not explicitly declared static). 4475 if (Name.getCXXOverloadedOperator() == OO_New || 4476 Name.getCXXOverloadedOperator() == OO_Array_New) 4477 isStatic = true; 4478 4479 // [class.free]p6 Any deallocation function for a class X is a static member 4480 // (even if not explicitly declared static). 4481 if (Name.getCXXOverloadedOperator() == OO_Delete || 4482 Name.getCXXOverloadedOperator() == OO_Array_Delete) 4483 isStatic = true; 4484 4485 // This is a C++ method declaration. 4486 CXXMethodDecl *NewMD = CXXMethodDecl::Create( 4487 Context, cast<CXXRecordDecl>(DC), 4488 D.getSourceRange().getBegin(), 4489 NameInfo, R, TInfo, 4490 isStatic, SCAsWritten, isInline, 4491 isConstexpr, 4492 SourceLocation()); 4493 NewFD = NewMD; 4494 4495 isVirtualOkay = !isStatic; 4496 } else { 4497 // Determine whether the function was written with a 4498 // prototype. This true when: 4499 // - we're in C++ (where every function has a prototype), 4500 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(), 4501 NameInfo, R, TInfo, SC, SCAsWritten, isInline, 4502 true/*HasPrototype*/, isConstexpr); 4503 } 4504 4505 if (isFriend && !isInline && IsFunctionDefinition) { 4506 // C++ [class.friend]p5 4507 // A function can be defined in a friend declaration of a 4508 // class . . . . Such a function is implicitly inline. 4509 NewFD->setImplicitlyInline(); 4510 } 4511 4512 SetNestedNameSpecifier(NewFD, D); 4513 isExplicitSpecialization = false; 4514 isFunctionTemplateSpecialization = false; 4515 if (D.isInvalidType()) 4516 NewFD->setInvalidDecl(); 4517 4518 // Set the lexical context. If the declarator has a C++ 4519 // scope specifier, or is the object of a friend declaration, the 4520 // lexical context will be different from the semantic context. 4521 NewFD->setLexicalDeclContext(CurContext); 4522 4523 // Match up the template parameter lists with the scope specifier, then 4524 // determine whether we have a template or a template specialization. 4525 bool Invalid = false; 4526 if (TemplateParameterList *TemplateParams 4527 = MatchTemplateParametersToScopeSpecifier( 4528 D.getDeclSpec().getSourceRange().getBegin(), 4529 D.getIdentifierLoc(), 4530 D.getCXXScopeSpec(), 4531 TemplateParamLists.get(), 4532 TemplateParamLists.size(), 4533 isFriend, 4534 isExplicitSpecialization, 4535 Invalid)) { 4536 if (TemplateParams->size() > 0) { 4537 // This is a function template 4538 4539 // Check that we can declare a template here. 4540 if (CheckTemplateDeclScope(S, TemplateParams)) 4541 return 0; 4542 4543 // A destructor cannot be a template. 4544 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4545 Diag(NewFD->getLocation(), diag::err_destructor_template); 4546 return 0; 4547 } 4548 4549 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 4550 NewFD->getLocation(), 4551 Name, TemplateParams, 4552 NewFD); 4553 FunctionTemplate->setLexicalDeclContext(CurContext); 4554 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 4555 4556 // For source fidelity, store the other template param lists. 4557 if (TemplateParamLists.size() > 1) { 4558 NewFD->setTemplateParameterListsInfo(Context, 4559 TemplateParamLists.size() - 1, 4560 TemplateParamLists.release()); 4561 } 4562 } else { 4563 // This is a function template specialization. 4564 isFunctionTemplateSpecialization = true; 4565 // For source fidelity, store all the template param lists. 4566 NewFD->setTemplateParameterListsInfo(Context, 4567 TemplateParamLists.size(), 4568 TemplateParamLists.release()); 4569 4570 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 4571 if (isFriend) { 4572 // We want to remove the "template<>", found here. 4573 SourceRange RemoveRange = TemplateParams->getSourceRange(); 4574 4575 // If we remove the template<> and the name is not a 4576 // template-id, we're actually silently creating a problem: 4577 // the friend declaration will refer to an untemplated decl, 4578 // and clearly the user wants a template specialization. So 4579 // we need to insert '<>' after the name. 4580 SourceLocation InsertLoc; 4581 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 4582 InsertLoc = D.getName().getSourceRange().getEnd(); 4583 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 4584 } 4585 4586 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 4587 << Name << RemoveRange 4588 << FixItHint::CreateRemoval(RemoveRange) 4589 << FixItHint::CreateInsertion(InsertLoc, "<>"); 4590 } 4591 } 4592 } 4593 else { 4594 // All template param lists were matched against the scope specifier: 4595 // this is NOT (an explicit specialization of) a template. 4596 if (TemplateParamLists.size() > 0) 4597 // For source fidelity, store all the template param lists. 4598 NewFD->setTemplateParameterListsInfo(Context, 4599 TemplateParamLists.size(), 4600 TemplateParamLists.release()); 4601 } 4602 4603 if (Invalid) { 4604 NewFD->setInvalidDecl(); 4605 if (FunctionTemplate) 4606 FunctionTemplate->setInvalidDecl(); 4607 } 4608 4609 // C++ [dcl.fct.spec]p5: 4610 // The virtual specifier shall only be used in declarations of 4611 // nonstatic class member functions that appear within a 4612 // member-specification of a class declaration; see 10.3. 4613 // 4614 if (isVirtual && !NewFD->isInvalidDecl()) { 4615 if (!isVirtualOkay) { 4616 Diag(D.getDeclSpec().getVirtualSpecLoc(), 4617 diag::err_virtual_non_function); 4618 } else if (!CurContext->isRecord()) { 4619 // 'virtual' was specified outside of the class. 4620 Diag(D.getDeclSpec().getVirtualSpecLoc(), 4621 diag::err_virtual_out_of_class) 4622 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 4623 } else if (NewFD->getDescribedFunctionTemplate()) { 4624 // C++ [temp.mem]p3: 4625 // A member function template shall not be virtual. 4626 Diag(D.getDeclSpec().getVirtualSpecLoc(), 4627 diag::err_virtual_member_function_template) 4628 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 4629 } else { 4630 // Okay: Add virtual to the method. 4631 NewFD->setVirtualAsWritten(true); 4632 } 4633 } 4634 4635 // C++ [dcl.fct.spec]p3: 4636 // The inline specifier shall not appear on a block scope function declaration. 4637 if (isInline && !NewFD->isInvalidDecl()) { 4638 if (CurContext->isFunctionOrMethod()) { 4639 // 'inline' is not allowed on block scope function declaration. 4640 Diag(D.getDeclSpec().getInlineSpecLoc(), 4641 diag::err_inline_declaration_block_scope) << Name 4642 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 4643 } 4644 } 4645 4646 // C++ [dcl.fct.spec]p6: 4647 // The explicit specifier shall be used only in the declaration of a 4648 // constructor or conversion function within its class definition; see 12.3.1 4649 // and 12.3.2. 4650 if (isExplicit && !NewFD->isInvalidDecl()) { 4651 if (!CurContext->isRecord()) { 4652 // 'explicit' was specified outside of the class. 4653 Diag(D.getDeclSpec().getExplicitSpecLoc(), 4654 diag::err_explicit_out_of_class) 4655 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 4656 } else if (!isa<CXXConstructorDecl>(NewFD) && 4657 !isa<CXXConversionDecl>(NewFD)) { 4658 // 'explicit' was specified on a function that wasn't a constructor 4659 // or conversion function. 4660 Diag(D.getDeclSpec().getExplicitSpecLoc(), 4661 diag::err_explicit_non_ctor_or_conv_function) 4662 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 4663 } 4664 } 4665 4666 if (isConstexpr) { 4667 // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors 4668 // are implicitly inline. 4669 NewFD->setImplicitlyInline(); 4670 4671 // FIXME: If this is a redeclaration, check the original declaration was 4672 // marked constepr. 4673 4674 // C++0x [dcl.constexpr]p3: functions declared constexpr are required to 4675 // be either constructors or to return a literal type. Therefore, 4676 // destructors cannot be declared constexpr. 4677 if (isa<CXXDestructorDecl>(NewFD)) 4678 Diag(D.getDeclSpec().getConstexprSpecLoc(), 4679 diag::err_constexpr_dtor); 4680 } 4681 4682 4683 // Filter out previous declarations that don't match the scope. 4684 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(), 4685 isExplicitSpecialization || 4686 isFunctionTemplateSpecialization); 4687 4688 if (isFriend) { 4689 // For now, claim that the objects have no previous declaration. 4690 if (FunctionTemplate) { 4691 FunctionTemplate->setObjectOfFriendDecl(false); 4692 FunctionTemplate->setAccess(AS_public); 4693 } 4694 NewFD->setObjectOfFriendDecl(false); 4695 NewFD->setAccess(AS_public); 4696 } 4697 4698 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && IsFunctionDefinition) { 4699 // A method is implicitly inline if it's defined in its class 4700 // definition. 4701 NewFD->setImplicitlyInline(); 4702 } 4703 4704 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 4705 !CurContext->isRecord()) { 4706 // C++ [class.static]p1: 4707 // A data or function member of a class may be declared static 4708 // in a class definition, in which case it is a static member of 4709 // the class. 4710 4711 // Complain about the 'static' specifier if it's on an out-of-line 4712 // member function definition. 4713 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4714 diag::err_static_out_of_line) 4715 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 4716 } 4717 } 4718 4719 // Handle GNU asm-label extension (encoded as an attribute). 4720 if (Expr *E = (Expr*) D.getAsmLabel()) { 4721 // The parser guarantees this is a string. 4722 StringLiteral *SE = cast<StringLiteral>(E); 4723 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 4724 SE->getString())); 4725 } 4726 4727 // Copy the parameter declarations from the declarator D to the function 4728 // declaration NewFD, if they are available. First scavenge them into Params. 4729 SmallVector<ParmVarDecl*, 16> Params; 4730 if (D.isFunctionDeclarator()) { 4731 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 4732 4733 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 4734 // function that takes no arguments, not a function that takes a 4735 // single void argument. 4736 // We let through "const void" here because Sema::GetTypeForDeclarator 4737 // already checks for that case. 4738 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 4739 FTI.ArgInfo[0].Param && 4740 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 4741 // Empty arg list, don't push any params. 4742 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param); 4743 4744 // In C++, the empty parameter-type-list must be spelled "void"; a 4745 // typedef of void is not permitted. 4746 if (getLangOptions().CPlusPlus && 4747 Param->getType().getUnqualifiedType() != Context.VoidTy) { 4748 bool IsTypeAlias = false; 4749 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>()) 4750 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl()); 4751 else if (const TemplateSpecializationType *TST = 4752 Param->getType()->getAs<TemplateSpecializationType>()) 4753 IsTypeAlias = TST->isTypeAlias(); 4754 Diag(Param->getLocation(), diag::err_param_typedef_of_void) 4755 << IsTypeAlias; 4756 } 4757 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 4758 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 4759 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 4760 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 4761 Param->setDeclContext(NewFD); 4762 Params.push_back(Param); 4763 4764 if (Param->isInvalidDecl()) 4765 NewFD->setInvalidDecl(); 4766 } 4767 } 4768 4769 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 4770 // When we're declaring a function with a typedef, typeof, etc as in the 4771 // following example, we'll need to synthesize (unnamed) 4772 // parameters for use in the declaration. 4773 // 4774 // @code 4775 // typedef void fn(int); 4776 // fn f; 4777 // @endcode 4778 4779 // Synthesize a parameter for each argument type. 4780 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 4781 AE = FT->arg_type_end(); AI != AE; ++AI) { 4782 ParmVarDecl *Param = 4783 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 4784 Param->setScopeInfo(0, Params.size()); 4785 Params.push_back(Param); 4786 } 4787 } else { 4788 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 4789 "Should not need args for typedef of non-prototype fn"); 4790 } 4791 // Finally, we know we have the right number of parameters, install them. 4792 NewFD->setParams(Params.data(), Params.size()); 4793 4794 // Process the non-inheritable attributes on this declaration. 4795 ProcessDeclAttributes(S, NewFD, D, 4796 /*NonInheritable=*/true, /*Inheritable=*/false); 4797 4798 if (!getLangOptions().CPlusPlus) { 4799 // Perform semantic checking on the function declaration. 4800 bool isExplicitSpecialization=false; 4801 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization, 4802 Redeclaration); 4803 assert((NewFD->isInvalidDecl() || !Redeclaration || 4804 Previous.getResultKind() != LookupResult::FoundOverloaded) && 4805 "previous declaration set still overloaded"); 4806 } else { 4807 // If the declarator is a template-id, translate the parser's template 4808 // argument list into our AST format. 4809 bool HasExplicitTemplateArgs = false; 4810 TemplateArgumentListInfo TemplateArgs; 4811 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 4812 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 4813 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 4814 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 4815 ASTTemplateArgsPtr TemplateArgsPtr(*this, 4816 TemplateId->getTemplateArgs(), 4817 TemplateId->NumArgs); 4818 translateTemplateArguments(TemplateArgsPtr, 4819 TemplateArgs); 4820 TemplateArgsPtr.release(); 4821 4822 HasExplicitTemplateArgs = true; 4823 4824 if (NewFD->isInvalidDecl()) { 4825 HasExplicitTemplateArgs = false; 4826 } else if (FunctionTemplate) { 4827 // Function template with explicit template arguments. 4828 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 4829 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 4830 4831 HasExplicitTemplateArgs = false; 4832 } else if (!isFunctionTemplateSpecialization && 4833 !D.getDeclSpec().isFriendSpecified()) { 4834 // We have encountered something that the user meant to be a 4835 // specialization (because it has explicitly-specified template 4836 // arguments) but that was not introduced with a "template<>" (or had 4837 // too few of them). 4838 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 4839 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 4840 << FixItHint::CreateInsertion( 4841 D.getDeclSpec().getSourceRange().getBegin(), 4842 "template<> "); 4843 isFunctionTemplateSpecialization = true; 4844 } else { 4845 // "friend void foo<>(int);" is an implicit specialization decl. 4846 isFunctionTemplateSpecialization = true; 4847 } 4848 } else if (isFriend && isFunctionTemplateSpecialization) { 4849 // This combination is only possible in a recovery case; the user 4850 // wrote something like: 4851 // template <> friend void foo(int); 4852 // which we're recovering from as if the user had written: 4853 // friend void foo<>(int); 4854 // Go ahead and fake up a template id. 4855 HasExplicitTemplateArgs = true; 4856 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 4857 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 4858 } 4859 4860 // If it's a friend (and only if it's a friend), it's possible 4861 // that either the specialized function type or the specialized 4862 // template is dependent, and therefore matching will fail. In 4863 // this case, don't check the specialization yet. 4864 if (isFunctionTemplateSpecialization && isFriend && 4865 (NewFD->getType()->isDependentType() || DC->isDependentContext())) { 4866 assert(HasExplicitTemplateArgs && 4867 "friend function specialization without template args"); 4868 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 4869 Previous)) 4870 NewFD->setInvalidDecl(); 4871 } else if (isFunctionTemplateSpecialization) { 4872 if (CurContext->isDependentContext() && CurContext->isRecord() 4873 && !isFriend) { 4874 isDependentClassScopeExplicitSpecialization = true; 4875 Diag(NewFD->getLocation(), getLangOptions().Microsoft ? 4876 diag::ext_function_specialization_in_class : 4877 diag::err_function_specialization_in_class) 4878 << NewFD->getDeclName(); 4879 } else if (CheckFunctionTemplateSpecialization(NewFD, 4880 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 4881 Previous)) 4882 NewFD->setInvalidDecl(); 4883 4884 // C++ [dcl.stc]p1: 4885 // A storage-class-specifier shall not be specified in an explicit 4886 // specialization (14.7.3) 4887 if (SC != SC_None) { 4888 if (SC != NewFD->getStorageClass()) 4889 Diag(NewFD->getLocation(), 4890 diag::err_explicit_specialization_inconsistent_storage_class) 4891 << SC 4892 << FixItHint::CreateRemoval( 4893 D.getDeclSpec().getStorageClassSpecLoc()); 4894 4895 else 4896 Diag(NewFD->getLocation(), 4897 diag::ext_explicit_specialization_storage_class) 4898 << FixItHint::CreateRemoval( 4899 D.getDeclSpec().getStorageClassSpecLoc()); 4900 } 4901 4902 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 4903 if (CheckMemberSpecialization(NewFD, Previous)) 4904 NewFD->setInvalidDecl(); 4905 } 4906 4907 // Perform semantic checking on the function declaration. 4908 if (!isDependentClassScopeExplicitSpecialization) 4909 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization, 4910 Redeclaration); 4911 4912 assert((NewFD->isInvalidDecl() || !Redeclaration || 4913 Previous.getResultKind() != LookupResult::FoundOverloaded) && 4914 "previous declaration set still overloaded"); 4915 4916 NamedDecl *PrincipalDecl = (FunctionTemplate 4917 ? cast<NamedDecl>(FunctionTemplate) 4918 : NewFD); 4919 4920 if (isFriend && Redeclaration) { 4921 AccessSpecifier Access = AS_public; 4922 if (!NewFD->isInvalidDecl()) 4923 Access = NewFD->getPreviousDeclaration()->getAccess(); 4924 4925 NewFD->setAccess(Access); 4926 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 4927 4928 PrincipalDecl->setObjectOfFriendDecl(true); 4929 } 4930 4931 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 4932 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 4933 PrincipalDecl->setNonMemberOperator(); 4934 4935 // If we have a function template, check the template parameter 4936 // list. This will check and merge default template arguments. 4937 if (FunctionTemplate) { 4938 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration(); 4939 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 4940 PrevTemplate? PrevTemplate->getTemplateParameters() : 0, 4941 D.getDeclSpec().isFriendSpecified() 4942 ? (IsFunctionDefinition 4943 ? TPC_FriendFunctionTemplateDefinition 4944 : TPC_FriendFunctionTemplate) 4945 : (D.getCXXScopeSpec().isSet() && 4946 DC && DC->isRecord() && 4947 DC->isDependentContext()) 4948 ? TPC_ClassTemplateMember 4949 : TPC_FunctionTemplate); 4950 } 4951 4952 if (NewFD->isInvalidDecl()) { 4953 // Ignore all the rest of this. 4954 } else if (!Redeclaration) { 4955 // Fake up an access specifier if it's supposed to be a class member. 4956 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 4957 NewFD->setAccess(AS_public); 4958 4959 // Qualified decls generally require a previous declaration. 4960 if (D.getCXXScopeSpec().isSet()) { 4961 // ...with the major exception of templated-scope or 4962 // dependent-scope friend declarations. 4963 4964 // TODO: we currently also suppress this check in dependent 4965 // contexts because (1) the parameter depth will be off when 4966 // matching friend templates and (2) we might actually be 4967 // selecting a friend based on a dependent factor. But there 4968 // are situations where these conditions don't apply and we 4969 // can actually do this check immediately. 4970 if (isFriend && 4971 (TemplateParamLists.size() || 4972 D.getCXXScopeSpec().getScopeRep()->isDependent() || 4973 CurContext->isDependentContext())) { 4974 // ignore these 4975 } else { 4976 // The user tried to provide an out-of-line definition for a 4977 // function that is a member of a class or namespace, but there 4978 // was no such member function declared (C++ [class.mfct]p2, 4979 // C++ [namespace.memdef]p2). For example: 4980 // 4981 // class X { 4982 // void f() const; 4983 // }; 4984 // 4985 // void X::f() { } // ill-formed 4986 // 4987 // Complain about this problem, and attempt to suggest close 4988 // matches (e.g., those that differ only in cv-qualifiers and 4989 // whether the parameter types are references). 4990 4991 DiagnoseInvalidRedeclaration(*this, NewFD, false); 4992 } 4993 4994 // Unqualified local friend declarations are required to resolve 4995 // to something. 4996 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 4997 DiagnoseInvalidRedeclaration(*this, NewFD, true); 4998 } 4999 5000 } else if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && 5001 !isFriend && !isFunctionTemplateSpecialization && 5002 !isExplicitSpecialization) { 5003 // An out-of-line member function declaration must also be a 5004 // definition (C++ [dcl.meaning]p1). 5005 // Note that this is not the case for explicit specializations of 5006 // function templates or member functions of class templates, per 5007 // C++ [temp.expl.spec]p2. We also allow these declarations as an extension 5008 // for compatibility with old SWIG code which likes to generate them. 5009 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 5010 << D.getCXXScopeSpec().getRange(); 5011 } 5012 } 5013 5014 5015 // Handle attributes. We need to have merged decls when handling attributes 5016 // (for example to check for conflicts, etc). 5017 // FIXME: This needs to happen before we merge declarations. Then, 5018 // let attribute merging cope with attribute conflicts. 5019 ProcessDeclAttributes(S, NewFD, D, 5020 /*NonInheritable=*/false, /*Inheritable=*/true); 5021 5022 // attributes declared post-definition are currently ignored 5023 // FIXME: This should happen during attribute merging 5024 if (Redeclaration && Previous.isSingleResult()) { 5025 const FunctionDecl *Def; 5026 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl()); 5027 if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) { 5028 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition); 5029 Diag(Def->getLocation(), diag::note_previous_definition); 5030 } 5031 } 5032 5033 AddKnownFunctionAttributes(NewFD); 5034 5035 if (NewFD->hasAttr<OverloadableAttr>() && 5036 !NewFD->getType()->getAs<FunctionProtoType>()) { 5037 Diag(NewFD->getLocation(), 5038 diag::err_attribute_overloadable_no_prototype) 5039 << NewFD; 5040 5041 // Turn this into a variadic function with no parameters. 5042 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 5043 FunctionProtoType::ExtProtoInfo EPI; 5044 EPI.Variadic = true; 5045 EPI.ExtInfo = FT->getExtInfo(); 5046 5047 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI); 5048 NewFD->setType(R); 5049 } 5050 5051 // If there's a #pragma GCC visibility in scope, and this isn't a class 5052 // member, set the visibility of this function. 5053 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord()) 5054 AddPushedVisibilityAttribute(NewFD); 5055 5056 // If this is a locally-scoped extern C function, update the 5057 // map of such names. 5058 if (CurContext->isFunctionOrMethod() && NewFD->isExternC() 5059 && !NewFD->isInvalidDecl()) 5060 RegisterLocallyScopedExternCDecl(NewFD, Previous, S); 5061 5062 // Set this FunctionDecl's range up to the right paren. 5063 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 5064 5065 if (getLangOptions().CPlusPlus) { 5066 if (FunctionTemplate) { 5067 if (NewFD->isInvalidDecl()) 5068 FunctionTemplate->setInvalidDecl(); 5069 return FunctionTemplate; 5070 } 5071 } 5072 5073 MarkUnusedFileScopedDecl(NewFD); 5074 5075 if (getLangOptions().CUDA) 5076 if (IdentifierInfo *II = NewFD->getIdentifier()) 5077 if (!NewFD->isInvalidDecl() && 5078 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5079 if (II->isStr("cudaConfigureCall")) { 5080 if (!R->getAs<FunctionType>()->getResultType()->isScalarType()) 5081 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 5082 5083 Context.setcudaConfigureCallDecl(NewFD); 5084 } 5085 } 5086 5087 // Here we have an function template explicit specialization at class scope. 5088 // The actually specialization will be postponed to template instatiation 5089 // time via the ClassScopeFunctionSpecializationDecl node. 5090 if (isDependentClassScopeExplicitSpecialization) { 5091 ClassScopeFunctionSpecializationDecl *NewSpec = 5092 ClassScopeFunctionSpecializationDecl::Create( 5093 Context, CurContext, SourceLocation(), 5094 cast<CXXMethodDecl>(NewFD)); 5095 CurContext->addDecl(NewSpec); 5096 AddToScope = false; 5097 } 5098 5099 return NewFD; 5100} 5101 5102/// \brief Perform semantic checking of a new function declaration. 5103/// 5104/// Performs semantic analysis of the new function declaration 5105/// NewFD. This routine performs all semantic checking that does not 5106/// require the actual declarator involved in the declaration, and is 5107/// used both for the declaration of functions as they are parsed 5108/// (called via ActOnDeclarator) and for the declaration of functions 5109/// that have been instantiated via C++ template instantiation (called 5110/// via InstantiateDecl). 5111/// 5112/// \param IsExplicitSpecialiation whether this new function declaration is 5113/// an explicit specialization of the previous declaration. 5114/// 5115/// This sets NewFD->isInvalidDecl() to true if there was an error. 5116void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 5117 LookupResult &Previous, 5118 bool IsExplicitSpecialization, 5119 bool &Redeclaration) { 5120 // If NewFD is already known erroneous, don't do any of this checking. 5121 if (NewFD->isInvalidDecl()) { 5122 // If this is a class member, mark the class invalid immediately. 5123 // This avoids some consistency errors later. 5124 if (isa<CXXMethodDecl>(NewFD)) 5125 cast<CXXMethodDecl>(NewFD)->getParent()->setInvalidDecl(); 5126 5127 return; 5128 } 5129 5130 if (NewFD->getResultType()->isVariablyModifiedType()) { 5131 // Functions returning a variably modified type violate C99 6.7.5.2p2 5132 // because all functions have linkage. 5133 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 5134 return NewFD->setInvalidDecl(); 5135 } 5136 5137 if (NewFD->isMain()) 5138 CheckMain(NewFD); 5139 5140 // Check for a previous declaration of this name. 5141 if (Previous.empty() && NewFD->isExternC()) { 5142 // Since we did not find anything by this name and we're declaring 5143 // an extern "C" function, look for a non-visible extern "C" 5144 // declaration with the same name. 5145 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 5146 = findLocallyScopedExternalDecl(NewFD->getDeclName()); 5147 if (Pos != LocallyScopedExternalDecls.end()) 5148 Previous.addDecl(Pos->second); 5149 } 5150 5151 // Merge or overload the declaration with an existing declaration of 5152 // the same name, if appropriate. 5153 if (!Previous.empty()) { 5154 // Determine whether NewFD is an overload of PrevDecl or 5155 // a declaration that requires merging. If it's an overload, 5156 // there's no more work to do here; we'll just add the new 5157 // function to the scope. 5158 5159 NamedDecl *OldDecl = 0; 5160 if (!AllowOverloadingOfFunction(Previous, Context)) { 5161 Redeclaration = true; 5162 OldDecl = Previous.getFoundDecl(); 5163 } else { 5164 switch (CheckOverload(S, NewFD, Previous, OldDecl, 5165 /*NewIsUsingDecl*/ false)) { 5166 case Ovl_Match: 5167 Redeclaration = true; 5168 break; 5169 5170 case Ovl_NonFunction: 5171 Redeclaration = true; 5172 break; 5173 5174 case Ovl_Overload: 5175 Redeclaration = false; 5176 break; 5177 } 5178 5179 if (!getLangOptions().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 5180 // If a function name is overloadable in C, then every function 5181 // with that name must be marked "overloadable". 5182 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 5183 << Redeclaration << NewFD; 5184 NamedDecl *OverloadedDecl = 0; 5185 if (Redeclaration) 5186 OverloadedDecl = OldDecl; 5187 else if (!Previous.empty()) 5188 OverloadedDecl = Previous.getRepresentativeDecl(); 5189 if (OverloadedDecl) 5190 Diag(OverloadedDecl->getLocation(), 5191 diag::note_attribute_overloadable_prev_overload); 5192 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 5193 Context)); 5194 } 5195 } 5196 5197 if (Redeclaration) { 5198 // NewFD and OldDecl represent declarations that need to be 5199 // merged. 5200 if (MergeFunctionDecl(NewFD, OldDecl)) 5201 return NewFD->setInvalidDecl(); 5202 5203 Previous.clear(); 5204 Previous.addDecl(OldDecl); 5205 5206 if (FunctionTemplateDecl *OldTemplateDecl 5207 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 5208 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 5209 FunctionTemplateDecl *NewTemplateDecl 5210 = NewFD->getDescribedFunctionTemplate(); 5211 assert(NewTemplateDecl && "Template/non-template mismatch"); 5212 if (CXXMethodDecl *Method 5213 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 5214 Method->setAccess(OldTemplateDecl->getAccess()); 5215 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 5216 } 5217 5218 // If this is an explicit specialization of a member that is a function 5219 // template, mark it as a member specialization. 5220 if (IsExplicitSpecialization && 5221 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 5222 NewTemplateDecl->setMemberSpecialization(); 5223 assert(OldTemplateDecl->isMemberSpecialization()); 5224 } 5225 } else { 5226 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions 5227 NewFD->setAccess(OldDecl->getAccess()); 5228 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 5229 } 5230 } 5231 } 5232 5233 // Semantic checking for this function declaration (in isolation). 5234 if (getLangOptions().CPlusPlus) { 5235 // C++-specific checks. 5236 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 5237 CheckConstructor(Constructor); 5238 } else if (CXXDestructorDecl *Destructor = 5239 dyn_cast<CXXDestructorDecl>(NewFD)) { 5240 CXXRecordDecl *Record = Destructor->getParent(); 5241 QualType ClassType = Context.getTypeDeclType(Record); 5242 5243 // FIXME: Shouldn't we be able to perform this check even when the class 5244 // type is dependent? Both gcc and edg can handle that. 5245 if (!ClassType->isDependentType()) { 5246 DeclarationName Name 5247 = Context.DeclarationNames.getCXXDestructorName( 5248 Context.getCanonicalType(ClassType)); 5249 if (NewFD->getDeclName() != Name) { 5250 Diag(NewFD->getLocation(), diag::err_destructor_name); 5251 return NewFD->setInvalidDecl(); 5252 } 5253 } 5254 } else if (CXXConversionDecl *Conversion 5255 = dyn_cast<CXXConversionDecl>(NewFD)) { 5256 ActOnConversionDeclarator(Conversion); 5257 } 5258 5259 // Find any virtual functions that this function overrides. 5260 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 5261 if (!Method->isFunctionTemplateSpecialization() && 5262 !Method->getDescribedFunctionTemplate()) { 5263 if (AddOverriddenMethods(Method->getParent(), Method)) { 5264 // If the function was marked as "static", we have a problem. 5265 if (NewFD->getStorageClass() == SC_Static) { 5266 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual) 5267 << NewFD->getDeclName(); 5268 for (CXXMethodDecl::method_iterator 5269 Overridden = Method->begin_overridden_methods(), 5270 OverriddenEnd = Method->end_overridden_methods(); 5271 Overridden != OverriddenEnd; 5272 ++Overridden) { 5273 Diag((*Overridden)->getLocation(), 5274 diag::note_overridden_virtual_function); 5275 } 5276 } 5277 } 5278 } 5279 } 5280 5281 // Extra checking for C++ overloaded operators (C++ [over.oper]). 5282 if (NewFD->isOverloadedOperator() && 5283 CheckOverloadedOperatorDeclaration(NewFD)) 5284 return NewFD->setInvalidDecl(); 5285 5286 // Extra checking for C++0x literal operators (C++0x [over.literal]). 5287 if (NewFD->getLiteralIdentifier() && 5288 CheckLiteralOperatorDeclaration(NewFD)) 5289 return NewFD->setInvalidDecl(); 5290 5291 // In C++, check default arguments now that we have merged decls. Unless 5292 // the lexical context is the class, because in this case this is done 5293 // during delayed parsing anyway. 5294 if (!CurContext->isRecord()) 5295 CheckCXXDefaultArguments(NewFD); 5296 5297 // If this function declares a builtin function, check the type of this 5298 // declaration against the expected type for the builtin. 5299 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 5300 ASTContext::GetBuiltinTypeError Error; 5301 QualType T = Context.GetBuiltinType(BuiltinID, Error); 5302 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 5303 // The type of this function differs from the type of the builtin, 5304 // so forget about the builtin entirely. 5305 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 5306 } 5307 } 5308 } 5309} 5310 5311void Sema::CheckMain(FunctionDecl* FD) { 5312 // C++ [basic.start.main]p3: A program that declares main to be inline 5313 // or static is ill-formed. 5314 // C99 6.7.4p4: In a hosted environment, the inline function specifier 5315 // shall not appear in a declaration of main. 5316 // static main is not an error under C99, but we should warn about it. 5317 bool isInline = FD->isInlineSpecified(); 5318 bool isStatic = FD->getStorageClass() == SC_Static; 5319 if (isInline || isStatic) { 5320 unsigned diagID = diag::warn_unusual_main_decl; 5321 if (isInline || getLangOptions().CPlusPlus) 5322 diagID = diag::err_unusual_main_decl; 5323 5324 int which = isStatic + (isInline << 1) - 1; 5325 Diag(FD->getLocation(), diagID) << which; 5326 } 5327 5328 QualType T = FD->getType(); 5329 assert(T->isFunctionType() && "function decl is not of function type"); 5330 const FunctionType* FT = T->getAs<FunctionType>(); 5331 5332 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 5333 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 5334 FD->setInvalidDecl(true); 5335 } 5336 5337 // Treat protoless main() as nullary. 5338 if (isa<FunctionNoProtoType>(FT)) return; 5339 5340 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 5341 unsigned nparams = FTP->getNumArgs(); 5342 assert(FD->getNumParams() == nparams); 5343 5344 bool HasExtraParameters = (nparams > 3); 5345 5346 // Darwin passes an undocumented fourth argument of type char**. If 5347 // other platforms start sprouting these, the logic below will start 5348 // getting shifty. 5349 if (nparams == 4 && Context.Target.getTriple().isOSDarwin()) 5350 HasExtraParameters = false; 5351 5352 if (HasExtraParameters) { 5353 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 5354 FD->setInvalidDecl(true); 5355 nparams = 3; 5356 } 5357 5358 // FIXME: a lot of the following diagnostics would be improved 5359 // if we had some location information about types. 5360 5361 QualType CharPP = 5362 Context.getPointerType(Context.getPointerType(Context.CharTy)); 5363 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 5364 5365 for (unsigned i = 0; i < nparams; ++i) { 5366 QualType AT = FTP->getArgType(i); 5367 5368 bool mismatch = true; 5369 5370 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 5371 mismatch = false; 5372 else if (Expected[i] == CharPP) { 5373 // As an extension, the following forms are okay: 5374 // char const ** 5375 // char const * const * 5376 // char * const * 5377 5378 QualifierCollector qs; 5379 const PointerType* PT; 5380 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 5381 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 5382 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) { 5383 qs.removeConst(); 5384 mismatch = !qs.empty(); 5385 } 5386 } 5387 5388 if (mismatch) { 5389 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 5390 // TODO: suggest replacing given type with expected type 5391 FD->setInvalidDecl(true); 5392 } 5393 } 5394 5395 if (nparams == 1 && !FD->isInvalidDecl()) { 5396 Diag(FD->getLocation(), diag::warn_main_one_arg); 5397 } 5398 5399 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 5400 Diag(FD->getLocation(), diag::err_main_template_decl); 5401 FD->setInvalidDecl(); 5402 } 5403} 5404 5405bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 5406 // FIXME: Need strict checking. In C89, we need to check for 5407 // any assignment, increment, decrement, function-calls, or 5408 // commas outside of a sizeof. In C99, it's the same list, 5409 // except that the aforementioned are allowed in unevaluated 5410 // expressions. Everything else falls under the 5411 // "may accept other forms of constant expressions" exception. 5412 // (We never end up here for C++, so the constant expression 5413 // rules there don't matter.) 5414 if (Init->isConstantInitializer(Context, false)) 5415 return false; 5416 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 5417 << Init->getSourceRange(); 5418 return true; 5419} 5420 5421namespace { 5422 // Visits an initialization expression to see if OrigDecl is evaluated in 5423 // its own initialization and throws a warning if it does. 5424 class SelfReferenceChecker 5425 : public EvaluatedExprVisitor<SelfReferenceChecker> { 5426 Sema &S; 5427 Decl *OrigDecl; 5428 5429 public: 5430 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 5431 5432 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 5433 S(S), OrigDecl(OrigDecl) { } 5434 5435 void VisitExpr(Expr *E) { 5436 if (isa<ObjCMessageExpr>(*E)) return; 5437 Inherited::VisitExpr(E); 5438 } 5439 5440 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 5441 CheckForSelfReference(E); 5442 Inherited::VisitImplicitCastExpr(E); 5443 } 5444 5445 void CheckForSelfReference(ImplicitCastExpr *E) { 5446 if (E->getCastKind() != CK_LValueToRValue) return; 5447 Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts(); 5448 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr); 5449 if (!DRE) return; 5450 Decl* ReferenceDecl = DRE->getDecl(); 5451 if (OrigDecl != ReferenceDecl) return; 5452 LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName, 5453 Sema::NotForRedeclaration); 5454 S.DiagRuntimeBehavior(SubExpr->getLocStart(), SubExpr, 5455 S.PDiag(diag::warn_uninit_self_reference_in_init) 5456 << Result.getLookupName() 5457 << OrigDecl->getLocation() 5458 << SubExpr->getSourceRange()); 5459 } 5460 }; 5461} 5462 5463/// AddInitializerToDecl - Adds the initializer Init to the 5464/// declaration dcl. If DirectInit is true, this is C++ direct 5465/// initialization rather than copy initialization. 5466void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 5467 bool DirectInit, bool TypeMayContainAuto) { 5468 // If there is no declaration, there was an error parsing it. Just ignore 5469 // the initializer. 5470 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 5471 return; 5472 5473 // Check for self-references within variable initializers. 5474 if (VarDecl *vd = dyn_cast<VarDecl>(RealDecl)) { 5475 // Variables declared within a function/method body are handled 5476 // by a dataflow analysis. 5477 if (!vd->hasLocalStorage() && !vd->isStaticLocal()) 5478 SelfReferenceChecker(*this, RealDecl).VisitExpr(Init); 5479 } 5480 else { 5481 SelfReferenceChecker(*this, RealDecl).VisitExpr(Init); 5482 } 5483 5484 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 5485 // With declarators parsed the way they are, the parser cannot 5486 // distinguish between a normal initializer and a pure-specifier. 5487 // Thus this grotesque test. 5488 IntegerLiteral *IL; 5489 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 5490 Context.getCanonicalType(IL->getType()) == Context.IntTy) 5491 CheckPureMethod(Method, Init->getSourceRange()); 5492 else { 5493 Diag(Method->getLocation(), diag::err_member_function_initialization) 5494 << Method->getDeclName() << Init->getSourceRange(); 5495 Method->setInvalidDecl(); 5496 } 5497 return; 5498 } 5499 5500 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 5501 if (!VDecl) { 5502 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 5503 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 5504 RealDecl->setInvalidDecl(); 5505 return; 5506 } 5507 5508 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 5509 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) { 5510 TypeSourceInfo *DeducedType = 0; 5511 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType)) 5512 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure) 5513 << VDecl->getDeclName() << VDecl->getType() << Init->getType() 5514 << Init->getSourceRange(); 5515 if (!DeducedType) { 5516 RealDecl->setInvalidDecl(); 5517 return; 5518 } 5519 VDecl->setTypeSourceInfo(DeducedType); 5520 VDecl->setType(DeducedType->getType()); 5521 5522 // In ARC, infer lifetime. 5523 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 5524 VDecl->setInvalidDecl(); 5525 5526 // If this is a redeclaration, check that the type we just deduced matches 5527 // the previously declared type. 5528 if (VarDecl *Old = VDecl->getPreviousDeclaration()) 5529 MergeVarDeclTypes(VDecl, Old); 5530 } 5531 5532 5533 // A definition must end up with a complete type, which means it must be 5534 // complete with the restriction that an array type might be completed by the 5535 // initializer; note that later code assumes this restriction. 5536 QualType BaseDeclType = VDecl->getType(); 5537 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 5538 BaseDeclType = Array->getElementType(); 5539 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 5540 diag::err_typecheck_decl_incomplete_type)) { 5541 RealDecl->setInvalidDecl(); 5542 return; 5543 } 5544 5545 // The variable can not have an abstract class type. 5546 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 5547 diag::err_abstract_type_in_decl, 5548 AbstractVariableType)) 5549 VDecl->setInvalidDecl(); 5550 5551 const VarDecl *Def; 5552 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 5553 Diag(VDecl->getLocation(), diag::err_redefinition) 5554 << VDecl->getDeclName(); 5555 Diag(Def->getLocation(), diag::note_previous_definition); 5556 VDecl->setInvalidDecl(); 5557 return; 5558 } 5559 5560 const VarDecl* PrevInit = 0; 5561 if (getLangOptions().CPlusPlus) { 5562 // C++ [class.static.data]p4 5563 // If a static data member is of const integral or const 5564 // enumeration type, its declaration in the class definition can 5565 // specify a constant-initializer which shall be an integral 5566 // constant expression (5.19). In that case, the member can appear 5567 // in integral constant expressions. The member shall still be 5568 // defined in a namespace scope if it is used in the program and the 5569 // namespace scope definition shall not contain an initializer. 5570 // 5571 // We already performed a redefinition check above, but for static 5572 // data members we also need to check whether there was an in-class 5573 // declaration with an initializer. 5574 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 5575 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName(); 5576 Diag(PrevInit->getLocation(), diag::note_previous_definition); 5577 return; 5578 } 5579 5580 if (VDecl->hasLocalStorage()) 5581 getCurFunction()->setHasBranchProtectedScope(); 5582 5583 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 5584 VDecl->setInvalidDecl(); 5585 return; 5586 } 5587 } 5588 5589 // Capture the variable that is being initialized and the style of 5590 // initialization. 5591 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 5592 5593 // FIXME: Poor source location information. 5594 InitializationKind Kind 5595 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(), 5596 Init->getLocStart(), 5597 Init->getLocEnd()) 5598 : InitializationKind::CreateCopy(VDecl->getLocation(), 5599 Init->getLocStart()); 5600 5601 // Get the decls type and save a reference for later, since 5602 // CheckInitializerTypes may change it. 5603 QualType DclT = VDecl->getType(), SavT = DclT; 5604 if (VDecl->isLocalVarDecl()) { 5605 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5 5606 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 5607 VDecl->setInvalidDecl(); 5608 } else if (!VDecl->isInvalidDecl()) { 5609 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 5610 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 5611 MultiExprArg(*this, &Init, 1), 5612 &DclT); 5613 if (Result.isInvalid()) { 5614 VDecl->setInvalidDecl(); 5615 return; 5616 } 5617 5618 Init = Result.takeAs<Expr>(); 5619 5620 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 5621 // Don't check invalid declarations to avoid emitting useless diagnostics. 5622 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 5623 if (VDecl->getStorageClass() == SC_Static) // C99 6.7.8p4. 5624 CheckForConstantInitializer(Init, DclT); 5625 } 5626 } 5627 } else if (VDecl->isStaticDataMember() && 5628 VDecl->getLexicalDeclContext()->isRecord()) { 5629 // This is an in-class initialization for a static data member, e.g., 5630 // 5631 // struct S { 5632 // static const int value = 17; 5633 // }; 5634 5635 // Try to perform the initialization regardless. 5636 if (!VDecl->isInvalidDecl()) { 5637 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 5638 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 5639 MultiExprArg(*this, &Init, 1), 5640 &DclT); 5641 if (Result.isInvalid()) { 5642 VDecl->setInvalidDecl(); 5643 return; 5644 } 5645 5646 Init = Result.takeAs<Expr>(); 5647 } 5648 5649 // C++ [class.mem]p4: 5650 // A member-declarator can contain a constant-initializer only 5651 // if it declares a static member (9.4) of const integral or 5652 // const enumeration type, see 9.4.2. 5653 QualType T = VDecl->getType(); 5654 5655 // Do nothing on dependent types. 5656 if (T->isDependentType()) { 5657 5658 // Require constness. 5659 } else if (!T.isConstQualified()) { 5660 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 5661 << Init->getSourceRange(); 5662 VDecl->setInvalidDecl(); 5663 5664 // We allow integer constant expressions in all cases. 5665 } else if (T->isIntegralOrEnumerationType()) { 5666 // Check whether the expression is a constant expression. 5667 SourceLocation Loc; 5668 if (Init->isValueDependent()) 5669 ; // Nothing to check. 5670 else if (Init->isIntegerConstantExpr(Context, &Loc)) 5671 ; // Ok, it's an ICE! 5672 else if (Init->isEvaluatable(Context)) { 5673 // If we can constant fold the initializer through heroics, accept it, 5674 // but report this as a use of an extension for -pedantic. 5675 Diag(Loc, diag::ext_in_class_initializer_non_constant) 5676 << Init->getSourceRange(); 5677 } else { 5678 // Otherwise, this is some crazy unknown case. Report the issue at the 5679 // location provided by the isIntegerConstantExpr failed check. 5680 Diag(Loc, diag::err_in_class_initializer_non_constant) 5681 << Init->getSourceRange(); 5682 VDecl->setInvalidDecl(); 5683 } 5684 5685 // We allow floating-point constants as an extension in C++03, and 5686 // C++0x has far more complicated rules that we don't really 5687 // implement fully. 5688 } else { 5689 bool Allowed = false; 5690 if (getLangOptions().CPlusPlus0x) { 5691 Allowed = T->isLiteralType(); 5692 } else if (T->isFloatingType()) { // also permits complex, which is ok 5693 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 5694 << T << Init->getSourceRange(); 5695 Allowed = true; 5696 } 5697 5698 if (!Allowed) { 5699 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 5700 << T << Init->getSourceRange(); 5701 VDecl->setInvalidDecl(); 5702 5703 // TODO: there are probably expressions that pass here that shouldn't. 5704 } else if (!Init->isValueDependent() && 5705 !Init->isConstantInitializer(Context, false)) { 5706 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 5707 << Init->getSourceRange(); 5708 VDecl->setInvalidDecl(); 5709 } 5710 } 5711 } else if (VDecl->isFileVarDecl()) { 5712 if (VDecl->getStorageClassAsWritten() == SC_Extern && 5713 (!getLangOptions().CPlusPlus || 5714 !Context.getBaseElementType(VDecl->getType()).isConstQualified())) 5715 Diag(VDecl->getLocation(), diag::warn_extern_init); 5716 if (!VDecl->isInvalidDecl()) { 5717 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 5718 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 5719 MultiExprArg(*this, &Init, 1), 5720 &DclT); 5721 if (Result.isInvalid()) { 5722 VDecl->setInvalidDecl(); 5723 return; 5724 } 5725 5726 Init = Result.takeAs<Expr>(); 5727 } 5728 5729 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 5730 // Don't check invalid declarations to avoid emitting useless diagnostics. 5731 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 5732 // C99 6.7.8p4. All file scoped initializers need to be constant. 5733 CheckForConstantInitializer(Init, DclT); 5734 } 5735 } 5736 // If the type changed, it means we had an incomplete type that was 5737 // completed by the initializer. For example: 5738 // int ary[] = { 1, 3, 5 }; 5739 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 5740 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 5741 VDecl->setType(DclT); 5742 Init->setType(DclT); 5743 } 5744 5745 // Check any implicit conversions within the expression. 5746 CheckImplicitConversions(Init, VDecl->getLocation()); 5747 5748 if (!VDecl->isInvalidDecl()) 5749 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 5750 5751 Init = MaybeCreateExprWithCleanups(Init); 5752 // Attach the initializer to the decl. 5753 VDecl->setInit(Init); 5754 5755 CheckCompleteVariableDeclaration(VDecl); 5756} 5757 5758/// ActOnInitializerError - Given that there was an error parsing an 5759/// initializer for the given declaration, try to return to some form 5760/// of sanity. 5761void Sema::ActOnInitializerError(Decl *D) { 5762 // Our main concern here is re-establishing invariants like "a 5763 // variable's type is either dependent or complete". 5764 if (!D || D->isInvalidDecl()) return; 5765 5766 VarDecl *VD = dyn_cast<VarDecl>(D); 5767 if (!VD) return; 5768 5769 // Auto types are meaningless if we can't make sense of the initializer. 5770 if (ParsingInitForAutoVars.count(D)) { 5771 D->setInvalidDecl(); 5772 return; 5773 } 5774 5775 QualType Ty = VD->getType(); 5776 if (Ty->isDependentType()) return; 5777 5778 // Require a complete type. 5779 if (RequireCompleteType(VD->getLocation(), 5780 Context.getBaseElementType(Ty), 5781 diag::err_typecheck_decl_incomplete_type)) { 5782 VD->setInvalidDecl(); 5783 return; 5784 } 5785 5786 // Require an abstract type. 5787 if (RequireNonAbstractType(VD->getLocation(), Ty, 5788 diag::err_abstract_type_in_decl, 5789 AbstractVariableType)) { 5790 VD->setInvalidDecl(); 5791 return; 5792 } 5793 5794 // Don't bother complaining about constructors or destructors, 5795 // though. 5796} 5797 5798void Sema::ActOnUninitializedDecl(Decl *RealDecl, 5799 bool TypeMayContainAuto) { 5800 // If there is no declaration, there was an error parsing it. Just ignore it. 5801 if (RealDecl == 0) 5802 return; 5803 5804 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 5805 QualType Type = Var->getType(); 5806 5807 // C++0x [dcl.spec.auto]p3 5808 if (TypeMayContainAuto && Type->getContainedAutoType()) { 5809 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 5810 << Var->getDeclName() << Type; 5811 Var->setInvalidDecl(); 5812 return; 5813 } 5814 5815 switch (Var->isThisDeclarationADefinition()) { 5816 case VarDecl::Definition: 5817 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 5818 break; 5819 5820 // We have an out-of-line definition of a static data member 5821 // that has an in-class initializer, so we type-check this like 5822 // a declaration. 5823 // 5824 // Fall through 5825 5826 case VarDecl::DeclarationOnly: 5827 // It's only a declaration. 5828 5829 // Block scope. C99 6.7p7: If an identifier for an object is 5830 // declared with no linkage (C99 6.2.2p6), the type for the 5831 // object shall be complete. 5832 if (!Type->isDependentType() && Var->isLocalVarDecl() && 5833 !Var->getLinkage() && !Var->isInvalidDecl() && 5834 RequireCompleteType(Var->getLocation(), Type, 5835 diag::err_typecheck_decl_incomplete_type)) 5836 Var->setInvalidDecl(); 5837 5838 // Make sure that the type is not abstract. 5839 if (!Type->isDependentType() && !Var->isInvalidDecl() && 5840 RequireNonAbstractType(Var->getLocation(), Type, 5841 diag::err_abstract_type_in_decl, 5842 AbstractVariableType)) 5843 Var->setInvalidDecl(); 5844 return; 5845 5846 case VarDecl::TentativeDefinition: 5847 // File scope. C99 6.9.2p2: A declaration of an identifier for an 5848 // object that has file scope without an initializer, and without a 5849 // storage-class specifier or with the storage-class specifier "static", 5850 // constitutes a tentative definition. Note: A tentative definition with 5851 // external linkage is valid (C99 6.2.2p5). 5852 if (!Var->isInvalidDecl()) { 5853 if (const IncompleteArrayType *ArrayT 5854 = Context.getAsIncompleteArrayType(Type)) { 5855 if (RequireCompleteType(Var->getLocation(), 5856 ArrayT->getElementType(), 5857 diag::err_illegal_decl_array_incomplete_type)) 5858 Var->setInvalidDecl(); 5859 } else if (Var->getStorageClass() == SC_Static) { 5860 // C99 6.9.2p3: If the declaration of an identifier for an object is 5861 // a tentative definition and has internal linkage (C99 6.2.2p3), the 5862 // declared type shall not be an incomplete type. 5863 // NOTE: code such as the following 5864 // static struct s; 5865 // struct s { int a; }; 5866 // is accepted by gcc. Hence here we issue a warning instead of 5867 // an error and we do not invalidate the static declaration. 5868 // NOTE: to avoid multiple warnings, only check the first declaration. 5869 if (Var->getPreviousDeclaration() == 0) 5870 RequireCompleteType(Var->getLocation(), Type, 5871 diag::ext_typecheck_decl_incomplete_type); 5872 } 5873 } 5874 5875 // Record the tentative definition; we're done. 5876 if (!Var->isInvalidDecl()) 5877 TentativeDefinitions.push_back(Var); 5878 return; 5879 } 5880 5881 // Provide a specific diagnostic for uninitialized variable 5882 // definitions with incomplete array type. 5883 if (Type->isIncompleteArrayType()) { 5884 Diag(Var->getLocation(), 5885 diag::err_typecheck_incomplete_array_needs_initializer); 5886 Var->setInvalidDecl(); 5887 return; 5888 } 5889 5890 // Provide a specific diagnostic for uninitialized variable 5891 // definitions with reference type. 5892 if (Type->isReferenceType()) { 5893 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 5894 << Var->getDeclName() 5895 << SourceRange(Var->getLocation(), Var->getLocation()); 5896 Var->setInvalidDecl(); 5897 return; 5898 } 5899 5900 // Do not attempt to type-check the default initializer for a 5901 // variable with dependent type. 5902 if (Type->isDependentType()) 5903 return; 5904 5905 if (Var->isInvalidDecl()) 5906 return; 5907 5908 if (RequireCompleteType(Var->getLocation(), 5909 Context.getBaseElementType(Type), 5910 diag::err_typecheck_decl_incomplete_type)) { 5911 Var->setInvalidDecl(); 5912 return; 5913 } 5914 5915 // The variable can not have an abstract class type. 5916 if (RequireNonAbstractType(Var->getLocation(), Type, 5917 diag::err_abstract_type_in_decl, 5918 AbstractVariableType)) { 5919 Var->setInvalidDecl(); 5920 return; 5921 } 5922 5923 // Check for jumps past the implicit initializer. C++0x 5924 // clarifies that this applies to a "variable with automatic 5925 // storage duration", not a "local variable". 5926 // C++0x [stmt.dcl]p3 5927 // A program that jumps from a point where a variable with automatic 5928 // storage duration is not in scope to a point where it is in scope is 5929 // ill-formed unless the variable has scalar type, class type with a 5930 // trivial default constructor and a trivial destructor, a cv-qualified 5931 // version of one of these types, or an array of one of the preceding 5932 // types and is declared without an initializer. 5933 if (getLangOptions().CPlusPlus && Var->hasLocalStorage()) { 5934 if (const RecordType *Record 5935 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 5936 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 5937 if ((!getLangOptions().CPlusPlus0x && !CXXRecord->isPOD()) || 5938 (getLangOptions().CPlusPlus0x && 5939 (!CXXRecord->hasTrivialDefaultConstructor() || 5940 !CXXRecord->hasTrivialDestructor()))) 5941 getCurFunction()->setHasBranchProtectedScope(); 5942 } 5943 } 5944 5945 // C++03 [dcl.init]p9: 5946 // If no initializer is specified for an object, and the 5947 // object is of (possibly cv-qualified) non-POD class type (or 5948 // array thereof), the object shall be default-initialized; if 5949 // the object is of const-qualified type, the underlying class 5950 // type shall have a user-declared default 5951 // constructor. Otherwise, if no initializer is specified for 5952 // a non- static object, the object and its subobjects, if 5953 // any, have an indeterminate initial value); if the object 5954 // or any of its subobjects are of const-qualified type, the 5955 // program is ill-formed. 5956 // C++0x [dcl.init]p11: 5957 // If no initializer is specified for an object, the object is 5958 // default-initialized; [...]. 5959 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 5960 InitializationKind Kind 5961 = InitializationKind::CreateDefault(Var->getLocation()); 5962 5963 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0); 5964 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, 5965 MultiExprArg(*this, 0, 0)); 5966 if (Init.isInvalid()) 5967 Var->setInvalidDecl(); 5968 else if (Init.get()) 5969 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 5970 5971 CheckCompleteVariableDeclaration(Var); 5972 } 5973} 5974 5975void Sema::ActOnCXXForRangeDecl(Decl *D) { 5976 VarDecl *VD = dyn_cast<VarDecl>(D); 5977 if (!VD) { 5978 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 5979 D->setInvalidDecl(); 5980 return; 5981 } 5982 5983 VD->setCXXForRangeDecl(true); 5984 5985 // for-range-declaration cannot be given a storage class specifier. 5986 int Error = -1; 5987 switch (VD->getStorageClassAsWritten()) { 5988 case SC_None: 5989 break; 5990 case SC_Extern: 5991 Error = 0; 5992 break; 5993 case SC_Static: 5994 Error = 1; 5995 break; 5996 case SC_PrivateExtern: 5997 Error = 2; 5998 break; 5999 case SC_Auto: 6000 Error = 3; 6001 break; 6002 case SC_Register: 6003 Error = 4; 6004 break; 6005 } 6006 // FIXME: constexpr isn't allowed here. 6007 //if (DS.isConstexprSpecified()) 6008 // Error = 5; 6009 if (Error != -1) { 6010 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 6011 << VD->getDeclName() << Error; 6012 D->setInvalidDecl(); 6013 } 6014} 6015 6016void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 6017 if (var->isInvalidDecl()) return; 6018 6019 // In ARC, don't allow jumps past the implicit initialization of a 6020 // local retaining variable. 6021 if (getLangOptions().ObjCAutoRefCount && 6022 var->hasLocalStorage()) { 6023 switch (var->getType().getObjCLifetime()) { 6024 case Qualifiers::OCL_None: 6025 case Qualifiers::OCL_ExplicitNone: 6026 case Qualifiers::OCL_Autoreleasing: 6027 break; 6028 6029 case Qualifiers::OCL_Weak: 6030 case Qualifiers::OCL_Strong: 6031 getCurFunction()->setHasBranchProtectedScope(); 6032 break; 6033 } 6034 } 6035 6036 // All the following checks are C++ only. 6037 if (!getLangOptions().CPlusPlus) return; 6038 6039 QualType baseType = Context.getBaseElementType(var->getType()); 6040 if (baseType->isDependentType()) return; 6041 6042 // __block variables might require us to capture a copy-initializer. 6043 if (var->hasAttr<BlocksAttr>()) { 6044 // It's currently invalid to ever have a __block variable with an 6045 // array type; should we diagnose that here? 6046 6047 // Regardless, we don't want to ignore array nesting when 6048 // constructing this copy. 6049 QualType type = var->getType(); 6050 6051 if (type->isStructureOrClassType()) { 6052 SourceLocation poi = var->getLocation(); 6053 Expr *varRef = new (Context) DeclRefExpr(var, type, VK_LValue, poi); 6054 ExprResult result = 6055 PerformCopyInitialization( 6056 InitializedEntity::InitializeBlock(poi, type, false), 6057 poi, Owned(varRef)); 6058 if (!result.isInvalid()) { 6059 result = MaybeCreateExprWithCleanups(result); 6060 Expr *init = result.takeAs<Expr>(); 6061 Context.setBlockVarCopyInits(var, init); 6062 } 6063 } 6064 } 6065 6066 // Check for global constructors. 6067 if (!var->getDeclContext()->isDependentContext() && 6068 var->hasGlobalStorage() && 6069 !var->isStaticLocal() && 6070 var->getInit() && 6071 !var->getInit()->isConstantInitializer(Context, 6072 baseType->isReferenceType())) 6073 Diag(var->getLocation(), diag::warn_global_constructor) 6074 << var->getInit()->getSourceRange(); 6075 6076 // Require the destructor. 6077 if (const RecordType *recordType = baseType->getAs<RecordType>()) 6078 FinalizeVarWithDestructor(var, recordType); 6079} 6080 6081/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 6082/// any semantic actions necessary after any initializer has been attached. 6083void 6084Sema::FinalizeDeclaration(Decl *ThisDecl) { 6085 // Note that we are no longer parsing the initializer for this declaration. 6086 ParsingInitForAutoVars.erase(ThisDecl); 6087} 6088 6089Sema::DeclGroupPtrTy 6090Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 6091 Decl **Group, unsigned NumDecls) { 6092 SmallVector<Decl*, 8> Decls; 6093 6094 if (DS.isTypeSpecOwned()) 6095 Decls.push_back(DS.getRepAsDecl()); 6096 6097 for (unsigned i = 0; i != NumDecls; ++i) 6098 if (Decl *D = Group[i]) 6099 Decls.push_back(D); 6100 6101 return BuildDeclaratorGroup(Decls.data(), Decls.size(), 6102 DS.getTypeSpecType() == DeclSpec::TST_auto); 6103} 6104 6105/// BuildDeclaratorGroup - convert a list of declarations into a declaration 6106/// group, performing any necessary semantic checking. 6107Sema::DeclGroupPtrTy 6108Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls, 6109 bool TypeMayContainAuto) { 6110 // C++0x [dcl.spec.auto]p7: 6111 // If the type deduced for the template parameter U is not the same in each 6112 // deduction, the program is ill-formed. 6113 // FIXME: When initializer-list support is added, a distinction is needed 6114 // between the deduced type U and the deduced type which 'auto' stands for. 6115 // auto a = 0, b = { 1, 2, 3 }; 6116 // is legal because the deduced type U is 'int' in both cases. 6117 if (TypeMayContainAuto && NumDecls > 1) { 6118 QualType Deduced; 6119 CanQualType DeducedCanon; 6120 VarDecl *DeducedDecl = 0; 6121 for (unsigned i = 0; i != NumDecls; ++i) { 6122 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 6123 AutoType *AT = D->getType()->getContainedAutoType(); 6124 // Don't reissue diagnostics when instantiating a template. 6125 if (AT && D->isInvalidDecl()) 6126 break; 6127 if (AT && AT->isDeduced()) { 6128 QualType U = AT->getDeducedType(); 6129 CanQualType UCanon = Context.getCanonicalType(U); 6130 if (Deduced.isNull()) { 6131 Deduced = U; 6132 DeducedCanon = UCanon; 6133 DeducedDecl = D; 6134 } else if (DeducedCanon != UCanon) { 6135 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 6136 diag::err_auto_different_deductions) 6137 << Deduced << DeducedDecl->getDeclName() 6138 << U << D->getDeclName() 6139 << DeducedDecl->getInit()->getSourceRange() 6140 << D->getInit()->getSourceRange(); 6141 D->setInvalidDecl(); 6142 break; 6143 } 6144 } 6145 } 6146 } 6147 } 6148 6149 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls)); 6150} 6151 6152 6153/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 6154/// to introduce parameters into function prototype scope. 6155Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 6156 const DeclSpec &DS = D.getDeclSpec(); 6157 6158 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 6159 VarDecl::StorageClass StorageClass = SC_None; 6160 VarDecl::StorageClass StorageClassAsWritten = SC_None; 6161 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 6162 StorageClass = SC_Register; 6163 StorageClassAsWritten = SC_Register; 6164 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 6165 Diag(DS.getStorageClassSpecLoc(), 6166 diag::err_invalid_storage_class_in_func_decl); 6167 D.getMutableDeclSpec().ClearStorageClassSpecs(); 6168 } 6169 6170 if (D.getDeclSpec().isThreadSpecified()) 6171 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 6172 if (D.getDeclSpec().isConstexprSpecified()) 6173 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6174 << 0; 6175 6176 DiagnoseFunctionSpecifiers(D); 6177 6178 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6179 QualType parmDeclType = TInfo->getType(); 6180 6181 if (getLangOptions().CPlusPlus) { 6182 // Check that there are no default arguments inside the type of this 6183 // parameter. 6184 CheckExtraCXXDefaultArguments(D); 6185 6186 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 6187 if (D.getCXXScopeSpec().isSet()) { 6188 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 6189 << D.getCXXScopeSpec().getRange(); 6190 D.getCXXScopeSpec().clear(); 6191 } 6192 } 6193 6194 // Ensure we have a valid name 6195 IdentifierInfo *II = 0; 6196 if (D.hasName()) { 6197 II = D.getIdentifier(); 6198 if (!II) { 6199 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 6200 << GetNameForDeclarator(D).getName().getAsString(); 6201 D.setInvalidType(true); 6202 } 6203 } 6204 6205 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 6206 if (II) { 6207 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 6208 ForRedeclaration); 6209 LookupName(R, S); 6210 if (R.isSingleResult()) { 6211 NamedDecl *PrevDecl = R.getFoundDecl(); 6212 if (PrevDecl->isTemplateParameter()) { 6213 // Maybe we will complain about the shadowed template parameter. 6214 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 6215 // Just pretend that we didn't see the previous declaration. 6216 PrevDecl = 0; 6217 } else if (S->isDeclScope(PrevDecl)) { 6218 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 6219 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 6220 6221 // Recover by removing the name 6222 II = 0; 6223 D.SetIdentifier(0, D.getIdentifierLoc()); 6224 D.setInvalidType(true); 6225 } 6226 } 6227 } 6228 6229 // Temporarily put parameter variables in the translation unit, not 6230 // the enclosing context. This prevents them from accidentally 6231 // looking like class members in C++. 6232 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 6233 D.getSourceRange().getBegin(), 6234 D.getIdentifierLoc(), II, 6235 parmDeclType, TInfo, 6236 StorageClass, StorageClassAsWritten); 6237 6238 if (D.isInvalidType()) 6239 New->setInvalidDecl(); 6240 6241 assert(S->isFunctionPrototypeScope()); 6242 assert(S->getFunctionPrototypeDepth() >= 1); 6243 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 6244 S->getNextFunctionPrototypeIndex()); 6245 6246 // Add the parameter declaration into this scope. 6247 S->AddDecl(New); 6248 if (II) 6249 IdResolver.AddDecl(New); 6250 6251 ProcessDeclAttributes(S, New, D); 6252 6253 if (New->hasAttr<BlocksAttr>()) { 6254 Diag(New->getLocation(), diag::err_block_on_nonlocal); 6255 } 6256 return New; 6257} 6258 6259/// \brief Synthesizes a variable for a parameter arising from a 6260/// typedef. 6261ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 6262 SourceLocation Loc, 6263 QualType T) { 6264 /* FIXME: setting StartLoc == Loc. 6265 Would it be worth to modify callers so as to provide proper source 6266 location for the unnamed parameters, embedding the parameter's type? */ 6267 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 6268 T, Context.getTrivialTypeSourceInfo(T, Loc), 6269 SC_None, SC_None, 0); 6270 Param->setImplicit(); 6271 return Param; 6272} 6273 6274void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 6275 ParmVarDecl * const *ParamEnd) { 6276 // Don't diagnose unused-parameter errors in template instantiations; we 6277 // will already have done so in the template itself. 6278 if (!ActiveTemplateInstantiations.empty()) 6279 return; 6280 6281 for (; Param != ParamEnd; ++Param) { 6282 if (!(*Param)->isUsed() && (*Param)->getDeclName() && 6283 !(*Param)->hasAttr<UnusedAttr>()) { 6284 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 6285 << (*Param)->getDeclName(); 6286 } 6287 } 6288} 6289 6290void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 6291 ParmVarDecl * const *ParamEnd, 6292 QualType ReturnTy, 6293 NamedDecl *D) { 6294 if (LangOpts.NumLargeByValueCopy == 0) // No check. 6295 return; 6296 6297 // Warn if the return value is pass-by-value and larger than the specified 6298 // threshold. 6299 if (ReturnTy.isPODType(Context)) { 6300 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 6301 if (Size > LangOpts.NumLargeByValueCopy) 6302 Diag(D->getLocation(), diag::warn_return_value_size) 6303 << D->getDeclName() << Size; 6304 } 6305 6306 // Warn if any parameter is pass-by-value and larger than the specified 6307 // threshold. 6308 for (; Param != ParamEnd; ++Param) { 6309 QualType T = (*Param)->getType(); 6310 if (!T.isPODType(Context)) 6311 continue; 6312 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 6313 if (Size > LangOpts.NumLargeByValueCopy) 6314 Diag((*Param)->getLocation(), diag::warn_parameter_size) 6315 << (*Param)->getDeclName() << Size; 6316 } 6317} 6318 6319ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 6320 SourceLocation NameLoc, IdentifierInfo *Name, 6321 QualType T, TypeSourceInfo *TSInfo, 6322 VarDecl::StorageClass StorageClass, 6323 VarDecl::StorageClass StorageClassAsWritten) { 6324 // In ARC, infer a lifetime qualifier for appropriate parameter types. 6325 if (getLangOptions().ObjCAutoRefCount && 6326 T.getObjCLifetime() == Qualifiers::OCL_None && 6327 T->isObjCLifetimeType()) { 6328 6329 Qualifiers::ObjCLifetime lifetime; 6330 6331 // Special cases for arrays: 6332 // - if it's const, use __unsafe_unretained 6333 // - otherwise, it's an error 6334 if (T->isArrayType()) { 6335 if (!T.isConstQualified()) { 6336 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 6337 << TSInfo->getTypeLoc().getSourceRange(); 6338 } 6339 lifetime = Qualifiers::OCL_ExplicitNone; 6340 } else { 6341 lifetime = T->getObjCARCImplicitLifetime(); 6342 } 6343 T = Context.getLifetimeQualifiedType(T, lifetime); 6344 } 6345 6346 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 6347 Context.getAdjustedParameterType(T), 6348 TSInfo, 6349 StorageClass, StorageClassAsWritten, 6350 0); 6351 6352 // Parameters can not be abstract class types. 6353 // For record types, this is done by the AbstractClassUsageDiagnoser once 6354 // the class has been completely parsed. 6355 if (!CurContext->isRecord() && 6356 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 6357 AbstractParamType)) 6358 New->setInvalidDecl(); 6359 6360 // Parameter declarators cannot be interface types. All ObjC objects are 6361 // passed by reference. 6362 if (T->isObjCObjectType()) { 6363 Diag(NameLoc, 6364 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 6365 << FixItHint::CreateInsertion(NameLoc, "*"); 6366 T = Context.getObjCObjectPointerType(T); 6367 New->setType(T); 6368 } 6369 6370 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 6371 // duration shall not be qualified by an address-space qualifier." 6372 // Since all parameters have automatic store duration, they can not have 6373 // an address space. 6374 if (T.getAddressSpace() != 0) { 6375 Diag(NameLoc, diag::err_arg_with_address_space); 6376 New->setInvalidDecl(); 6377 } 6378 6379 return New; 6380} 6381 6382void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 6383 SourceLocation LocAfterDecls) { 6384 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6385 6386 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 6387 // for a K&R function. 6388 if (!FTI.hasPrototype) { 6389 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 6390 --i; 6391 if (FTI.ArgInfo[i].Param == 0) { 6392 llvm::SmallString<256> Code; 6393 llvm::raw_svector_ostream(Code) << " int " 6394 << FTI.ArgInfo[i].Ident->getName() 6395 << ";\n"; 6396 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 6397 << FTI.ArgInfo[i].Ident 6398 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 6399 6400 // Implicitly declare the argument as type 'int' for lack of a better 6401 // type. 6402 AttributeFactory attrs; 6403 DeclSpec DS(attrs); 6404 const char* PrevSpec; // unused 6405 unsigned DiagID; // unused 6406 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 6407 PrevSpec, DiagID); 6408 Declarator ParamD(DS, Declarator::KNRTypeListContext); 6409 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 6410 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 6411 } 6412 } 6413 } 6414} 6415 6416Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, 6417 Declarator &D) { 6418 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 6419 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 6420 Scope *ParentScope = FnBodyScope->getParent(); 6421 6422 Decl *DP = HandleDeclarator(ParentScope, D, 6423 MultiTemplateParamsArg(*this), 6424 /*IsFunctionDefinition=*/true); 6425 return ActOnStartOfFunctionDef(FnBodyScope, DP); 6426} 6427 6428static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) { 6429 // Don't warn about invalid declarations. 6430 if (FD->isInvalidDecl()) 6431 return false; 6432 6433 // Or declarations that aren't global. 6434 if (!FD->isGlobal()) 6435 return false; 6436 6437 // Don't warn about C++ member functions. 6438 if (isa<CXXMethodDecl>(FD)) 6439 return false; 6440 6441 // Don't warn about 'main'. 6442 if (FD->isMain()) 6443 return false; 6444 6445 // Don't warn about inline functions. 6446 if (FD->isInlined()) 6447 return false; 6448 6449 // Don't warn about function templates. 6450 if (FD->getDescribedFunctionTemplate()) 6451 return false; 6452 6453 // Don't warn about function template specializations. 6454 if (FD->isFunctionTemplateSpecialization()) 6455 return false; 6456 6457 bool MissingPrototype = true; 6458 for (const FunctionDecl *Prev = FD->getPreviousDeclaration(); 6459 Prev; Prev = Prev->getPreviousDeclaration()) { 6460 // Ignore any declarations that occur in function or method 6461 // scope, because they aren't visible from the header. 6462 if (Prev->getDeclContext()->isFunctionOrMethod()) 6463 continue; 6464 6465 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 6466 break; 6467 } 6468 6469 return MissingPrototype; 6470} 6471 6472void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) { 6473 // Don't complain if we're in GNU89 mode and the previous definition 6474 // was an extern inline function. 6475 const FunctionDecl *Definition; 6476 if (FD->isDefined(Definition) && 6477 !canRedefineFunction(Definition, getLangOptions())) { 6478 if (getLangOptions().GNUMode && Definition->isInlineSpecified() && 6479 Definition->getStorageClass() == SC_Extern) 6480 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 6481 << FD->getDeclName() << getLangOptions().CPlusPlus; 6482 else 6483 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 6484 Diag(Definition->getLocation(), diag::note_previous_definition); 6485 } 6486} 6487 6488Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 6489 // Clear the last template instantiation error context. 6490 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 6491 6492 if (!D) 6493 return D; 6494 FunctionDecl *FD = 0; 6495 6496 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 6497 FD = FunTmpl->getTemplatedDecl(); 6498 else 6499 FD = cast<FunctionDecl>(D); 6500 6501 // Enter a new function scope 6502 PushFunctionScope(); 6503 6504 // See if this is a redefinition. 6505 if (!FD->isLateTemplateParsed()) 6506 CheckForFunctionRedefinition(FD); 6507 6508 // Builtin functions cannot be defined. 6509 if (unsigned BuiltinID = FD->getBuiltinID()) { 6510 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 6511 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 6512 FD->setInvalidDecl(); 6513 } 6514 } 6515 6516 // The return type of a function definition must be complete 6517 // (C99 6.9.1p3, C++ [dcl.fct]p6). 6518 QualType ResultType = FD->getResultType(); 6519 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 6520 !FD->isInvalidDecl() && 6521 RequireCompleteType(FD->getLocation(), ResultType, 6522 diag::err_func_def_incomplete_result)) 6523 FD->setInvalidDecl(); 6524 6525 // GNU warning -Wmissing-prototypes: 6526 // Warn if a global function is defined without a previous 6527 // prototype declaration. This warning is issued even if the 6528 // definition itself provides a prototype. The aim is to detect 6529 // global functions that fail to be declared in header files. 6530 if (ShouldWarnAboutMissingPrototype(FD)) 6531 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 6532 6533 if (FnBodyScope) 6534 PushDeclContext(FnBodyScope, FD); 6535 6536 // Check the validity of our function parameters 6537 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 6538 /*CheckParameterNames=*/true); 6539 6540 // Introduce our parameters into the function scope 6541 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 6542 ParmVarDecl *Param = FD->getParamDecl(p); 6543 Param->setOwningFunction(FD); 6544 6545 // If this has an identifier, add it to the scope stack. 6546 if (Param->getIdentifier() && FnBodyScope) { 6547 CheckShadow(FnBodyScope, Param); 6548 6549 PushOnScopeChains(Param, FnBodyScope); 6550 } 6551 } 6552 6553 // Checking attributes of current function definition 6554 // dllimport attribute. 6555 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 6556 if (DA && (!FD->getAttr<DLLExportAttr>())) { 6557 // dllimport attribute cannot be directly applied to definition. 6558 // Microsoft accepts dllimport for functions defined within class scope. 6559 if (!DA->isInherited() && 6560 !(LangOpts.Microsoft && FD->getLexicalDeclContext()->isRecord())) { 6561 Diag(FD->getLocation(), 6562 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 6563 << "dllimport"; 6564 FD->setInvalidDecl(); 6565 return FD; 6566 } 6567 6568 // Visual C++ appears to not think this is an issue, so only issue 6569 // a warning when Microsoft extensions are disabled. 6570 if (!LangOpts.Microsoft) { 6571 // If a symbol previously declared dllimport is later defined, the 6572 // attribute is ignored in subsequent references, and a warning is 6573 // emitted. 6574 Diag(FD->getLocation(), 6575 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6576 << FD->getName() << "dllimport"; 6577 } 6578 } 6579 return FD; 6580} 6581 6582/// \brief Given the set of return statements within a function body, 6583/// compute the variables that are subject to the named return value 6584/// optimization. 6585/// 6586/// Each of the variables that is subject to the named return value 6587/// optimization will be marked as NRVO variables in the AST, and any 6588/// return statement that has a marked NRVO variable as its NRVO candidate can 6589/// use the named return value optimization. 6590/// 6591/// This function applies a very simplistic algorithm for NRVO: if every return 6592/// statement in the function has the same NRVO candidate, that candidate is 6593/// the NRVO variable. 6594/// 6595/// FIXME: Employ a smarter algorithm that accounts for multiple return 6596/// statements and the lifetimes of the NRVO candidates. We should be able to 6597/// find a maximal set of NRVO variables. 6598static void ComputeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 6599 ReturnStmt **Returns = Scope->Returns.data(); 6600 6601 const VarDecl *NRVOCandidate = 0; 6602 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 6603 if (!Returns[I]->getNRVOCandidate()) 6604 return; 6605 6606 if (!NRVOCandidate) 6607 NRVOCandidate = Returns[I]->getNRVOCandidate(); 6608 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 6609 return; 6610 } 6611 6612 if (NRVOCandidate) 6613 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 6614} 6615 6616Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 6617 return ActOnFinishFunctionBody(D, move(BodyArg), false); 6618} 6619 6620Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 6621 bool IsInstantiation) { 6622 FunctionDecl *FD = 0; 6623 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 6624 if (FunTmpl) 6625 FD = FunTmpl->getTemplatedDecl(); 6626 else 6627 FD = dyn_cast_or_null<FunctionDecl>(dcl); 6628 6629 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 6630 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 6631 6632 if (FD) { 6633 FD->setBody(Body); 6634 if (FD->isMain()) { 6635 // C and C++ allow for main to automagically return 0. 6636 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3. 6637 FD->setHasImplicitReturnZero(true); 6638 WP.disableCheckFallThrough(); 6639 } else if (FD->hasAttr<NakedAttr>()) { 6640 // If the function is marked 'naked', don't complain about missing return 6641 // statements. 6642 WP.disableCheckFallThrough(); 6643 } 6644 6645 // MSVC permits the use of pure specifier (=0) on function definition, 6646 // defined at class scope, warn about this non standard construct. 6647 if (getLangOptions().Microsoft && FD->isPure()) 6648 Diag(FD->getLocation(), diag::warn_pure_function_definition); 6649 6650 if (!FD->isInvalidDecl()) { 6651 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 6652 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 6653 FD->getResultType(), FD); 6654 6655 // If this is a constructor, we need a vtable. 6656 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 6657 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 6658 6659 ComputeNRVO(Body, getCurFunction()); 6660 } 6661 6662 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 6663 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 6664 assert(MD == getCurMethodDecl() && "Method parsing confused"); 6665 MD->setBody(Body); 6666 if (Body) 6667 MD->setEndLoc(Body->getLocEnd()); 6668 if (!MD->isInvalidDecl()) { 6669 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 6670 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 6671 MD->getResultType(), MD); 6672 } 6673 if (ObjCShouldCallSuperDealloc) { 6674 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_dealloc); 6675 ObjCShouldCallSuperDealloc = false; 6676 } 6677 } else { 6678 return 0; 6679 } 6680 6681 assert(!ObjCShouldCallSuperDealloc && "This should only be set for " 6682 "ObjC methods, which should have been handled in the block above."); 6683 6684 // Verify and clean out per-function state. 6685 if (Body) { 6686 // C++ constructors that have function-try-blocks can't have return 6687 // statements in the handlers of that block. (C++ [except.handle]p14) 6688 // Verify this. 6689 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 6690 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 6691 6692 // Verify that gotos and switch cases don't jump into scopes illegally. 6693 if (getCurFunction()->NeedsScopeChecking() && 6694 !dcl->isInvalidDecl() && 6695 !hasAnyUnrecoverableErrorsInThisFunction()) 6696 DiagnoseInvalidJumps(Body); 6697 6698 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 6699 if (!Destructor->getParent()->isDependentType()) 6700 CheckDestructor(Destructor); 6701 6702 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 6703 Destructor->getParent()); 6704 } 6705 6706 // If any errors have occurred, clear out any temporaries that may have 6707 // been leftover. This ensures that these temporaries won't be picked up for 6708 // deletion in some later function. 6709 if (PP.getDiagnostics().hasErrorOccurred() || 6710 PP.getDiagnostics().getSuppressAllDiagnostics()) { 6711 ExprTemporaries.clear(); 6712 ExprNeedsCleanups = false; 6713 } else if (!isa<FunctionTemplateDecl>(dcl)) { 6714 // Since the body is valid, issue any analysis-based warnings that are 6715 // enabled. 6716 ActivePolicy = &WP; 6717 } 6718 6719 assert(ExprTemporaries.empty() && "Leftover temporaries in function"); 6720 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 6721 } 6722 6723 if (!IsInstantiation) 6724 PopDeclContext(); 6725 6726 PopFunctionOrBlockScope(ActivePolicy, dcl); 6727 6728 // If any errors have occurred, clear out any temporaries that may have 6729 // been leftover. This ensures that these temporaries won't be picked up for 6730 // deletion in some later function. 6731 if (getDiagnostics().hasErrorOccurred()) { 6732 ExprTemporaries.clear(); 6733 ExprNeedsCleanups = false; 6734 } 6735 6736 return dcl; 6737} 6738 6739/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 6740/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 6741NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 6742 IdentifierInfo &II, Scope *S) { 6743 // Before we produce a declaration for an implicitly defined 6744 // function, see whether there was a locally-scoped declaration of 6745 // this name as a function or variable. If so, use that 6746 // (non-visible) declaration, and complain about it. 6747 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 6748 = findLocallyScopedExternalDecl(&II); 6749 if (Pos != LocallyScopedExternalDecls.end()) { 6750 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 6751 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 6752 return Pos->second; 6753 } 6754 6755 // Extension in C99. Legal in C90, but warn about it. 6756 if (II.getName().startswith("__builtin_")) 6757 Diag(Loc, diag::warn_builtin_unknown) << &II; 6758 else if (getLangOptions().C99) 6759 Diag(Loc, diag::ext_implicit_function_decl) << &II; 6760 else 6761 Diag(Loc, diag::warn_implicit_function_decl) << &II; 6762 6763 // Set a Declarator for the implicit definition: int foo(); 6764 const char *Dummy; 6765 AttributeFactory attrFactory; 6766 DeclSpec DS(attrFactory); 6767 unsigned DiagID; 6768 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 6769 (void)Error; // Silence warning. 6770 assert(!Error && "Error setting up implicit decl!"); 6771 Declarator D(DS, Declarator::BlockContext); 6772 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0, 6773 0, 0, true, SourceLocation(), 6774 SourceLocation(), 6775 EST_None, SourceLocation(), 6776 0, 0, 0, 0, Loc, Loc, D), 6777 DS.getAttributes(), 6778 SourceLocation()); 6779 D.SetIdentifier(&II, Loc); 6780 6781 // Insert this function into translation-unit scope. 6782 6783 DeclContext *PrevDC = CurContext; 6784 CurContext = Context.getTranslationUnitDecl(); 6785 6786 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 6787 FD->setImplicit(); 6788 6789 CurContext = PrevDC; 6790 6791 AddKnownFunctionAttributes(FD); 6792 6793 return FD; 6794} 6795 6796/// \brief Adds any function attributes that we know a priori based on 6797/// the declaration of this function. 6798/// 6799/// These attributes can apply both to implicitly-declared builtins 6800/// (like __builtin___printf_chk) or to library-declared functions 6801/// like NSLog or printf. 6802/// 6803/// We need to check for duplicate attributes both here and where user-written 6804/// attributes are applied to declarations. 6805void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 6806 if (FD->isInvalidDecl()) 6807 return; 6808 6809 // If this is a built-in function, map its builtin attributes to 6810 // actual attributes. 6811 if (unsigned BuiltinID = FD->getBuiltinID()) { 6812 // Handle printf-formatting attributes. 6813 unsigned FormatIdx; 6814 bool HasVAListArg; 6815 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 6816 if (!FD->getAttr<FormatAttr>()) 6817 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 6818 "printf", FormatIdx+1, 6819 HasVAListArg ? 0 : FormatIdx+2)); 6820 } 6821 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 6822 HasVAListArg)) { 6823 if (!FD->getAttr<FormatAttr>()) 6824 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 6825 "scanf", FormatIdx+1, 6826 HasVAListArg ? 0 : FormatIdx+2)); 6827 } 6828 6829 // Mark const if we don't care about errno and that is the only 6830 // thing preventing the function from being const. This allows 6831 // IRgen to use LLVM intrinsics for such functions. 6832 if (!getLangOptions().MathErrno && 6833 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 6834 if (!FD->getAttr<ConstAttr>()) 6835 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 6836 } 6837 6838 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>()) 6839 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context)); 6840 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>()) 6841 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 6842 } 6843 6844 IdentifierInfo *Name = FD->getIdentifier(); 6845 if (!Name) 6846 return; 6847 if ((!getLangOptions().CPlusPlus && 6848 FD->getDeclContext()->isTranslationUnit()) || 6849 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 6850 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 6851 LinkageSpecDecl::lang_c)) { 6852 // Okay: this could be a libc/libm/Objective-C function we know 6853 // about. 6854 } else 6855 return; 6856 6857 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) { 6858 // FIXME: NSLog and NSLogv should be target specific 6859 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) { 6860 // FIXME: We known better than our headers. 6861 const_cast<FormatAttr *>(Format)->setType(Context, "printf"); 6862 } else 6863 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 6864 "printf", 1, 6865 Name->isStr("NSLogv") ? 0 : 2)); 6866 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 6867 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 6868 // target-specific builtins, perhaps? 6869 if (!FD->getAttr<FormatAttr>()) 6870 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 6871 "printf", 2, 6872 Name->isStr("vasprintf") ? 0 : 3)); 6873 } 6874} 6875 6876TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 6877 TypeSourceInfo *TInfo) { 6878 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 6879 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 6880 6881 if (!TInfo) { 6882 assert(D.isInvalidType() && "no declarator info for valid type"); 6883 TInfo = Context.getTrivialTypeSourceInfo(T); 6884 } 6885 6886 // Scope manipulation handled by caller. 6887 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 6888 D.getSourceRange().getBegin(), 6889 D.getIdentifierLoc(), 6890 D.getIdentifier(), 6891 TInfo); 6892 6893 // Bail out immediately if we have an invalid declaration. 6894 if (D.isInvalidType()) { 6895 NewTD->setInvalidDecl(); 6896 return NewTD; 6897 } 6898 6899 // C++ [dcl.typedef]p8: 6900 // If the typedef declaration defines an unnamed class (or 6901 // enum), the first typedef-name declared by the declaration 6902 // to be that class type (or enum type) is used to denote the 6903 // class type (or enum type) for linkage purposes only. 6904 // We need to check whether the type was declared in the declaration. 6905 switch (D.getDeclSpec().getTypeSpecType()) { 6906 case TST_enum: 6907 case TST_struct: 6908 case TST_union: 6909 case TST_class: { 6910 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 6911 6912 // Do nothing if the tag is not anonymous or already has an 6913 // associated typedef (from an earlier typedef in this decl group). 6914 if (tagFromDeclSpec->getIdentifier()) break; 6915 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 6916 6917 // A well-formed anonymous tag must always be a TUK_Definition. 6918 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 6919 6920 // The type must match the tag exactly; no qualifiers allowed. 6921 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 6922 break; 6923 6924 // Otherwise, set this is the anon-decl typedef for the tag. 6925 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 6926 break; 6927 } 6928 6929 default: 6930 break; 6931 } 6932 6933 return NewTD; 6934} 6935 6936 6937/// \brief Determine whether a tag with a given kind is acceptable 6938/// as a redeclaration of the given tag declaration. 6939/// 6940/// \returns true if the new tag kind is acceptable, false otherwise. 6941bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 6942 TagTypeKind NewTag, bool isDefinition, 6943 SourceLocation NewTagLoc, 6944 const IdentifierInfo &Name) { 6945 // C++ [dcl.type.elab]p3: 6946 // The class-key or enum keyword present in the 6947 // elaborated-type-specifier shall agree in kind with the 6948 // declaration to which the name in the elaborated-type-specifier 6949 // refers. This rule also applies to the form of 6950 // elaborated-type-specifier that declares a class-name or 6951 // friend class since it can be construed as referring to the 6952 // definition of the class. Thus, in any 6953 // elaborated-type-specifier, the enum keyword shall be used to 6954 // refer to an enumeration (7.2), the union class-key shall be 6955 // used to refer to a union (clause 9), and either the class or 6956 // struct class-key shall be used to refer to a class (clause 9) 6957 // declared using the class or struct class-key. 6958 TagTypeKind OldTag = Previous->getTagKind(); 6959 if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct)) 6960 if (OldTag == NewTag) 6961 return true; 6962 6963 if ((OldTag == TTK_Struct || OldTag == TTK_Class) && 6964 (NewTag == TTK_Struct || NewTag == TTK_Class)) { 6965 // Warn about the struct/class tag mismatch. 6966 bool isTemplate = false; 6967 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 6968 isTemplate = Record->getDescribedClassTemplate(); 6969 6970 if (!ActiveTemplateInstantiations.empty()) { 6971 // In a template instantiation, do not offer fix-its for tag mismatches 6972 // since they usually mess up the template instead of fixing the problem. 6973 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 6974 << (NewTag == TTK_Class) << isTemplate << &Name; 6975 return true; 6976 } 6977 6978 if (isDefinition) { 6979 // On definitions, check previous tags and issue a fix-it for each 6980 // one that doesn't match the current tag. 6981 if (Previous->getDefinition()) { 6982 // Don't suggest fix-its for redefinitions. 6983 return true; 6984 } 6985 6986 bool previousMismatch = false; 6987 for (TagDecl::redecl_iterator I(Previous->redecls_begin()), 6988 E(Previous->redecls_end()); I != E; ++I) { 6989 if (I->getTagKind() != NewTag) { 6990 if (!previousMismatch) { 6991 previousMismatch = true; 6992 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 6993 << (NewTag == TTK_Class) << isTemplate << &Name; 6994 } 6995 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 6996 << (NewTag == TTK_Class) 6997 << FixItHint::CreateReplacement(I->getInnerLocStart(), 6998 NewTag == TTK_Class? 6999 "class" : "struct"); 7000 } 7001 } 7002 return true; 7003 } 7004 7005 // Check for a previous definition. If current tag and definition 7006 // are same type, do nothing. If no definition, but disagree with 7007 // with previous tag type, give a warning, but no fix-it. 7008 const TagDecl *Redecl = Previous->getDefinition() ? 7009 Previous->getDefinition() : Previous; 7010 if (Redecl->getTagKind() == NewTag) { 7011 return true; 7012 } 7013 7014 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 7015 << (NewTag == TTK_Class) 7016 << isTemplate << &Name; 7017 Diag(Redecl->getLocation(), diag::note_previous_use); 7018 7019 // If there is a previous defintion, suggest a fix-it. 7020 if (Previous->getDefinition()) { 7021 Diag(NewTagLoc, diag::note_struct_class_suggestion) 7022 << (Redecl->getTagKind() == TTK_Class) 7023 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 7024 Redecl->getTagKind() == TTK_Class? "class" : "struct"); 7025 } 7026 7027 return true; 7028 } 7029 return false; 7030} 7031 7032/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 7033/// former case, Name will be non-null. In the later case, Name will be null. 7034/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 7035/// reference/declaration/definition of a tag. 7036Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 7037 SourceLocation KWLoc, CXXScopeSpec &SS, 7038 IdentifierInfo *Name, SourceLocation NameLoc, 7039 AttributeList *Attr, AccessSpecifier AS, 7040 MultiTemplateParamsArg TemplateParameterLists, 7041 bool &OwnedDecl, bool &IsDependent, 7042 bool ScopedEnum, bool ScopedEnumUsesClassTag, 7043 TypeResult UnderlyingType) { 7044 // If this is not a definition, it must have a name. 7045 assert((Name != 0 || TUK == TUK_Definition) && 7046 "Nameless record must be a definition!"); 7047 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 7048 7049 OwnedDecl = false; 7050 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 7051 7052 // FIXME: Check explicit specializations more carefully. 7053 bool isExplicitSpecialization = false; 7054 bool Invalid = false; 7055 7056 // We only need to do this matching if we have template parameters 7057 // or a scope specifier, which also conveniently avoids this work 7058 // for non-C++ cases. 7059 if (TemplateParameterLists.size() > 0 || 7060 (SS.isNotEmpty() && TUK != TUK_Reference)) { 7061 if (TemplateParameterList *TemplateParams 7062 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS, 7063 TemplateParameterLists.get(), 7064 TemplateParameterLists.size(), 7065 TUK == TUK_Friend, 7066 isExplicitSpecialization, 7067 Invalid)) { 7068 if (TemplateParams->size() > 0) { 7069 // This is a declaration or definition of a class template (which may 7070 // be a member of another template). 7071 7072 if (Invalid) 7073 return 0; 7074 7075 OwnedDecl = false; 7076 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 7077 SS, Name, NameLoc, Attr, 7078 TemplateParams, AS, 7079 TemplateParameterLists.size() - 1, 7080 (TemplateParameterList**) TemplateParameterLists.release()); 7081 return Result.get(); 7082 } else { 7083 // The "template<>" header is extraneous. 7084 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 7085 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 7086 isExplicitSpecialization = true; 7087 } 7088 } 7089 } 7090 7091 // Figure out the underlying type if this a enum declaration. We need to do 7092 // this early, because it's needed to detect if this is an incompatible 7093 // redeclaration. 7094 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 7095 7096 if (Kind == TTK_Enum) { 7097 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 7098 // No underlying type explicitly specified, or we failed to parse the 7099 // type, default to int. 7100 EnumUnderlying = Context.IntTy.getTypePtr(); 7101 else if (UnderlyingType.get()) { 7102 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 7103 // integral type; any cv-qualification is ignored. 7104 TypeSourceInfo *TI = 0; 7105 QualType T = GetTypeFromParser(UnderlyingType.get(), &TI); 7106 EnumUnderlying = TI; 7107 7108 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 7109 7110 if (!T->isDependentType() && !T->isIntegralType(Context)) { 7111 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) 7112 << T; 7113 // Recover by falling back to int. 7114 EnumUnderlying = Context.IntTy.getTypePtr(); 7115 } 7116 7117 if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI, 7118 UPPC_FixedUnderlyingType)) 7119 EnumUnderlying = Context.IntTy.getTypePtr(); 7120 7121 } else if (getLangOptions().Microsoft) 7122 // Microsoft enums are always of int type. 7123 EnumUnderlying = Context.IntTy.getTypePtr(); 7124 } 7125 7126 DeclContext *SearchDC = CurContext; 7127 DeclContext *DC = CurContext; 7128 bool isStdBadAlloc = false; 7129 7130 RedeclarationKind Redecl = ForRedeclaration; 7131 if (TUK == TUK_Friend || TUK == TUK_Reference) 7132 Redecl = NotForRedeclaration; 7133 7134 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 7135 7136 if (Name && SS.isNotEmpty()) { 7137 // We have a nested-name tag ('struct foo::bar'). 7138 7139 // Check for invalid 'foo::'. 7140 if (SS.isInvalid()) { 7141 Name = 0; 7142 goto CreateNewDecl; 7143 } 7144 7145 // If this is a friend or a reference to a class in a dependent 7146 // context, don't try to make a decl for it. 7147 if (TUK == TUK_Friend || TUK == TUK_Reference) { 7148 DC = computeDeclContext(SS, false); 7149 if (!DC) { 7150 IsDependent = true; 7151 return 0; 7152 } 7153 } else { 7154 DC = computeDeclContext(SS, true); 7155 if (!DC) { 7156 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 7157 << SS.getRange(); 7158 return 0; 7159 } 7160 } 7161 7162 if (RequireCompleteDeclContext(SS, DC)) 7163 return 0; 7164 7165 SearchDC = DC; 7166 // Look-up name inside 'foo::'. 7167 LookupQualifiedName(Previous, DC); 7168 7169 if (Previous.isAmbiguous()) 7170 return 0; 7171 7172 if (Previous.empty()) { 7173 // Name lookup did not find anything. However, if the 7174 // nested-name-specifier refers to the current instantiation, 7175 // and that current instantiation has any dependent base 7176 // classes, we might find something at instantiation time: treat 7177 // this as a dependent elaborated-type-specifier. 7178 // But this only makes any sense for reference-like lookups. 7179 if (Previous.wasNotFoundInCurrentInstantiation() && 7180 (TUK == TUK_Reference || TUK == TUK_Friend)) { 7181 IsDependent = true; 7182 return 0; 7183 } 7184 7185 // A tag 'foo::bar' must already exist. 7186 Diag(NameLoc, diag::err_not_tag_in_scope) 7187 << Kind << Name << DC << SS.getRange(); 7188 Name = 0; 7189 Invalid = true; 7190 goto CreateNewDecl; 7191 } 7192 } else if (Name) { 7193 // If this is a named struct, check to see if there was a previous forward 7194 // declaration or definition. 7195 // FIXME: We're looking into outer scopes here, even when we 7196 // shouldn't be. Doing so can result in ambiguities that we 7197 // shouldn't be diagnosing. 7198 LookupName(Previous, S); 7199 7200 if (Previous.isAmbiguous() && 7201 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 7202 LookupResult::Filter F = Previous.makeFilter(); 7203 while (F.hasNext()) { 7204 NamedDecl *ND = F.next(); 7205 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 7206 F.erase(); 7207 } 7208 F.done(); 7209 } 7210 7211 // Note: there used to be some attempt at recovery here. 7212 if (Previous.isAmbiguous()) 7213 return 0; 7214 7215 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) { 7216 // FIXME: This makes sure that we ignore the contexts associated 7217 // with C structs, unions, and enums when looking for a matching 7218 // tag declaration or definition. See the similar lookup tweak 7219 // in Sema::LookupName; is there a better way to deal with this? 7220 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 7221 SearchDC = SearchDC->getParent(); 7222 } 7223 } else if (S->isFunctionPrototypeScope()) { 7224 // If this is an enum declaration in function prototype scope, set its 7225 // initial context to the translation unit. 7226 SearchDC = Context.getTranslationUnitDecl(); 7227 } 7228 7229 if (Previous.isSingleResult() && 7230 Previous.getFoundDecl()->isTemplateParameter()) { 7231 // Maybe we will complain about the shadowed template parameter. 7232 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 7233 // Just pretend that we didn't see the previous declaration. 7234 Previous.clear(); 7235 } 7236 7237 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace && 7238 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 7239 // This is a declaration of or a reference to "std::bad_alloc". 7240 isStdBadAlloc = true; 7241 7242 if (Previous.empty() && StdBadAlloc) { 7243 // std::bad_alloc has been implicitly declared (but made invisible to 7244 // name lookup). Fill in this implicit declaration as the previous 7245 // declaration, so that the declarations get chained appropriately. 7246 Previous.addDecl(getStdBadAlloc()); 7247 } 7248 } 7249 7250 // If we didn't find a previous declaration, and this is a reference 7251 // (or friend reference), move to the correct scope. In C++, we 7252 // also need to do a redeclaration lookup there, just in case 7253 // there's a shadow friend decl. 7254 if (Name && Previous.empty() && 7255 (TUK == TUK_Reference || TUK == TUK_Friend)) { 7256 if (Invalid) goto CreateNewDecl; 7257 assert(SS.isEmpty()); 7258 7259 if (TUK == TUK_Reference) { 7260 // C++ [basic.scope.pdecl]p5: 7261 // -- for an elaborated-type-specifier of the form 7262 // 7263 // class-key identifier 7264 // 7265 // if the elaborated-type-specifier is used in the 7266 // decl-specifier-seq or parameter-declaration-clause of a 7267 // function defined in namespace scope, the identifier is 7268 // declared as a class-name in the namespace that contains 7269 // the declaration; otherwise, except as a friend 7270 // declaration, the identifier is declared in the smallest 7271 // non-class, non-function-prototype scope that contains the 7272 // declaration. 7273 // 7274 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 7275 // C structs and unions. 7276 // 7277 // It is an error in C++ to declare (rather than define) an enum 7278 // type, including via an elaborated type specifier. We'll 7279 // diagnose that later; for now, declare the enum in the same 7280 // scope as we would have picked for any other tag type. 7281 // 7282 // GNU C also supports this behavior as part of its incomplete 7283 // enum types extension, while GNU C++ does not. 7284 // 7285 // Find the context where we'll be declaring the tag. 7286 // FIXME: We would like to maintain the current DeclContext as the 7287 // lexical context, 7288 while (SearchDC->isRecord() || SearchDC->isTransparentContext()) 7289 SearchDC = SearchDC->getParent(); 7290 7291 // Find the scope where we'll be declaring the tag. 7292 while (S->isClassScope() || 7293 (getLangOptions().CPlusPlus && 7294 S->isFunctionPrototypeScope()) || 7295 ((S->getFlags() & Scope::DeclScope) == 0) || 7296 (S->getEntity() && 7297 ((DeclContext *)S->getEntity())->isTransparentContext())) 7298 S = S->getParent(); 7299 } else { 7300 assert(TUK == TUK_Friend); 7301 // C++ [namespace.memdef]p3: 7302 // If a friend declaration in a non-local class first declares a 7303 // class or function, the friend class or function is a member of 7304 // the innermost enclosing namespace. 7305 SearchDC = SearchDC->getEnclosingNamespaceContext(); 7306 } 7307 7308 // In C++, we need to do a redeclaration lookup to properly 7309 // diagnose some problems. 7310 if (getLangOptions().CPlusPlus) { 7311 Previous.setRedeclarationKind(ForRedeclaration); 7312 LookupQualifiedName(Previous, SearchDC); 7313 } 7314 } 7315 7316 if (!Previous.empty()) { 7317 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 7318 7319 // It's okay to have a tag decl in the same scope as a typedef 7320 // which hides a tag decl in the same scope. Finding this 7321 // insanity with a redeclaration lookup can only actually happen 7322 // in C++. 7323 // 7324 // This is also okay for elaborated-type-specifiers, which is 7325 // technically forbidden by the current standard but which is 7326 // okay according to the likely resolution of an open issue; 7327 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 7328 if (getLangOptions().CPlusPlus) { 7329 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 7330 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 7331 TagDecl *Tag = TT->getDecl(); 7332 if (Tag->getDeclName() == Name && 7333 Tag->getDeclContext()->getRedeclContext() 7334 ->Equals(TD->getDeclContext()->getRedeclContext())) { 7335 PrevDecl = Tag; 7336 Previous.clear(); 7337 Previous.addDecl(Tag); 7338 Previous.resolveKind(); 7339 } 7340 } 7341 } 7342 } 7343 7344 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 7345 // If this is a use of a previous tag, or if the tag is already declared 7346 // in the same scope (so that the definition/declaration completes or 7347 // rementions the tag), reuse the decl. 7348 if (TUK == TUK_Reference || TUK == TUK_Friend || 7349 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) { 7350 // Make sure that this wasn't declared as an enum and now used as a 7351 // struct or something similar. 7352 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 7353 TUK == TUK_Definition, KWLoc, 7354 *Name)) { 7355 bool SafeToContinue 7356 = (PrevTagDecl->getTagKind() != TTK_Enum && 7357 Kind != TTK_Enum); 7358 if (SafeToContinue) 7359 Diag(KWLoc, diag::err_use_with_wrong_tag) 7360 << Name 7361 << FixItHint::CreateReplacement(SourceRange(KWLoc), 7362 PrevTagDecl->getKindName()); 7363 else 7364 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 7365 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7366 7367 if (SafeToContinue) 7368 Kind = PrevTagDecl->getTagKind(); 7369 else { 7370 // Recover by making this an anonymous redefinition. 7371 Name = 0; 7372 Previous.clear(); 7373 Invalid = true; 7374 } 7375 } 7376 7377 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 7378 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 7379 7380 // All conflicts with previous declarations are recovered by 7381 // returning the previous declaration. 7382 if (ScopedEnum != PrevEnum->isScoped()) { 7383 Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch) 7384 << PrevEnum->isScoped(); 7385 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7386 return PrevTagDecl; 7387 } 7388 else if (EnumUnderlying && PrevEnum->isFixed()) { 7389 QualType T; 7390 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 7391 T = TI->getType(); 7392 else 7393 T = QualType(EnumUnderlying.get<const Type*>(), 0); 7394 7395 if (!Context.hasSameUnqualifiedType(T, PrevEnum->getIntegerType())) { 7396 Diag(NameLoc.isValid() ? NameLoc : KWLoc, 7397 diag::err_enum_redeclare_type_mismatch) 7398 << T 7399 << PrevEnum->getIntegerType(); 7400 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7401 return PrevTagDecl; 7402 } 7403 } 7404 else if (!EnumUnderlying.isNull() != PrevEnum->isFixed()) { 7405 Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch) 7406 << PrevEnum->isFixed(); 7407 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7408 return PrevTagDecl; 7409 } 7410 } 7411 7412 if (!Invalid) { 7413 // If this is a use, just return the declaration we found. 7414 7415 // FIXME: In the future, return a variant or some other clue 7416 // for the consumer of this Decl to know it doesn't own it. 7417 // For our current ASTs this shouldn't be a problem, but will 7418 // need to be changed with DeclGroups. 7419 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 7420 getLangOptions().Microsoft)) || TUK == TUK_Friend) 7421 return PrevTagDecl; 7422 7423 // Diagnose attempts to redefine a tag. 7424 if (TUK == TUK_Definition) { 7425 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 7426 // If we're defining a specialization and the previous definition 7427 // is from an implicit instantiation, don't emit an error 7428 // here; we'll catch this in the general case below. 7429 if (!isExplicitSpecialization || 7430 !isa<CXXRecordDecl>(Def) || 7431 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind() 7432 == TSK_ExplicitSpecialization) { 7433 Diag(NameLoc, diag::err_redefinition) << Name; 7434 Diag(Def->getLocation(), diag::note_previous_definition); 7435 // If this is a redefinition, recover by making this 7436 // struct be anonymous, which will make any later 7437 // references get the previous definition. 7438 Name = 0; 7439 Previous.clear(); 7440 Invalid = true; 7441 } 7442 } else { 7443 // If the type is currently being defined, complain 7444 // about a nested redefinition. 7445 const TagType *Tag 7446 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 7447 if (Tag->isBeingDefined()) { 7448 Diag(NameLoc, diag::err_nested_redefinition) << Name; 7449 Diag(PrevTagDecl->getLocation(), 7450 diag::note_previous_definition); 7451 Name = 0; 7452 Previous.clear(); 7453 Invalid = true; 7454 } 7455 } 7456 7457 // Okay, this is definition of a previously declared or referenced 7458 // tag PrevDecl. We're going to create a new Decl for it. 7459 } 7460 } 7461 // If we get here we have (another) forward declaration or we 7462 // have a definition. Just create a new decl. 7463 7464 } else { 7465 // If we get here, this is a definition of a new tag type in a nested 7466 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 7467 // new decl/type. We set PrevDecl to NULL so that the entities 7468 // have distinct types. 7469 Previous.clear(); 7470 } 7471 // If we get here, we're going to create a new Decl. If PrevDecl 7472 // is non-NULL, it's a definition of the tag declared by 7473 // PrevDecl. If it's NULL, we have a new definition. 7474 7475 7476 // Otherwise, PrevDecl is not a tag, but was found with tag 7477 // lookup. This is only actually possible in C++, where a few 7478 // things like templates still live in the tag namespace. 7479 } else { 7480 assert(getLangOptions().CPlusPlus); 7481 7482 // Use a better diagnostic if an elaborated-type-specifier 7483 // found the wrong kind of type on the first 7484 // (non-redeclaration) lookup. 7485 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 7486 !Previous.isForRedeclaration()) { 7487 unsigned Kind = 0; 7488 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 7489 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 7490 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 7491 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 7492 Diag(PrevDecl->getLocation(), diag::note_declared_at); 7493 Invalid = true; 7494 7495 // Otherwise, only diagnose if the declaration is in scope. 7496 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 7497 isExplicitSpecialization)) { 7498 // do nothing 7499 7500 // Diagnose implicit declarations introduced by elaborated types. 7501 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 7502 unsigned Kind = 0; 7503 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 7504 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 7505 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 7506 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 7507 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 7508 Invalid = true; 7509 7510 // Otherwise it's a declaration. Call out a particularly common 7511 // case here. 7512 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 7513 unsigned Kind = 0; 7514 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 7515 Diag(NameLoc, diag::err_tag_definition_of_typedef) 7516 << Name << Kind << TND->getUnderlyingType(); 7517 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 7518 Invalid = true; 7519 7520 // Otherwise, diagnose. 7521 } else { 7522 // The tag name clashes with something else in the target scope, 7523 // issue an error and recover by making this tag be anonymous. 7524 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 7525 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7526 Name = 0; 7527 Invalid = true; 7528 } 7529 7530 // The existing declaration isn't relevant to us; we're in a 7531 // new scope, so clear out the previous declaration. 7532 Previous.clear(); 7533 } 7534 } 7535 7536CreateNewDecl: 7537 7538 TagDecl *PrevDecl = 0; 7539 if (Previous.isSingleResult()) 7540 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 7541 7542 // If there is an identifier, use the location of the identifier as the 7543 // location of the decl, otherwise use the location of the struct/union 7544 // keyword. 7545 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 7546 7547 // Otherwise, create a new declaration. If there is a previous 7548 // declaration of the same entity, the two will be linked via 7549 // PrevDecl. 7550 TagDecl *New; 7551 7552 bool IsForwardReference = false; 7553 if (Kind == TTK_Enum) { 7554 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 7555 // enum X { A, B, C } D; D should chain to X. 7556 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 7557 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 7558 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 7559 // If this is an undefined enum, warn. 7560 if (TUK != TUK_Definition && !Invalid) { 7561 TagDecl *Def; 7562 if (getLangOptions().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) { 7563 // C++0x: 7.2p2: opaque-enum-declaration. 7564 // Conflicts are diagnosed above. Do nothing. 7565 } 7566 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 7567 Diag(Loc, diag::ext_forward_ref_enum_def) 7568 << New; 7569 Diag(Def->getLocation(), diag::note_previous_definition); 7570 } else { 7571 unsigned DiagID = diag::ext_forward_ref_enum; 7572 if (getLangOptions().Microsoft) 7573 DiagID = diag::ext_ms_forward_ref_enum; 7574 else if (getLangOptions().CPlusPlus) 7575 DiagID = diag::err_forward_ref_enum; 7576 Diag(Loc, DiagID); 7577 7578 // If this is a forward-declared reference to an enumeration, make a 7579 // note of it; we won't actually be introducing the declaration into 7580 // the declaration context. 7581 if (TUK == TUK_Reference) 7582 IsForwardReference = true; 7583 } 7584 } 7585 7586 if (EnumUnderlying) { 7587 EnumDecl *ED = cast<EnumDecl>(New); 7588 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 7589 ED->setIntegerTypeSourceInfo(TI); 7590 else 7591 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 7592 ED->setPromotionType(ED->getIntegerType()); 7593 } 7594 7595 } else { 7596 // struct/union/class 7597 7598 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 7599 // struct X { int A; } D; D should chain to X. 7600 if (getLangOptions().CPlusPlus) { 7601 // FIXME: Look for a way to use RecordDecl for simple structs. 7602 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 7603 cast_or_null<CXXRecordDecl>(PrevDecl)); 7604 7605 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 7606 StdBadAlloc = cast<CXXRecordDecl>(New); 7607 } else 7608 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 7609 cast_or_null<RecordDecl>(PrevDecl)); 7610 } 7611 7612 // Maybe add qualifier info. 7613 if (SS.isNotEmpty()) { 7614 if (SS.isSet()) { 7615 New->setQualifierInfo(SS.getWithLocInContext(Context)); 7616 if (TemplateParameterLists.size() > 0) { 7617 New->setTemplateParameterListsInfo(Context, 7618 TemplateParameterLists.size(), 7619 (TemplateParameterList**) TemplateParameterLists.release()); 7620 } 7621 } 7622 else 7623 Invalid = true; 7624 } 7625 7626 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 7627 // Add alignment attributes if necessary; these attributes are checked when 7628 // the ASTContext lays out the structure. 7629 // 7630 // It is important for implementing the correct semantics that this 7631 // happen here (in act on tag decl). The #pragma pack stack is 7632 // maintained as a result of parser callbacks which can occur at 7633 // many points during the parsing of a struct declaration (because 7634 // the #pragma tokens are effectively skipped over during the 7635 // parsing of the struct). 7636 AddAlignmentAttributesForRecord(RD); 7637 7638 AddMsStructLayoutForRecord(RD); 7639 } 7640 7641 // If this is a specialization of a member class (of a class template), 7642 // check the specialization. 7643 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 7644 Invalid = true; 7645 7646 if (Invalid) 7647 New->setInvalidDecl(); 7648 7649 if (Attr) 7650 ProcessDeclAttributeList(S, New, Attr); 7651 7652 // If we're declaring or defining a tag in function prototype scope 7653 // in C, note that this type can only be used within the function. 7654 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus) 7655 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 7656 7657 // Set the lexical context. If the tag has a C++ scope specifier, the 7658 // lexical context will be different from the semantic context. 7659 New->setLexicalDeclContext(CurContext); 7660 7661 // Mark this as a friend decl if applicable. 7662 // In Microsoft mode, a friend declaration also acts as a forward 7663 // declaration so we always pass true to setObjectOfFriendDecl to make 7664 // the tag name visible. 7665 if (TUK == TUK_Friend) 7666 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() || 7667 getLangOptions().Microsoft); 7668 7669 // Set the access specifier. 7670 if (!Invalid && SearchDC->isRecord()) 7671 SetMemberAccessSpecifier(New, PrevDecl, AS); 7672 7673 if (TUK == TUK_Definition) 7674 New->startDefinition(); 7675 7676 // If this has an identifier, add it to the scope stack. 7677 if (TUK == TUK_Friend) { 7678 // We might be replacing an existing declaration in the lookup tables; 7679 // if so, borrow its access specifier. 7680 if (PrevDecl) 7681 New->setAccess(PrevDecl->getAccess()); 7682 7683 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 7684 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false); 7685 if (Name) // can be null along some error paths 7686 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 7687 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 7688 } else if (Name) { 7689 S = getNonFieldDeclScope(S); 7690 PushOnScopeChains(New, S, !IsForwardReference); 7691 if (IsForwardReference) 7692 SearchDC->makeDeclVisibleInContext(New, /* Recoverable = */ false); 7693 7694 } else { 7695 CurContext->addDecl(New); 7696 } 7697 7698 // If this is the C FILE type, notify the AST context. 7699 if (IdentifierInfo *II = New->getIdentifier()) 7700 if (!New->isInvalidDecl() && 7701 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7702 II->isStr("FILE")) 7703 Context.setFILEDecl(New); 7704 7705 OwnedDecl = true; 7706 return New; 7707} 7708 7709void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 7710 AdjustDeclIfTemplate(TagD); 7711 TagDecl *Tag = cast<TagDecl>(TagD); 7712 7713 // Enter the tag context. 7714 PushDeclContext(S, Tag); 7715} 7716 7717void Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 7718 assert(isa<ObjCContainerDecl>(IDecl) && 7719 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 7720 DeclContext *OCD = cast<DeclContext>(IDecl); 7721 assert(getContainingDC(OCD) == CurContext && 7722 "The next DeclContext should be lexically contained in the current one."); 7723 CurContext = OCD; 7724} 7725 7726void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 7727 SourceLocation FinalLoc, 7728 SourceLocation LBraceLoc) { 7729 AdjustDeclIfTemplate(TagD); 7730 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 7731 7732 FieldCollector->StartClass(); 7733 7734 if (!Record->getIdentifier()) 7735 return; 7736 7737 if (FinalLoc.isValid()) 7738 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context)); 7739 7740 // C++ [class]p2: 7741 // [...] The class-name is also inserted into the scope of the 7742 // class itself; this is known as the injected-class-name. For 7743 // purposes of access checking, the injected-class-name is treated 7744 // as if it were a public member name. 7745 CXXRecordDecl *InjectedClassName 7746 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 7747 Record->getLocStart(), Record->getLocation(), 7748 Record->getIdentifier(), 7749 /*PrevDecl=*/0, 7750 /*DelayTypeCreation=*/true); 7751 Context.getTypeDeclType(InjectedClassName, Record); 7752 InjectedClassName->setImplicit(); 7753 InjectedClassName->setAccess(AS_public); 7754 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 7755 InjectedClassName->setDescribedClassTemplate(Template); 7756 PushOnScopeChains(InjectedClassName, S); 7757 assert(InjectedClassName->isInjectedClassName() && 7758 "Broken injected-class-name"); 7759} 7760 7761void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 7762 SourceLocation RBraceLoc) { 7763 AdjustDeclIfTemplate(TagD); 7764 TagDecl *Tag = cast<TagDecl>(TagD); 7765 Tag->setRBraceLoc(RBraceLoc); 7766 7767 if (isa<CXXRecordDecl>(Tag)) 7768 FieldCollector->FinishClass(); 7769 7770 // Exit this scope of this tag's definition. 7771 PopDeclContext(); 7772 7773 // Notify the consumer that we've defined a tag. 7774 Consumer.HandleTagDeclDefinition(Tag); 7775} 7776 7777void Sema::ActOnObjCContainerFinishDefinition(Decl *IDecl) { 7778 // Exit this scope of this interface definition. 7779 PopDeclContext(); 7780} 7781 7782void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 7783 AdjustDeclIfTemplate(TagD); 7784 TagDecl *Tag = cast<TagDecl>(TagD); 7785 Tag->setInvalidDecl(); 7786 7787 // We're undoing ActOnTagStartDefinition here, not 7788 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 7789 // the FieldCollector. 7790 7791 PopDeclContext(); 7792} 7793 7794// Note that FieldName may be null for anonymous bitfields. 7795bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 7796 QualType FieldTy, const Expr *BitWidth, 7797 bool *ZeroWidth) { 7798 // Default to true; that shouldn't confuse checks for emptiness 7799 if (ZeroWidth) 7800 *ZeroWidth = true; 7801 7802 // C99 6.7.2.1p4 - verify the field type. 7803 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 7804 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 7805 // Handle incomplete types with specific error. 7806 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 7807 return true; 7808 if (FieldName) 7809 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 7810 << FieldName << FieldTy << BitWidth->getSourceRange(); 7811 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 7812 << FieldTy << BitWidth->getSourceRange(); 7813 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 7814 UPPC_BitFieldWidth)) 7815 return true; 7816 7817 // If the bit-width is type- or value-dependent, don't try to check 7818 // it now. 7819 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 7820 return false; 7821 7822 llvm::APSInt Value; 7823 if (VerifyIntegerConstantExpression(BitWidth, &Value)) 7824 return true; 7825 7826 if (Value != 0 && ZeroWidth) 7827 *ZeroWidth = false; 7828 7829 // Zero-width bitfield is ok for anonymous field. 7830 if (Value == 0 && FieldName) 7831 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 7832 7833 if (Value.isSigned() && Value.isNegative()) { 7834 if (FieldName) 7835 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 7836 << FieldName << Value.toString(10); 7837 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 7838 << Value.toString(10); 7839 } 7840 7841 if (!FieldTy->isDependentType()) { 7842 uint64_t TypeSize = Context.getTypeSize(FieldTy); 7843 if (Value.getZExtValue() > TypeSize) { 7844 if (!getLangOptions().CPlusPlus) { 7845 if (FieldName) 7846 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 7847 << FieldName << (unsigned)Value.getZExtValue() 7848 << (unsigned)TypeSize; 7849 7850 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 7851 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 7852 } 7853 7854 if (FieldName) 7855 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 7856 << FieldName << (unsigned)Value.getZExtValue() 7857 << (unsigned)TypeSize; 7858 else 7859 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 7860 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 7861 } 7862 } 7863 7864 return false; 7865} 7866 7867/// ActOnField - Each field of a C struct/union is passed into this in order 7868/// to create a FieldDecl object for it. 7869Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 7870 Declarator &D, ExprTy *BitfieldWidth) { 7871 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 7872 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 7873 /*HasInit=*/false, AS_public); 7874 return Res; 7875} 7876 7877/// HandleField - Analyze a field of a C struct or a C++ data member. 7878/// 7879FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 7880 SourceLocation DeclStart, 7881 Declarator &D, Expr *BitWidth, bool HasInit, 7882 AccessSpecifier AS) { 7883 IdentifierInfo *II = D.getIdentifier(); 7884 SourceLocation Loc = DeclStart; 7885 if (II) Loc = D.getIdentifierLoc(); 7886 7887 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 7888 QualType T = TInfo->getType(); 7889 if (getLangOptions().CPlusPlus) { 7890 CheckExtraCXXDefaultArguments(D); 7891 7892 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 7893 UPPC_DataMemberType)) { 7894 D.setInvalidType(); 7895 T = Context.IntTy; 7896 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 7897 } 7898 } 7899 7900 DiagnoseFunctionSpecifiers(D); 7901 7902 if (D.getDeclSpec().isThreadSpecified()) 7903 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 7904 if (D.getDeclSpec().isConstexprSpecified()) 7905 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 7906 << 2; 7907 7908 // Check to see if this name was declared as a member previously 7909 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 7910 LookupName(Previous, S); 7911 assert((Previous.empty() || Previous.isOverloadedResult() || 7912 Previous.isSingleResult()) 7913 && "Lookup of member name should be either overloaded, single or null"); 7914 7915 // If the name is overloaded then get any declaration else get the single result 7916 NamedDecl *PrevDecl = Previous.isOverloadedResult() ? 7917 Previous.getRepresentativeDecl() : Previous.getAsSingle<NamedDecl>(); 7918 7919 if (PrevDecl && PrevDecl->isTemplateParameter()) { 7920 // Maybe we will complain about the shadowed template parameter. 7921 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 7922 // Just pretend that we didn't see the previous declaration. 7923 PrevDecl = 0; 7924 } 7925 7926 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 7927 PrevDecl = 0; 7928 7929 bool Mutable 7930 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 7931 SourceLocation TSSL = D.getSourceRange().getBegin(); 7932 FieldDecl *NewFD 7933 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit, 7934 TSSL, AS, PrevDecl, &D); 7935 7936 if (NewFD->isInvalidDecl()) 7937 Record->setInvalidDecl(); 7938 7939 if (NewFD->isInvalidDecl() && PrevDecl) { 7940 // Don't introduce NewFD into scope; there's already something 7941 // with the same name in the same scope. 7942 } else if (II) { 7943 PushOnScopeChains(NewFD, S); 7944 } else 7945 Record->addDecl(NewFD); 7946 7947 return NewFD; 7948} 7949 7950/// \brief Build a new FieldDecl and check its well-formedness. 7951/// 7952/// This routine builds a new FieldDecl given the fields name, type, 7953/// record, etc. \p PrevDecl should refer to any previous declaration 7954/// with the same name and in the same scope as the field to be 7955/// created. 7956/// 7957/// \returns a new FieldDecl. 7958/// 7959/// \todo The Declarator argument is a hack. It will be removed once 7960FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 7961 TypeSourceInfo *TInfo, 7962 RecordDecl *Record, SourceLocation Loc, 7963 bool Mutable, Expr *BitWidth, bool HasInit, 7964 SourceLocation TSSL, 7965 AccessSpecifier AS, NamedDecl *PrevDecl, 7966 Declarator *D) { 7967 IdentifierInfo *II = Name.getAsIdentifierInfo(); 7968 bool InvalidDecl = false; 7969 if (D) InvalidDecl = D->isInvalidType(); 7970 7971 // If we receive a broken type, recover by assuming 'int' and 7972 // marking this declaration as invalid. 7973 if (T.isNull()) { 7974 InvalidDecl = true; 7975 T = Context.IntTy; 7976 } 7977 7978 QualType EltTy = Context.getBaseElementType(T); 7979 if (!EltTy->isDependentType() && 7980 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 7981 // Fields of incomplete type force their record to be invalid. 7982 Record->setInvalidDecl(); 7983 InvalidDecl = true; 7984 } 7985 7986 // C99 6.7.2.1p8: A member of a structure or union may have any type other 7987 // than a variably modified type. 7988 if (!InvalidDecl && T->isVariablyModifiedType()) { 7989 bool SizeIsNegative; 7990 llvm::APSInt Oversized; 7991 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context, 7992 SizeIsNegative, 7993 Oversized); 7994 if (!FixedTy.isNull()) { 7995 Diag(Loc, diag::warn_illegal_constant_array_size); 7996 T = FixedTy; 7997 } else { 7998 if (SizeIsNegative) 7999 Diag(Loc, diag::err_typecheck_negative_array_size); 8000 else if (Oversized.getBoolValue()) 8001 Diag(Loc, diag::err_array_too_large) 8002 << Oversized.toString(10); 8003 else 8004 Diag(Loc, diag::err_typecheck_field_variable_size); 8005 InvalidDecl = true; 8006 } 8007 } 8008 8009 // Fields can not have abstract class types 8010 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 8011 diag::err_abstract_type_in_decl, 8012 AbstractFieldType)) 8013 InvalidDecl = true; 8014 8015 bool ZeroWidth = false; 8016 // If this is declared as a bit-field, check the bit-field. 8017 if (!InvalidDecl && BitWidth && 8018 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) { 8019 InvalidDecl = true; 8020 BitWidth = 0; 8021 ZeroWidth = false; 8022 } 8023 8024 // Check that 'mutable' is consistent with the type of the declaration. 8025 if (!InvalidDecl && Mutable) { 8026 unsigned DiagID = 0; 8027 if (T->isReferenceType()) 8028 DiagID = diag::err_mutable_reference; 8029 else if (T.isConstQualified()) 8030 DiagID = diag::err_mutable_const; 8031 8032 if (DiagID) { 8033 SourceLocation ErrLoc = Loc; 8034 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 8035 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 8036 Diag(ErrLoc, DiagID); 8037 Mutable = false; 8038 InvalidDecl = true; 8039 } 8040 } 8041 8042 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 8043 BitWidth, Mutable, HasInit); 8044 if (InvalidDecl) 8045 NewFD->setInvalidDecl(); 8046 8047 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 8048 Diag(Loc, diag::err_duplicate_member) << II; 8049 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 8050 NewFD->setInvalidDecl(); 8051 } 8052 8053 if (!InvalidDecl && getLangOptions().CPlusPlus) { 8054 if (Record->isUnion()) { 8055 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 8056 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 8057 if (RDecl->getDefinition()) { 8058 // C++ [class.union]p1: An object of a class with a non-trivial 8059 // constructor, a non-trivial copy constructor, a non-trivial 8060 // destructor, or a non-trivial copy assignment operator 8061 // cannot be a member of a union, nor can an array of such 8062 // objects. 8063 if (!getLangOptions().CPlusPlus0x && CheckNontrivialField(NewFD)) 8064 NewFD->setInvalidDecl(); 8065 } 8066 } 8067 8068 // C++ [class.union]p1: If a union contains a member of reference type, 8069 // the program is ill-formed. 8070 if (EltTy->isReferenceType()) { 8071 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type) 8072 << NewFD->getDeclName() << EltTy; 8073 NewFD->setInvalidDecl(); 8074 } 8075 } 8076 } 8077 8078 // FIXME: We need to pass in the attributes given an AST 8079 // representation, not a parser representation. 8080 if (D) 8081 // FIXME: What to pass instead of TUScope? 8082 ProcessDeclAttributes(TUScope, NewFD, *D); 8083 8084 // In auto-retain/release, infer strong retension for fields of 8085 // retainable type. 8086 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 8087 NewFD->setInvalidDecl(); 8088 8089 if (T.isObjCGCWeak()) 8090 Diag(Loc, diag::warn_attribute_weak_on_field); 8091 8092 NewFD->setAccess(AS); 8093 return NewFD; 8094} 8095 8096bool Sema::CheckNontrivialField(FieldDecl *FD) { 8097 assert(FD); 8098 assert(getLangOptions().CPlusPlus && "valid check only for C++"); 8099 8100 if (FD->isInvalidDecl()) 8101 return true; 8102 8103 QualType EltTy = Context.getBaseElementType(FD->getType()); 8104 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 8105 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 8106 if (RDecl->getDefinition()) { 8107 // We check for copy constructors before constructors 8108 // because otherwise we'll never get complaints about 8109 // copy constructors. 8110 8111 CXXSpecialMember member = CXXInvalid; 8112 if (!RDecl->hasTrivialCopyConstructor()) 8113 member = CXXCopyConstructor; 8114 else if (!RDecl->hasTrivialDefaultConstructor()) 8115 member = CXXDefaultConstructor; 8116 else if (!RDecl->hasTrivialCopyAssignment()) 8117 member = CXXCopyAssignment; 8118 else if (!RDecl->hasTrivialDestructor()) 8119 member = CXXDestructor; 8120 8121 if (member != CXXInvalid) { 8122 if (getLangOptions().ObjCAutoRefCount && RDecl->hasObjectMember()) { 8123 // Objective-C++ ARC: it is an error to have a non-trivial field of 8124 // a union. However, system headers in Objective-C programs 8125 // occasionally have Objective-C lifetime objects within unions, 8126 // and rather than cause the program to fail, we make those 8127 // members unavailable. 8128 SourceLocation Loc = FD->getLocation(); 8129 if (getSourceManager().isInSystemHeader(Loc)) { 8130 if (!FD->hasAttr<UnavailableAttr>()) 8131 FD->addAttr(new (Context) UnavailableAttr(Loc, Context, 8132 "this system field has retaining ownership")); 8133 return false; 8134 } 8135 } 8136 8137 Diag(FD->getLocation(), diag::err_illegal_union_or_anon_struct_member) 8138 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 8139 DiagnoseNontrivial(RT, member); 8140 return true; 8141 } 8142 } 8143 } 8144 8145 return false; 8146} 8147 8148/// DiagnoseNontrivial - Given that a class has a non-trivial 8149/// special member, figure out why. 8150void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) { 8151 QualType QT(T, 0U); 8152 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl()); 8153 8154 // Check whether the member was user-declared. 8155 switch (member) { 8156 case CXXInvalid: 8157 break; 8158 8159 case CXXDefaultConstructor: 8160 if (RD->hasUserDeclaredConstructor()) { 8161 typedef CXXRecordDecl::ctor_iterator ctor_iter; 8162 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){ 8163 const FunctionDecl *body = 0; 8164 ci->hasBody(body); 8165 if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) { 8166 SourceLocation CtorLoc = ci->getLocation(); 8167 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 8168 return; 8169 } 8170 } 8171 8172 assert(0 && "found no user-declared constructors"); 8173 return; 8174 } 8175 break; 8176 8177 case CXXCopyConstructor: 8178 if (RD->hasUserDeclaredCopyConstructor()) { 8179 SourceLocation CtorLoc = 8180 RD->getCopyConstructor(0)->getLocation(); 8181 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 8182 return; 8183 } 8184 break; 8185 8186 case CXXMoveConstructor: 8187 if (RD->hasUserDeclaredMoveConstructor()) { 8188 SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation(); 8189 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 8190 return; 8191 } 8192 break; 8193 8194 case CXXCopyAssignment: 8195 if (RD->hasUserDeclaredCopyAssignment()) { 8196 // FIXME: this should use the location of the copy 8197 // assignment, not the type. 8198 SourceLocation TyLoc = RD->getSourceRange().getBegin(); 8199 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member; 8200 return; 8201 } 8202 break; 8203 8204 case CXXMoveAssignment: 8205 if (RD->hasUserDeclaredMoveAssignment()) { 8206 SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation(); 8207 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member; 8208 return; 8209 } 8210 break; 8211 8212 case CXXDestructor: 8213 if (RD->hasUserDeclaredDestructor()) { 8214 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation(); 8215 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member; 8216 return; 8217 } 8218 break; 8219 } 8220 8221 typedef CXXRecordDecl::base_class_iterator base_iter; 8222 8223 // Virtual bases and members inhibit trivial copying/construction, 8224 // but not trivial destruction. 8225 if (member != CXXDestructor) { 8226 // Check for virtual bases. vbases includes indirect virtual bases, 8227 // so we just iterate through the direct bases. 8228 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) 8229 if (bi->isVirtual()) { 8230 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 8231 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1; 8232 return; 8233 } 8234 8235 // Check for virtual methods. 8236 typedef CXXRecordDecl::method_iterator meth_iter; 8237 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me; 8238 ++mi) { 8239 if (mi->isVirtual()) { 8240 SourceLocation MLoc = mi->getSourceRange().getBegin(); 8241 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0; 8242 return; 8243 } 8244 } 8245 } 8246 8247 bool (CXXRecordDecl::*hasTrivial)() const; 8248 switch (member) { 8249 case CXXDefaultConstructor: 8250 hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break; 8251 case CXXCopyConstructor: 8252 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break; 8253 case CXXCopyAssignment: 8254 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break; 8255 case CXXDestructor: 8256 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break; 8257 default: 8258 assert(0 && "unexpected special member"); return; 8259 } 8260 8261 // Check for nontrivial bases (and recurse). 8262 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) { 8263 const RecordType *BaseRT = bi->getType()->getAs<RecordType>(); 8264 assert(BaseRT && "Don't know how to handle dependent bases"); 8265 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl()); 8266 if (!(BaseRecTy->*hasTrivial)()) { 8267 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 8268 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member; 8269 DiagnoseNontrivial(BaseRT, member); 8270 return; 8271 } 8272 } 8273 8274 // Check for nontrivial members (and recurse). 8275 typedef RecordDecl::field_iterator field_iter; 8276 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe; 8277 ++fi) { 8278 QualType EltTy = Context.getBaseElementType((*fi)->getType()); 8279 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) { 8280 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl()); 8281 8282 if (!(EltRD->*hasTrivial)()) { 8283 SourceLocation FLoc = (*fi)->getLocation(); 8284 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member; 8285 DiagnoseNontrivial(EltRT, member); 8286 return; 8287 } 8288 } 8289 8290 if (EltTy->isObjCLifetimeType()) { 8291 switch (EltTy.getObjCLifetime()) { 8292 case Qualifiers::OCL_None: 8293 case Qualifiers::OCL_ExplicitNone: 8294 break; 8295 8296 case Qualifiers::OCL_Autoreleasing: 8297 case Qualifiers::OCL_Weak: 8298 case Qualifiers::OCL_Strong: 8299 Diag((*fi)->getLocation(), diag::note_nontrivial_objc_ownership) 8300 << QT << EltTy.getObjCLifetime(); 8301 return; 8302 } 8303 } 8304 } 8305 8306 assert(0 && "found no explanation for non-trivial member"); 8307} 8308 8309/// TranslateIvarVisibility - Translate visibility from a token ID to an 8310/// AST enum value. 8311static ObjCIvarDecl::AccessControl 8312TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 8313 switch (ivarVisibility) { 8314 default: assert(0 && "Unknown visitibility kind"); 8315 case tok::objc_private: return ObjCIvarDecl::Private; 8316 case tok::objc_public: return ObjCIvarDecl::Public; 8317 case tok::objc_protected: return ObjCIvarDecl::Protected; 8318 case tok::objc_package: return ObjCIvarDecl::Package; 8319 } 8320} 8321 8322/// ActOnIvar - Each ivar field of an objective-c class is passed into this 8323/// in order to create an IvarDecl object for it. 8324Decl *Sema::ActOnIvar(Scope *S, 8325 SourceLocation DeclStart, 8326 Declarator &D, ExprTy *BitfieldWidth, 8327 tok::ObjCKeywordKind Visibility) { 8328 8329 IdentifierInfo *II = D.getIdentifier(); 8330 Expr *BitWidth = (Expr*)BitfieldWidth; 8331 SourceLocation Loc = DeclStart; 8332 if (II) Loc = D.getIdentifierLoc(); 8333 8334 // FIXME: Unnamed fields can be handled in various different ways, for 8335 // example, unnamed unions inject all members into the struct namespace! 8336 8337 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 8338 QualType T = TInfo->getType(); 8339 8340 if (BitWidth) { 8341 // 6.7.2.1p3, 6.7.2.1p4 8342 if (VerifyBitField(Loc, II, T, BitWidth)) { 8343 D.setInvalidType(); 8344 BitWidth = 0; 8345 } 8346 } else { 8347 // Not a bitfield. 8348 8349 // validate II. 8350 8351 } 8352 if (T->isReferenceType()) { 8353 Diag(Loc, diag::err_ivar_reference_type); 8354 D.setInvalidType(); 8355 } 8356 // C99 6.7.2.1p8: A member of a structure or union may have any type other 8357 // than a variably modified type. 8358 else if (T->isVariablyModifiedType()) { 8359 Diag(Loc, diag::err_typecheck_ivar_variable_size); 8360 D.setInvalidType(); 8361 } 8362 8363 // Get the visibility (access control) for this ivar. 8364 ObjCIvarDecl::AccessControl ac = 8365 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 8366 : ObjCIvarDecl::None; 8367 // Must set ivar's DeclContext to its enclosing interface. 8368 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 8369 ObjCContainerDecl *EnclosingContext; 8370 if (ObjCImplementationDecl *IMPDecl = 8371 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 8372 if (!LangOpts.ObjCNonFragileABI2) { 8373 // Case of ivar declared in an implementation. Context is that of its class. 8374 EnclosingContext = IMPDecl->getClassInterface(); 8375 assert(EnclosingContext && "Implementation has no class interface!"); 8376 } 8377 else 8378 EnclosingContext = EnclosingDecl; 8379 } else { 8380 if (ObjCCategoryDecl *CDecl = 8381 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 8382 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) { 8383 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 8384 return 0; 8385 } 8386 } 8387 EnclosingContext = EnclosingDecl; 8388 } 8389 8390 // Construct the decl. 8391 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 8392 DeclStart, Loc, II, T, 8393 TInfo, ac, (Expr *)BitfieldWidth); 8394 8395 if (II) { 8396 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 8397 ForRedeclaration); 8398 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 8399 && !isa<TagDecl>(PrevDecl)) { 8400 Diag(Loc, diag::err_duplicate_member) << II; 8401 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 8402 NewID->setInvalidDecl(); 8403 } 8404 } 8405 8406 // Process attributes attached to the ivar. 8407 ProcessDeclAttributes(S, NewID, D); 8408 8409 if (D.isInvalidType()) 8410 NewID->setInvalidDecl(); 8411 8412 // In ARC, infer 'retaining' for ivars of retainable type. 8413 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 8414 NewID->setInvalidDecl(); 8415 8416 if (II) { 8417 // FIXME: When interfaces are DeclContexts, we'll need to add 8418 // these to the interface. 8419 S->AddDecl(NewID); 8420 IdResolver.AddDecl(NewID); 8421 } 8422 8423 return NewID; 8424} 8425 8426/// ActOnLastBitfield - This routine handles synthesized bitfields rules for 8427/// class and class extensions. For every class @interface and class 8428/// extension @interface, if the last ivar is a bitfield of any type, 8429/// then add an implicit `char :0` ivar to the end of that interface. 8430void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 8431 SmallVectorImpl<Decl *> &AllIvarDecls) { 8432 if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty()) 8433 return; 8434 8435 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 8436 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 8437 8438 if (!Ivar->isBitField()) 8439 return; 8440 uint64_t BitFieldSize = 8441 Ivar->getBitWidth()->EvaluateAsInt(Context).getZExtValue(); 8442 if (BitFieldSize == 0) 8443 return; 8444 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 8445 if (!ID) { 8446 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 8447 if (!CD->IsClassExtension()) 8448 return; 8449 } 8450 // No need to add this to end of @implementation. 8451 else 8452 return; 8453 } 8454 // All conditions are met. Add a new bitfield to the tail end of ivars. 8455 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 8456 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 8457 8458 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 8459 DeclLoc, DeclLoc, 0, 8460 Context.CharTy, 8461 Context.getTrivialTypeSourceInfo(Context.CharTy, 8462 DeclLoc), 8463 ObjCIvarDecl::Private, BW, 8464 true); 8465 AllIvarDecls.push_back(Ivar); 8466} 8467 8468void Sema::ActOnFields(Scope* S, 8469 SourceLocation RecLoc, Decl *EnclosingDecl, 8470 Decl **Fields, unsigned NumFields, 8471 SourceLocation LBrac, SourceLocation RBrac, 8472 AttributeList *Attr) { 8473 assert(EnclosingDecl && "missing record or interface decl"); 8474 8475 // If the decl this is being inserted into is invalid, then it may be a 8476 // redeclaration or some other bogus case. Don't try to add fields to it. 8477 if (EnclosingDecl->isInvalidDecl()) { 8478 // FIXME: Deallocate fields? 8479 return; 8480 } 8481 8482 8483 // Verify that all the fields are okay. 8484 unsigned NumNamedMembers = 0; 8485 SmallVector<FieldDecl*, 32> RecFields; 8486 8487 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 8488 bool ARCErrReported = false; 8489 for (unsigned i = 0; i != NumFields; ++i) { 8490 FieldDecl *FD = cast<FieldDecl>(Fields[i]); 8491 8492 // Get the type for the field. 8493 const Type *FDTy = FD->getType().getTypePtr(); 8494 8495 if (!FD->isAnonymousStructOrUnion()) { 8496 // Remember all fields written by the user. 8497 RecFields.push_back(FD); 8498 } 8499 8500 // If the field is already invalid for some reason, don't emit more 8501 // diagnostics about it. 8502 if (FD->isInvalidDecl()) { 8503 EnclosingDecl->setInvalidDecl(); 8504 continue; 8505 } 8506 8507 // C99 6.7.2.1p2: 8508 // A structure or union shall not contain a member with 8509 // incomplete or function type (hence, a structure shall not 8510 // contain an instance of itself, but may contain a pointer to 8511 // an instance of itself), except that the last member of a 8512 // structure with more than one named member may have incomplete 8513 // array type; such a structure (and any union containing, 8514 // possibly recursively, a member that is such a structure) 8515 // shall not be a member of a structure or an element of an 8516 // array. 8517 if (FDTy->isFunctionType()) { 8518 // Field declared as a function. 8519 Diag(FD->getLocation(), diag::err_field_declared_as_function) 8520 << FD->getDeclName(); 8521 FD->setInvalidDecl(); 8522 EnclosingDecl->setInvalidDecl(); 8523 continue; 8524 } else if (FDTy->isIncompleteArrayType() && Record && 8525 ((i == NumFields - 1 && !Record->isUnion()) || 8526 ((getLangOptions().Microsoft || getLangOptions().CPlusPlus) && 8527 (i == NumFields - 1 || Record->isUnion())))) { 8528 // Flexible array member. 8529 // Microsoft and g++ is more permissive regarding flexible array. 8530 // It will accept flexible array in union and also 8531 // as the sole element of a struct/class. 8532 if (getLangOptions().Microsoft) { 8533 if (Record->isUnion()) 8534 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms) 8535 << FD->getDeclName(); 8536 else if (NumFields == 1) 8537 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms) 8538 << FD->getDeclName() << Record->getTagKind(); 8539 } else if (getLangOptions().CPlusPlus) { 8540 if (Record->isUnion()) 8541 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 8542 << FD->getDeclName(); 8543 else if (NumFields == 1) 8544 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu) 8545 << FD->getDeclName() << Record->getTagKind(); 8546 } else if (NumNamedMembers < 1) { 8547 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 8548 << FD->getDeclName(); 8549 FD->setInvalidDecl(); 8550 EnclosingDecl->setInvalidDecl(); 8551 continue; 8552 } 8553 if (!FD->getType()->isDependentType() && 8554 !Context.getBaseElementType(FD->getType()).isPODType(Context)) { 8555 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type) 8556 << FD->getDeclName() << FD->getType(); 8557 FD->setInvalidDecl(); 8558 EnclosingDecl->setInvalidDecl(); 8559 continue; 8560 } 8561 // Okay, we have a legal flexible array member at the end of the struct. 8562 if (Record) 8563 Record->setHasFlexibleArrayMember(true); 8564 } else if (!FDTy->isDependentType() && 8565 RequireCompleteType(FD->getLocation(), FD->getType(), 8566 diag::err_field_incomplete)) { 8567 // Incomplete type 8568 FD->setInvalidDecl(); 8569 EnclosingDecl->setInvalidDecl(); 8570 continue; 8571 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 8572 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 8573 // If this is a member of a union, then entire union becomes "flexible". 8574 if (Record && Record->isUnion()) { 8575 Record->setHasFlexibleArrayMember(true); 8576 } else { 8577 // If this is a struct/class and this is not the last element, reject 8578 // it. Note that GCC supports variable sized arrays in the middle of 8579 // structures. 8580 if (i != NumFields-1) 8581 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 8582 << FD->getDeclName() << FD->getType(); 8583 else { 8584 // We support flexible arrays at the end of structs in 8585 // other structs as an extension. 8586 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 8587 << FD->getDeclName(); 8588 if (Record) 8589 Record->setHasFlexibleArrayMember(true); 8590 } 8591 } 8592 } 8593 if (Record && FDTTy->getDecl()->hasObjectMember()) 8594 Record->setHasObjectMember(true); 8595 } else if (FDTy->isObjCObjectType()) { 8596 /// A field cannot be an Objective-c object 8597 Diag(FD->getLocation(), diag::err_statically_allocated_object) 8598 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 8599 QualType T = Context.getObjCObjectPointerType(FD->getType()); 8600 FD->setType(T); 8601 } 8602 else if (!getLangOptions().CPlusPlus) { 8603 if (getLangOptions().ObjCAutoRefCount && Record && !ARCErrReported) { 8604 // It's an error in ARC if a field has lifetime. 8605 // We don't want to report this in a system header, though, 8606 // so we just make the field unavailable. 8607 // FIXME: that's really not sufficient; we need to make the type 8608 // itself invalid to, say, initialize or copy. 8609 QualType T = FD->getType(); 8610 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 8611 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 8612 SourceLocation loc = FD->getLocation(); 8613 if (getSourceManager().isInSystemHeader(loc)) { 8614 if (!FD->hasAttr<UnavailableAttr>()) { 8615 FD->addAttr(new (Context) UnavailableAttr(loc, Context, 8616 "this system field has retaining ownership")); 8617 } 8618 } else { 8619 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct); 8620 } 8621 ARCErrReported = true; 8622 } 8623 } 8624 else if (getLangOptions().ObjC1 && 8625 getLangOptions().getGCMode() != LangOptions::NonGC && 8626 Record && !Record->hasObjectMember()) { 8627 if (FD->getType()->isObjCObjectPointerType() || 8628 FD->getType().isObjCGCStrong()) 8629 Record->setHasObjectMember(true); 8630 else if (Context.getAsArrayType(FD->getType())) { 8631 QualType BaseType = Context.getBaseElementType(FD->getType()); 8632 if (BaseType->isRecordType() && 8633 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 8634 Record->setHasObjectMember(true); 8635 else if (BaseType->isObjCObjectPointerType() || 8636 BaseType.isObjCGCStrong()) 8637 Record->setHasObjectMember(true); 8638 } 8639 } 8640 } 8641 // Keep track of the number of named members. 8642 if (FD->getIdentifier()) 8643 ++NumNamedMembers; 8644 } 8645 8646 // Okay, we successfully defined 'Record'. 8647 if (Record) { 8648 bool Completed = false; 8649 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 8650 if (!CXXRecord->isInvalidDecl()) { 8651 // Set access bits correctly on the directly-declared conversions. 8652 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions(); 8653 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); 8654 I != E; ++I) 8655 Convs->setAccess(I, (*I)->getAccess()); 8656 8657 if (!CXXRecord->isDependentType()) { 8658 // Objective-C Automatic Reference Counting: 8659 // If a class has a non-static data member of Objective-C pointer 8660 // type (or array thereof), it is a non-POD type and its 8661 // default constructor (if any), copy constructor, copy assignment 8662 // operator, and destructor are non-trivial. 8663 // 8664 // This rule is also handled by CXXRecordDecl::completeDefinition(). 8665 // However, here we check whether this particular class is only 8666 // non-POD because of the presence of an Objective-C pointer member. 8667 // If so, objects of this type cannot be shared between code compiled 8668 // with instant objects and code compiled with manual retain/release. 8669 if (getLangOptions().ObjCAutoRefCount && 8670 CXXRecord->hasObjectMember() && 8671 CXXRecord->getLinkage() == ExternalLinkage) { 8672 if (CXXRecord->isPOD()) { 8673 Diag(CXXRecord->getLocation(), 8674 diag::warn_arc_non_pod_class_with_object_member) 8675 << CXXRecord; 8676 } else { 8677 // FIXME: Fix-Its would be nice here, but finding a good location 8678 // for them is going to be tricky. 8679 if (CXXRecord->hasTrivialCopyConstructor()) 8680 Diag(CXXRecord->getLocation(), 8681 diag::warn_arc_trivial_member_function_with_object_member) 8682 << CXXRecord << 0; 8683 if (CXXRecord->hasTrivialCopyAssignment()) 8684 Diag(CXXRecord->getLocation(), 8685 diag::warn_arc_trivial_member_function_with_object_member) 8686 << CXXRecord << 1; 8687 if (CXXRecord->hasTrivialDestructor()) 8688 Diag(CXXRecord->getLocation(), 8689 diag::warn_arc_trivial_member_function_with_object_member) 8690 << CXXRecord << 2; 8691 } 8692 } 8693 8694 // Adjust user-defined destructor exception spec. 8695 if (getLangOptions().CPlusPlus0x && 8696 CXXRecord->hasUserDeclaredDestructor()) 8697 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor()); 8698 8699 // Add any implicitly-declared members to this class. 8700 AddImplicitlyDeclaredMembersToClass(CXXRecord); 8701 8702 // If we have virtual base classes, we may end up finding multiple 8703 // final overriders for a given virtual function. Check for this 8704 // problem now. 8705 if (CXXRecord->getNumVBases()) { 8706 CXXFinalOverriderMap FinalOverriders; 8707 CXXRecord->getFinalOverriders(FinalOverriders); 8708 8709 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 8710 MEnd = FinalOverriders.end(); 8711 M != MEnd; ++M) { 8712 for (OverridingMethods::iterator SO = M->second.begin(), 8713 SOEnd = M->second.end(); 8714 SO != SOEnd; ++SO) { 8715 assert(SO->second.size() > 0 && 8716 "Virtual function without overridding functions?"); 8717 if (SO->second.size() == 1) 8718 continue; 8719 8720 // C++ [class.virtual]p2: 8721 // In a derived class, if a virtual member function of a base 8722 // class subobject has more than one final overrider the 8723 // program is ill-formed. 8724 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 8725 << (NamedDecl *)M->first << Record; 8726 Diag(M->first->getLocation(), 8727 diag::note_overridden_virtual_function); 8728 for (OverridingMethods::overriding_iterator 8729 OM = SO->second.begin(), 8730 OMEnd = SO->second.end(); 8731 OM != OMEnd; ++OM) 8732 Diag(OM->Method->getLocation(), diag::note_final_overrider) 8733 << (NamedDecl *)M->first << OM->Method->getParent(); 8734 8735 Record->setInvalidDecl(); 8736 } 8737 } 8738 CXXRecord->completeDefinition(&FinalOverriders); 8739 Completed = true; 8740 } 8741 } 8742 } 8743 } 8744 8745 if (!Completed) 8746 Record->completeDefinition(); 8747 8748 // Now that the record is complete, do any delayed exception spec checks 8749 // we were missing. 8750 while (!DelayedDestructorExceptionSpecChecks.empty()) { 8751 const CXXDestructorDecl *Dtor = 8752 DelayedDestructorExceptionSpecChecks.back().first; 8753 if (Dtor->getParent() != Record) 8754 break; 8755 8756 assert(!Dtor->getParent()->isDependentType() && 8757 "Should not ever add destructors of templates into the list."); 8758 CheckOverridingFunctionExceptionSpec(Dtor, 8759 DelayedDestructorExceptionSpecChecks.back().second); 8760 DelayedDestructorExceptionSpecChecks.pop_back(); 8761 } 8762 8763 } else { 8764 ObjCIvarDecl **ClsFields = 8765 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 8766 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 8767 ID->setLocEnd(RBrac); 8768 // Add ivar's to class's DeclContext. 8769 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 8770 ClsFields[i]->setLexicalDeclContext(ID); 8771 ID->addDecl(ClsFields[i]); 8772 } 8773 // Must enforce the rule that ivars in the base classes may not be 8774 // duplicates. 8775 if (ID->getSuperClass()) 8776 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 8777 } else if (ObjCImplementationDecl *IMPDecl = 8778 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 8779 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 8780 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 8781 // Ivar declared in @implementation never belongs to the implementation. 8782 // Only it is in implementation's lexical context. 8783 ClsFields[I]->setLexicalDeclContext(IMPDecl); 8784 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 8785 } else if (ObjCCategoryDecl *CDecl = 8786 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 8787 // case of ivars in class extension; all other cases have been 8788 // reported as errors elsewhere. 8789 // FIXME. Class extension does not have a LocEnd field. 8790 // CDecl->setLocEnd(RBrac); 8791 // Add ivar's to class extension's DeclContext. 8792 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 8793 ClsFields[i]->setLexicalDeclContext(CDecl); 8794 CDecl->addDecl(ClsFields[i]); 8795 } 8796 } 8797 } 8798 8799 if (Attr) 8800 ProcessDeclAttributeList(S, Record, Attr); 8801 8802 // If there's a #pragma GCC visibility in scope, and this isn't a subclass, 8803 // set the visibility of this record. 8804 if (Record && !Record->getDeclContext()->isRecord()) 8805 AddPushedVisibilityAttribute(Record); 8806} 8807 8808/// \brief Determine whether the given integral value is representable within 8809/// the given type T. 8810static bool isRepresentableIntegerValue(ASTContext &Context, 8811 llvm::APSInt &Value, 8812 QualType T) { 8813 assert(T->isIntegralType(Context) && "Integral type required!"); 8814 unsigned BitWidth = Context.getIntWidth(T); 8815 8816 if (Value.isUnsigned() || Value.isNonNegative()) { 8817 if (T->isSignedIntegerOrEnumerationType()) 8818 --BitWidth; 8819 return Value.getActiveBits() <= BitWidth; 8820 } 8821 return Value.getMinSignedBits() <= BitWidth; 8822} 8823 8824// \brief Given an integral type, return the next larger integral type 8825// (or a NULL type of no such type exists). 8826static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 8827 // FIXME: Int128/UInt128 support, which also needs to be introduced into 8828 // enum checking below. 8829 assert(T->isIntegralType(Context) && "Integral type required!"); 8830 const unsigned NumTypes = 4; 8831 QualType SignedIntegralTypes[NumTypes] = { 8832 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 8833 }; 8834 QualType UnsignedIntegralTypes[NumTypes] = { 8835 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 8836 Context.UnsignedLongLongTy 8837 }; 8838 8839 unsigned BitWidth = Context.getTypeSize(T); 8840 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 8841 : UnsignedIntegralTypes; 8842 for (unsigned I = 0; I != NumTypes; ++I) 8843 if (Context.getTypeSize(Types[I]) > BitWidth) 8844 return Types[I]; 8845 8846 return QualType(); 8847} 8848 8849EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 8850 EnumConstantDecl *LastEnumConst, 8851 SourceLocation IdLoc, 8852 IdentifierInfo *Id, 8853 Expr *Val) { 8854 unsigned IntWidth = Context.Target.getIntWidth(); 8855 llvm::APSInt EnumVal(IntWidth); 8856 QualType EltTy; 8857 8858 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 8859 Val = 0; 8860 8861 if (Val) { 8862 if (Enum->isDependentType() || Val->isTypeDependent()) 8863 EltTy = Context.DependentTy; 8864 else { 8865 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 8866 SourceLocation ExpLoc; 8867 if (!Val->isValueDependent() && 8868 VerifyIntegerConstantExpression(Val, &EnumVal)) { 8869 Val = 0; 8870 } else { 8871 if (!getLangOptions().CPlusPlus) { 8872 // C99 6.7.2.2p2: 8873 // The expression that defines the value of an enumeration constant 8874 // shall be an integer constant expression that has a value 8875 // representable as an int. 8876 8877 // Complain if the value is not representable in an int. 8878 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 8879 Diag(IdLoc, diag::ext_enum_value_not_int) 8880 << EnumVal.toString(10) << Val->getSourceRange() 8881 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 8882 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 8883 // Force the type of the expression to 'int'. 8884 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 8885 } 8886 } 8887 8888 if (Enum->isFixed()) { 8889 EltTy = Enum->getIntegerType(); 8890 8891 // C++0x [dcl.enum]p5: 8892 // ... if the initializing value of an enumerator cannot be 8893 // represented by the underlying type, the program is ill-formed. 8894 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 8895 if (getLangOptions().Microsoft) { 8896 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 8897 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 8898 } else 8899 Diag(IdLoc, diag::err_enumerator_too_large) 8900 << EltTy; 8901 } else 8902 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 8903 } 8904 else { 8905 // C++0x [dcl.enum]p5: 8906 // If the underlying type is not fixed, the type of each enumerator 8907 // is the type of its initializing value: 8908 // - If an initializer is specified for an enumerator, the 8909 // initializing value has the same type as the expression. 8910 EltTy = Val->getType(); 8911 } 8912 } 8913 } 8914 } 8915 8916 if (!Val) { 8917 if (Enum->isDependentType()) 8918 EltTy = Context.DependentTy; 8919 else if (!LastEnumConst) { 8920 // C++0x [dcl.enum]p5: 8921 // If the underlying type is not fixed, the type of each enumerator 8922 // is the type of its initializing value: 8923 // - If no initializer is specified for the first enumerator, the 8924 // initializing value has an unspecified integral type. 8925 // 8926 // GCC uses 'int' for its unspecified integral type, as does 8927 // C99 6.7.2.2p3. 8928 if (Enum->isFixed()) { 8929 EltTy = Enum->getIntegerType(); 8930 } 8931 else { 8932 EltTy = Context.IntTy; 8933 } 8934 } else { 8935 // Assign the last value + 1. 8936 EnumVal = LastEnumConst->getInitVal(); 8937 ++EnumVal; 8938 EltTy = LastEnumConst->getType(); 8939 8940 // Check for overflow on increment. 8941 if (EnumVal < LastEnumConst->getInitVal()) { 8942 // C++0x [dcl.enum]p5: 8943 // If the underlying type is not fixed, the type of each enumerator 8944 // is the type of its initializing value: 8945 // 8946 // - Otherwise the type of the initializing value is the same as 8947 // the type of the initializing value of the preceding enumerator 8948 // unless the incremented value is not representable in that type, 8949 // in which case the type is an unspecified integral type 8950 // sufficient to contain the incremented value. If no such type 8951 // exists, the program is ill-formed. 8952 QualType T = getNextLargerIntegralType(Context, EltTy); 8953 if (T.isNull() || Enum->isFixed()) { 8954 // There is no integral type larger enough to represent this 8955 // value. Complain, then allow the value to wrap around. 8956 EnumVal = LastEnumConst->getInitVal(); 8957 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 8958 ++EnumVal; 8959 if (Enum->isFixed()) 8960 // When the underlying type is fixed, this is ill-formed. 8961 Diag(IdLoc, diag::err_enumerator_wrapped) 8962 << EnumVal.toString(10) 8963 << EltTy; 8964 else 8965 Diag(IdLoc, diag::warn_enumerator_too_large) 8966 << EnumVal.toString(10); 8967 } else { 8968 EltTy = T; 8969 } 8970 8971 // Retrieve the last enumerator's value, extent that type to the 8972 // type that is supposed to be large enough to represent the incremented 8973 // value, then increment. 8974 EnumVal = LastEnumConst->getInitVal(); 8975 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 8976 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 8977 ++EnumVal; 8978 8979 // If we're not in C++, diagnose the overflow of enumerator values, 8980 // which in C99 means that the enumerator value is not representable in 8981 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 8982 // permits enumerator values that are representable in some larger 8983 // integral type. 8984 if (!getLangOptions().CPlusPlus && !T.isNull()) 8985 Diag(IdLoc, diag::warn_enum_value_overflow); 8986 } else if (!getLangOptions().CPlusPlus && 8987 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 8988 // Enforce C99 6.7.2.2p2 even when we compute the next value. 8989 Diag(IdLoc, diag::ext_enum_value_not_int) 8990 << EnumVal.toString(10) << 1; 8991 } 8992 } 8993 } 8994 8995 if (!EltTy->isDependentType()) { 8996 // Make the enumerator value match the signedness and size of the 8997 // enumerator's type. 8998 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 8999 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 9000 } 9001 9002 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 9003 Val, EnumVal); 9004} 9005 9006 9007Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 9008 SourceLocation IdLoc, IdentifierInfo *Id, 9009 AttributeList *Attr, 9010 SourceLocation EqualLoc, ExprTy *val) { 9011 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 9012 EnumConstantDecl *LastEnumConst = 9013 cast_or_null<EnumConstantDecl>(lastEnumConst); 9014 Expr *Val = static_cast<Expr*>(val); 9015 9016 // The scope passed in may not be a decl scope. Zip up the scope tree until 9017 // we find one that is. 9018 S = getNonFieldDeclScope(S); 9019 9020 // Verify that there isn't already something declared with this name in this 9021 // scope. 9022 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 9023 ForRedeclaration); 9024 if (PrevDecl && PrevDecl->isTemplateParameter()) { 9025 // Maybe we will complain about the shadowed template parameter. 9026 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 9027 // Just pretend that we didn't see the previous declaration. 9028 PrevDecl = 0; 9029 } 9030 9031 if (PrevDecl) { 9032 // When in C++, we may get a TagDecl with the same name; in this case the 9033 // enum constant will 'hide' the tag. 9034 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 9035 "Received TagDecl when not in C++!"); 9036 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 9037 if (isa<EnumConstantDecl>(PrevDecl)) 9038 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 9039 else 9040 Diag(IdLoc, diag::err_redefinition) << Id; 9041 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 9042 return 0; 9043 } 9044 } 9045 9046 // C++ [class.mem]p13: 9047 // If T is the name of a class, then each of the following shall have a 9048 // name different from T: 9049 // - every enumerator of every member of class T that is an enumerated 9050 // type 9051 if (CXXRecordDecl *Record 9052 = dyn_cast<CXXRecordDecl>( 9053 TheEnumDecl->getDeclContext()->getRedeclContext())) 9054 if (Record->getIdentifier() && Record->getIdentifier() == Id) 9055 Diag(IdLoc, diag::err_member_name_of_class) << Id; 9056 9057 EnumConstantDecl *New = 9058 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 9059 9060 if (New) { 9061 // Process attributes. 9062 if (Attr) ProcessDeclAttributeList(S, New, Attr); 9063 9064 // Register this decl in the current scope stack. 9065 New->setAccess(TheEnumDecl->getAccess()); 9066 PushOnScopeChains(New, S); 9067 } 9068 9069 return New; 9070} 9071 9072void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 9073 SourceLocation RBraceLoc, Decl *EnumDeclX, 9074 Decl **Elements, unsigned NumElements, 9075 Scope *S, AttributeList *Attr) { 9076 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 9077 QualType EnumType = Context.getTypeDeclType(Enum); 9078 9079 if (Attr) 9080 ProcessDeclAttributeList(S, Enum, Attr); 9081 9082 if (Enum->isDependentType()) { 9083 for (unsigned i = 0; i != NumElements; ++i) { 9084 EnumConstantDecl *ECD = 9085 cast_or_null<EnumConstantDecl>(Elements[i]); 9086 if (!ECD) continue; 9087 9088 ECD->setType(EnumType); 9089 } 9090 9091 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 9092 return; 9093 } 9094 9095 // TODO: If the result value doesn't fit in an int, it must be a long or long 9096 // long value. ISO C does not support this, but GCC does as an extension, 9097 // emit a warning. 9098 unsigned IntWidth = Context.Target.getIntWidth(); 9099 unsigned CharWidth = Context.Target.getCharWidth(); 9100 unsigned ShortWidth = Context.Target.getShortWidth(); 9101 9102 // Verify that all the values are okay, compute the size of the values, and 9103 // reverse the list. 9104 unsigned NumNegativeBits = 0; 9105 unsigned NumPositiveBits = 0; 9106 9107 // Keep track of whether all elements have type int. 9108 bool AllElementsInt = true; 9109 9110 for (unsigned i = 0; i != NumElements; ++i) { 9111 EnumConstantDecl *ECD = 9112 cast_or_null<EnumConstantDecl>(Elements[i]); 9113 if (!ECD) continue; // Already issued a diagnostic. 9114 9115 const llvm::APSInt &InitVal = ECD->getInitVal(); 9116 9117 // Keep track of the size of positive and negative values. 9118 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 9119 NumPositiveBits = std::max(NumPositiveBits, 9120 (unsigned)InitVal.getActiveBits()); 9121 else 9122 NumNegativeBits = std::max(NumNegativeBits, 9123 (unsigned)InitVal.getMinSignedBits()); 9124 9125 // Keep track of whether every enum element has type int (very commmon). 9126 if (AllElementsInt) 9127 AllElementsInt = ECD->getType() == Context.IntTy; 9128 } 9129 9130 // Figure out the type that should be used for this enum. 9131 QualType BestType; 9132 unsigned BestWidth; 9133 9134 // C++0x N3000 [conv.prom]p3: 9135 // An rvalue of an unscoped enumeration type whose underlying 9136 // type is not fixed can be converted to an rvalue of the first 9137 // of the following types that can represent all the values of 9138 // the enumeration: int, unsigned int, long int, unsigned long 9139 // int, long long int, or unsigned long long int. 9140 // C99 6.4.4.3p2: 9141 // An identifier declared as an enumeration constant has type int. 9142 // The C99 rule is modified by a gcc extension 9143 QualType BestPromotionType; 9144 9145 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 9146 // -fshort-enums is the equivalent to specifying the packed attribute on all 9147 // enum definitions. 9148 if (LangOpts.ShortEnums) 9149 Packed = true; 9150 9151 if (Enum->isFixed()) { 9152 BestType = BestPromotionType = Enum->getIntegerType(); 9153 // We don't need to set BestWidth, because BestType is going to be the type 9154 // of the enumerators, but we do anyway because otherwise some compilers 9155 // warn that it might be used uninitialized. 9156 BestWidth = CharWidth; 9157 } 9158 else if (NumNegativeBits) { 9159 // If there is a negative value, figure out the smallest integer type (of 9160 // int/long/longlong) that fits. 9161 // If it's packed, check also if it fits a char or a short. 9162 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 9163 BestType = Context.SignedCharTy; 9164 BestWidth = CharWidth; 9165 } else if (Packed && NumNegativeBits <= ShortWidth && 9166 NumPositiveBits < ShortWidth) { 9167 BestType = Context.ShortTy; 9168 BestWidth = ShortWidth; 9169 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 9170 BestType = Context.IntTy; 9171 BestWidth = IntWidth; 9172 } else { 9173 BestWidth = Context.Target.getLongWidth(); 9174 9175 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 9176 BestType = Context.LongTy; 9177 } else { 9178 BestWidth = Context.Target.getLongLongWidth(); 9179 9180 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 9181 Diag(Enum->getLocation(), diag::warn_enum_too_large); 9182 BestType = Context.LongLongTy; 9183 } 9184 } 9185 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 9186 } else { 9187 // If there is no negative value, figure out the smallest type that fits 9188 // all of the enumerator values. 9189 // If it's packed, check also if it fits a char or a short. 9190 if (Packed && NumPositiveBits <= CharWidth) { 9191 BestType = Context.UnsignedCharTy; 9192 BestPromotionType = Context.IntTy; 9193 BestWidth = CharWidth; 9194 } else if (Packed && NumPositiveBits <= ShortWidth) { 9195 BestType = Context.UnsignedShortTy; 9196 BestPromotionType = Context.IntTy; 9197 BestWidth = ShortWidth; 9198 } else if (NumPositiveBits <= IntWidth) { 9199 BestType = Context.UnsignedIntTy; 9200 BestWidth = IntWidth; 9201 BestPromotionType 9202 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 9203 ? Context.UnsignedIntTy : Context.IntTy; 9204 } else if (NumPositiveBits <= 9205 (BestWidth = Context.Target.getLongWidth())) { 9206 BestType = Context.UnsignedLongTy; 9207 BestPromotionType 9208 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 9209 ? Context.UnsignedLongTy : Context.LongTy; 9210 } else { 9211 BestWidth = Context.Target.getLongLongWidth(); 9212 assert(NumPositiveBits <= BestWidth && 9213 "How could an initializer get larger than ULL?"); 9214 BestType = Context.UnsignedLongLongTy; 9215 BestPromotionType 9216 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 9217 ? Context.UnsignedLongLongTy : Context.LongLongTy; 9218 } 9219 } 9220 9221 // Loop over all of the enumerator constants, changing their types to match 9222 // the type of the enum if needed. 9223 for (unsigned i = 0; i != NumElements; ++i) { 9224 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 9225 if (!ECD) continue; // Already issued a diagnostic. 9226 9227 // Standard C says the enumerators have int type, but we allow, as an 9228 // extension, the enumerators to be larger than int size. If each 9229 // enumerator value fits in an int, type it as an int, otherwise type it the 9230 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 9231 // that X has type 'int', not 'unsigned'. 9232 9233 // Determine whether the value fits into an int. 9234 llvm::APSInt InitVal = ECD->getInitVal(); 9235 9236 // If it fits into an integer type, force it. Otherwise force it to match 9237 // the enum decl type. 9238 QualType NewTy; 9239 unsigned NewWidth; 9240 bool NewSign; 9241 if (!getLangOptions().CPlusPlus && 9242 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 9243 NewTy = Context.IntTy; 9244 NewWidth = IntWidth; 9245 NewSign = true; 9246 } else if (ECD->getType() == BestType) { 9247 // Already the right type! 9248 if (getLangOptions().CPlusPlus) 9249 // C++ [dcl.enum]p4: Following the closing brace of an 9250 // enum-specifier, each enumerator has the type of its 9251 // enumeration. 9252 ECD->setType(EnumType); 9253 continue; 9254 } else { 9255 NewTy = BestType; 9256 NewWidth = BestWidth; 9257 NewSign = BestType->isSignedIntegerOrEnumerationType(); 9258 } 9259 9260 // Adjust the APSInt value. 9261 InitVal = InitVal.extOrTrunc(NewWidth); 9262 InitVal.setIsSigned(NewSign); 9263 ECD->setInitVal(InitVal); 9264 9265 // Adjust the Expr initializer and type. 9266 if (ECD->getInitExpr() && 9267 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 9268 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 9269 CK_IntegralCast, 9270 ECD->getInitExpr(), 9271 /*base paths*/ 0, 9272 VK_RValue)); 9273 if (getLangOptions().CPlusPlus) 9274 // C++ [dcl.enum]p4: Following the closing brace of an 9275 // enum-specifier, each enumerator has the type of its 9276 // enumeration. 9277 ECD->setType(EnumType); 9278 else 9279 ECD->setType(NewTy); 9280 } 9281 9282 Enum->completeDefinition(BestType, BestPromotionType, 9283 NumPositiveBits, NumNegativeBits); 9284} 9285 9286Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 9287 SourceLocation StartLoc, 9288 SourceLocation EndLoc) { 9289 StringLiteral *AsmString = cast<StringLiteral>(expr); 9290 9291 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 9292 AsmString, StartLoc, 9293 EndLoc); 9294 CurContext->addDecl(New); 9295 return New; 9296} 9297 9298DeclResult Sema::ActOnModuleImport(SourceLocation ImportLoc, 9299 IdentifierInfo &ModuleName, 9300 SourceLocation ModuleNameLoc) { 9301 ModuleKey Module = PP.getModuleLoader().loadModule(ImportLoc, 9302 ModuleName, ModuleNameLoc); 9303 if (!Module) 9304 return true; 9305 9306 // FIXME: Actually create a declaration to describe the module import. 9307 (void)Module; 9308 return DeclResult((Decl *)0); 9309} 9310 9311void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 9312 SourceLocation PragmaLoc, 9313 SourceLocation NameLoc) { 9314 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 9315 9316 if (PrevDecl) { 9317 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context)); 9318 } else { 9319 (void)WeakUndeclaredIdentifiers.insert( 9320 std::pair<IdentifierInfo*,WeakInfo> 9321 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 9322 } 9323} 9324 9325void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 9326 IdentifierInfo* AliasName, 9327 SourceLocation PragmaLoc, 9328 SourceLocation NameLoc, 9329 SourceLocation AliasNameLoc) { 9330 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 9331 LookupOrdinaryName); 9332 WeakInfo W = WeakInfo(Name, NameLoc); 9333 9334 if (PrevDecl) { 9335 if (!PrevDecl->hasAttr<AliasAttr>()) 9336 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 9337 DeclApplyPragmaWeak(TUScope, ND, W); 9338 } else { 9339 (void)WeakUndeclaredIdentifiers.insert( 9340 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 9341 } 9342} 9343 9344Decl *Sema::getObjCDeclContext() const { 9345 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 9346} 9347