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