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