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