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