SemaDecl.cpp revision 2767ce2e21d8bc17869b8436220bce719b3369e4
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 llvm::APSInt &Oversized) { 2369 // This method tries to turn a variable array into a constant 2370 // array even when the size isn't an ICE. This is necessary 2371 // for compatibility with code that depends on gcc's buggy 2372 // constant expression folding, like struct {char x[(int)(char*)2];} 2373 SizeIsNegative = false; 2374 Oversized = 0; 2375 2376 if (T->isDependentType()) 2377 return QualType(); 2378 2379 QualifierCollector Qs; 2380 const Type *Ty = Qs.strip(T); 2381 2382 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 2383 QualType Pointee = PTy->getPointeeType(); 2384 QualType FixedType = 2385 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 2386 Oversized); 2387 if (FixedType.isNull()) return FixedType; 2388 FixedType = Context.getPointerType(FixedType); 2389 return Qs.apply(FixedType); 2390 } 2391 2392 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 2393 if (!VLATy) 2394 return QualType(); 2395 // FIXME: We should probably handle this case 2396 if (VLATy->getElementType()->isVariablyModifiedType()) 2397 return QualType(); 2398 2399 Expr::EvalResult EvalResult; 2400 if (!VLATy->getSizeExpr() || 2401 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) || 2402 !EvalResult.Val.isInt()) 2403 return QualType(); 2404 2405 // Check whether the array size is negative. 2406 llvm::APSInt &Res = EvalResult.Val.getInt(); 2407 if (Res.isSigned() && Res.isNegative()) { 2408 SizeIsNegative = true; 2409 return QualType(); 2410 } 2411 2412 // Check whether the array is too large to be addressed. 2413 unsigned ActiveSizeBits 2414 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 2415 Res); 2416 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 2417 Oversized = Res; 2418 return QualType(); 2419 } 2420 2421 return Context.getConstantArrayType(VLATy->getElementType(), 2422 Res, ArrayType::Normal, 0); 2423} 2424 2425/// \brief Register the given locally-scoped external C declaration so 2426/// that it can be found later for redeclarations 2427void 2428Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, 2429 const LookupResult &Previous, 2430 Scope *S) { 2431 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 2432 "Decl is not a locally-scoped decl!"); 2433 // Note that we have a locally-scoped external with this name. 2434 LocallyScopedExternalDecls[ND->getDeclName()] = ND; 2435 2436 if (!Previous.isSingleResult()) 2437 return; 2438 2439 NamedDecl *PrevDecl = Previous.getFoundDecl(); 2440 2441 // If there was a previous declaration of this variable, it may be 2442 // in our identifier chain. Update the identifier chain with the new 2443 // declaration. 2444 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 2445 // The previous declaration was found on the identifer resolver 2446 // chain, so remove it from its scope. 2447 while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl))) 2448 S = S->getParent(); 2449 2450 if (S) 2451 S->RemoveDecl(DeclPtrTy::make(PrevDecl)); 2452 } 2453} 2454 2455/// \brief Diagnose function specifiers on a declaration of an identifier that 2456/// does not identify a function. 2457void Sema::DiagnoseFunctionSpecifiers(Declarator& D) { 2458 // FIXME: We should probably indicate the identifier in question to avoid 2459 // confusion for constructs like "inline int a(), b;" 2460 if (D.getDeclSpec().isInlineSpecified()) 2461 Diag(D.getDeclSpec().getInlineSpecLoc(), 2462 diag::err_inline_non_function); 2463 2464 if (D.getDeclSpec().isVirtualSpecified()) 2465 Diag(D.getDeclSpec().getVirtualSpecLoc(), 2466 diag::err_virtual_non_function); 2467 2468 if (D.getDeclSpec().isExplicitSpecified()) 2469 Diag(D.getDeclSpec().getExplicitSpecLoc(), 2470 diag::err_explicit_non_function); 2471} 2472 2473NamedDecl* 2474Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2475 QualType R, TypeSourceInfo *TInfo, 2476 LookupResult &Previous, bool &Redeclaration) { 2477 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 2478 if (D.getCXXScopeSpec().isSet()) { 2479 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 2480 << D.getCXXScopeSpec().getRange(); 2481 D.setInvalidType(); 2482 // Pretend we didn't see the scope specifier. 2483 DC = CurContext; 2484 Previous.clear(); 2485 } 2486 2487 if (getLangOptions().CPlusPlus) { 2488 // Check that there are no default arguments (C++ only). 2489 CheckExtraCXXDefaultArguments(D); 2490 } 2491 2492 DiagnoseFunctionSpecifiers(D); 2493 2494 if (D.getDeclSpec().isThreadSpecified()) 2495 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 2496 2497 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 2498 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 2499 << D.getName().getSourceRange(); 2500 return 0; 2501 } 2502 2503 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo); 2504 if (!NewTD) return 0; 2505 2506 // Handle attributes prior to checking for duplicates in MergeVarDecl 2507 ProcessDeclAttributes(S, NewTD, D); 2508 2509 // C99 6.7.7p2: If a typedef name specifies a variably modified type 2510 // then it shall have block scope. 2511 // Note that variably modified types must be fixed before merging the decl so 2512 // that redeclarations will match. 2513 QualType T = NewTD->getUnderlyingType(); 2514 if (T->isVariablyModifiedType()) { 2515 setFunctionHasBranchProtectedScope(); 2516 2517 if (S->getFnParent() == 0) { 2518 bool SizeIsNegative; 2519 llvm::APSInt Oversized; 2520 QualType FixedTy = 2521 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 2522 Oversized); 2523 if (!FixedTy.isNull()) { 2524 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size); 2525 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy)); 2526 } else { 2527 if (SizeIsNegative) 2528 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size); 2529 else if (T->isVariableArrayType()) 2530 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope); 2531 else if (Oversized.getBoolValue()) 2532 Diag(D.getIdentifierLoc(), diag::err_array_too_large) 2533 << Oversized.toString(10); 2534 else 2535 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope); 2536 NewTD->setInvalidDecl(); 2537 } 2538 } 2539 } 2540 2541 // Merge the decl with the existing one if appropriate. If the decl is 2542 // in an outer scope, it isn't the same thing. 2543 FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false); 2544 if (!Previous.empty()) { 2545 Redeclaration = true; 2546 MergeTypeDefDecl(NewTD, Previous); 2547 } 2548 2549 // If this is the C FILE type, notify the AST context. 2550 if (IdentifierInfo *II = NewTD->getIdentifier()) 2551 if (!NewTD->isInvalidDecl() && 2552 NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) { 2553 if (II->isStr("FILE")) 2554 Context.setFILEDecl(NewTD); 2555 else if (II->isStr("jmp_buf")) 2556 Context.setjmp_bufDecl(NewTD); 2557 else if (II->isStr("sigjmp_buf")) 2558 Context.setsigjmp_bufDecl(NewTD); 2559 } 2560 2561 return NewTD; 2562} 2563 2564/// \brief Determines whether the given declaration is an out-of-scope 2565/// previous declaration. 2566/// 2567/// This routine should be invoked when name lookup has found a 2568/// previous declaration (PrevDecl) that is not in the scope where a 2569/// new declaration by the same name is being introduced. If the new 2570/// declaration occurs in a local scope, previous declarations with 2571/// linkage may still be considered previous declarations (C99 2572/// 6.2.2p4-5, C++ [basic.link]p6). 2573/// 2574/// \param PrevDecl the previous declaration found by name 2575/// lookup 2576/// 2577/// \param DC the context in which the new declaration is being 2578/// declared. 2579/// 2580/// \returns true if PrevDecl is an out-of-scope previous declaration 2581/// for a new delcaration with the same name. 2582static bool 2583isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 2584 ASTContext &Context) { 2585 if (!PrevDecl) 2586 return 0; 2587 2588 if (!PrevDecl->hasLinkage()) 2589 return false; 2590 2591 if (Context.getLangOptions().CPlusPlus) { 2592 // C++ [basic.link]p6: 2593 // If there is a visible declaration of an entity with linkage 2594 // having the same name and type, ignoring entities declared 2595 // outside the innermost enclosing namespace scope, the block 2596 // scope declaration declares that same entity and receives the 2597 // linkage of the previous declaration. 2598 DeclContext *OuterContext = DC->getLookupContext(); 2599 if (!OuterContext->isFunctionOrMethod()) 2600 // This rule only applies to block-scope declarations. 2601 return false; 2602 else { 2603 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 2604 if (PrevOuterContext->isRecord()) 2605 // We found a member function: ignore it. 2606 return false; 2607 else { 2608 // Find the innermost enclosing namespace for the new and 2609 // previous declarations. 2610 while (!OuterContext->isFileContext()) 2611 OuterContext = OuterContext->getParent(); 2612 while (!PrevOuterContext->isFileContext()) 2613 PrevOuterContext = PrevOuterContext->getParent(); 2614 2615 // The previous declaration is in a different namespace, so it 2616 // isn't the same function. 2617 if (OuterContext->getPrimaryContext() != 2618 PrevOuterContext->getPrimaryContext()) 2619 return false; 2620 } 2621 } 2622 } 2623 2624 return true; 2625} 2626 2627static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 2628 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2629 if (!SS.isSet()) return; 2630 DD->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()), 2631 SS.getRange()); 2632} 2633 2634NamedDecl* 2635Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2636 QualType R, TypeSourceInfo *TInfo, 2637 LookupResult &Previous, 2638 MultiTemplateParamsArg TemplateParamLists, 2639 bool &Redeclaration) { 2640 DeclarationName Name = GetNameForDeclarator(D).getName(); 2641 2642 // Check that there are no default arguments (C++ only). 2643 if (getLangOptions().CPlusPlus) 2644 CheckExtraCXXDefaultArguments(D); 2645 2646 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 2647 assert(SCSpec != DeclSpec::SCS_typedef && 2648 "Parser allowed 'typedef' as storage class VarDecl."); 2649 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 2650 if (SCSpec == DeclSpec::SCS_mutable) { 2651 // mutable can only appear on non-static class members, so it's always 2652 // an error here 2653 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 2654 D.setInvalidType(); 2655 SC = VarDecl::None; 2656 } 2657 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 2658 VarDecl::StorageClass SCAsWritten 2659 = StorageClassSpecToVarDeclStorageClass(SCSpec); 2660 2661 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2662 if (!II) { 2663 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 2664 << Name.getAsString(); 2665 return 0; 2666 } 2667 2668 DiagnoseFunctionSpecifiers(D); 2669 2670 if (!DC->isRecord() && S->getFnParent() == 0) { 2671 // C99 6.9p2: The storage-class specifiers auto and register shall not 2672 // appear in the declaration specifiers in an external declaration. 2673 if (SC == VarDecl::Auto || SC == VarDecl::Register) { 2674 2675 // If this is a register variable with an asm label specified, then this 2676 // is a GNU extension. 2677 if (SC == VarDecl::Register && D.getAsmLabel()) 2678 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 2679 else 2680 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 2681 D.setInvalidType(); 2682 } 2683 } 2684 if (DC->isRecord() && !CurContext->isRecord()) { 2685 // This is an out-of-line definition of a static data member. 2686 if (SC == VarDecl::Static) { 2687 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 2688 diag::err_static_out_of_line) 2689 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 2690 } else if (SC == VarDecl::None) 2691 SC = VarDecl::Static; 2692 } 2693 if (SC == VarDecl::Static) { 2694 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 2695 if (RD->isLocalClass()) 2696 Diag(D.getIdentifierLoc(), 2697 diag::err_static_data_member_not_allowed_in_local_class) 2698 << Name << RD->getDeclName(); 2699 } 2700 } 2701 2702 // Match up the template parameter lists with the scope specifier, then 2703 // determine whether we have a template or a template specialization. 2704 bool isExplicitSpecialization = false; 2705 unsigned NumMatchedTemplateParamLists = TemplateParamLists.size(); 2706 bool Invalid = false; 2707 if (TemplateParameterList *TemplateParams 2708 = MatchTemplateParametersToScopeSpecifier( 2709 D.getDeclSpec().getSourceRange().getBegin(), 2710 D.getCXXScopeSpec(), 2711 (TemplateParameterList**)TemplateParamLists.get(), 2712 TemplateParamLists.size(), 2713 /*never a friend*/ false, 2714 isExplicitSpecialization, 2715 Invalid)) { 2716 // All but one template parameter lists have been matching. 2717 --NumMatchedTemplateParamLists; 2718 2719 if (TemplateParams->size() > 0) { 2720 // There is no such thing as a variable template. 2721 Diag(D.getIdentifierLoc(), diag::err_template_variable) 2722 << II 2723 << SourceRange(TemplateParams->getTemplateLoc(), 2724 TemplateParams->getRAngleLoc()); 2725 return 0; 2726 } else { 2727 // There is an extraneous 'template<>' for this variable. Complain 2728 // about it, but allow the declaration of the variable. 2729 Diag(TemplateParams->getTemplateLoc(), 2730 diag::err_template_variable_noparams) 2731 << II 2732 << SourceRange(TemplateParams->getTemplateLoc(), 2733 TemplateParams->getRAngleLoc()); 2734 2735 isExplicitSpecialization = true; 2736 } 2737 } 2738 2739 VarDecl *NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(), 2740 II, R, TInfo, SC, SCAsWritten); 2741 2742 if (D.isInvalidType() || Invalid) 2743 NewVD->setInvalidDecl(); 2744 2745 SetNestedNameSpecifier(NewVD, D); 2746 2747 if (NumMatchedTemplateParamLists > 0 && D.getCXXScopeSpec().isSet()) { 2748 NewVD->setTemplateParameterListsInfo(Context, 2749 NumMatchedTemplateParamLists, 2750 (TemplateParameterList**)TemplateParamLists.release()); 2751 } 2752 2753 if (D.getDeclSpec().isThreadSpecified()) { 2754 if (NewVD->hasLocalStorage()) 2755 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global); 2756 else if (!Context.Target.isTLSSupported()) 2757 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported); 2758 else 2759 NewVD->setThreadSpecified(true); 2760 } 2761 2762 // Set the lexical context. If the declarator has a C++ scope specifier, the 2763 // lexical context will be different from the semantic context. 2764 NewVD->setLexicalDeclContext(CurContext); 2765 2766 // Handle attributes prior to checking for duplicates in MergeVarDecl 2767 ProcessDeclAttributes(S, NewVD, D); 2768 2769 // Handle GNU asm-label extension (encoded as an attribute). 2770 if (Expr *E = (Expr*) D.getAsmLabel()) { 2771 // The parser guarantees this is a string. 2772 StringLiteral *SE = cast<StringLiteral>(E); 2773 NewVD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString())); 2774 } 2775 2776 // Diagnose shadowed variables before filtering for scope. 2777 if (!D.getCXXScopeSpec().isSet()) 2778 CheckShadow(S, NewVD, Previous); 2779 2780 // Don't consider existing declarations that are in a different 2781 // scope and are out-of-semantic-context declarations (if the new 2782 // declaration has linkage). 2783 FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage()); 2784 2785 // Merge the decl with the existing one if appropriate. 2786 if (!Previous.empty()) { 2787 if (Previous.isSingleResult() && 2788 isa<FieldDecl>(Previous.getFoundDecl()) && 2789 D.getCXXScopeSpec().isSet()) { 2790 // The user tried to define a non-static data member 2791 // out-of-line (C++ [dcl.meaning]p1). 2792 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 2793 << D.getCXXScopeSpec().getRange(); 2794 Previous.clear(); 2795 NewVD->setInvalidDecl(); 2796 } 2797 } else if (D.getCXXScopeSpec().isSet()) { 2798 // No previous declaration in the qualifying scope. 2799 Diag(D.getIdentifierLoc(), diag::err_no_member) 2800 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 2801 << D.getCXXScopeSpec().getRange(); 2802 NewVD->setInvalidDecl(); 2803 } 2804 2805 CheckVariableDeclaration(NewVD, Previous, Redeclaration); 2806 2807 // This is an explicit specialization of a static data member. Check it. 2808 if (isExplicitSpecialization && !NewVD->isInvalidDecl() && 2809 CheckMemberSpecialization(NewVD, Previous)) 2810 NewVD->setInvalidDecl(); 2811 2812 // attributes declared post-definition are currently ignored 2813 if (Previous.isSingleResult()) { 2814 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl()); 2815 if (Def && (Def = Def->getDefinition()) && 2816 Def != NewVD && D.hasAttributes()) { 2817 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition); 2818 Diag(Def->getLocation(), diag::note_previous_definition); 2819 } 2820 } 2821 2822 // If this is a locally-scoped extern C variable, update the map of 2823 // such variables. 2824 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() && 2825 !NewVD->isInvalidDecl()) 2826 RegisterLocallyScopedExternCDecl(NewVD, Previous, S); 2827 2828 // If there's a #pragma GCC visibility in scope, and this isn't a class 2829 // member, set the visibility of this variable. 2830 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord()) 2831 AddPushedVisibilityAttribute(NewVD); 2832 2833 MarkUnusedFileScopedDecl(NewVD); 2834 2835 return NewVD; 2836} 2837 2838/// \brief Diagnose variable or built-in function shadowing. Implements 2839/// -Wshadow. 2840/// 2841/// This method is called whenever a VarDecl is added to a "useful" 2842/// scope. 2843/// 2844/// \param S the scope in which the shadowing name is being declared 2845/// \param R the lookup of the name 2846/// 2847void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 2848 // Return if warning is ignored. 2849 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow) == Diagnostic::Ignored) 2850 return; 2851 2852 // Don't diagnose declarations at file scope. The scope might not 2853 // have a DeclContext if (e.g.) we're parsing a function prototype. 2854 DeclContext *NewDC = static_cast<DeclContext*>(S->getEntity()); 2855 if (NewDC && NewDC->isFileContext()) 2856 return; 2857 2858 // Only diagnose if we're shadowing an unambiguous field or variable. 2859 if (R.getResultKind() != LookupResult::Found) 2860 return; 2861 2862 NamedDecl* ShadowedDecl = R.getFoundDecl(); 2863 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 2864 return; 2865 2866 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 2867 2868 // Only warn about certain kinds of shadowing for class members. 2869 if (NewDC && NewDC->isRecord()) { 2870 // In particular, don't warn about shadowing non-class members. 2871 if (!OldDC->isRecord()) 2872 return; 2873 2874 // TODO: should we warn about static data members shadowing 2875 // static data members from base classes? 2876 2877 // TODO: don't diagnose for inaccessible shadowed members. 2878 // This is hard to do perfectly because we might friend the 2879 // shadowing context, but that's just a false negative. 2880 } 2881 2882 // Determine what kind of declaration we're shadowing. 2883 unsigned Kind; 2884 if (isa<RecordDecl>(OldDC)) { 2885 if (isa<FieldDecl>(ShadowedDecl)) 2886 Kind = 3; // field 2887 else 2888 Kind = 2; // static data member 2889 } else if (OldDC->isFileContext()) 2890 Kind = 1; // global 2891 else 2892 Kind = 0; // local 2893 2894 DeclarationName Name = R.getLookupName(); 2895 2896 // Emit warning and note. 2897 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 2898 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 2899} 2900 2901/// \brief Check -Wshadow without the advantage of a previous lookup. 2902void Sema::CheckShadow(Scope *S, VarDecl *D) { 2903 LookupResult R(*this, D->getDeclName(), D->getLocation(), 2904 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 2905 LookupName(R, S); 2906 CheckShadow(S, D, R); 2907} 2908 2909/// \brief Perform semantic checking on a newly-created variable 2910/// declaration. 2911/// 2912/// This routine performs all of the type-checking required for a 2913/// variable declaration once it has been built. It is used both to 2914/// check variables after they have been parsed and their declarators 2915/// have been translated into a declaration, and to check variables 2916/// that have been instantiated from a template. 2917/// 2918/// Sets NewVD->isInvalidDecl() if an error was encountered. 2919void Sema::CheckVariableDeclaration(VarDecl *NewVD, 2920 LookupResult &Previous, 2921 bool &Redeclaration) { 2922 // If the decl is already known invalid, don't check it. 2923 if (NewVD->isInvalidDecl()) 2924 return; 2925 2926 QualType T = NewVD->getType(); 2927 2928 if (T->isObjCObjectType()) { 2929 Diag(NewVD->getLocation(), diag::err_statically_allocated_object); 2930 return NewVD->setInvalidDecl(); 2931 } 2932 2933 // Emit an error if an address space was applied to decl with local storage. 2934 // This includes arrays of objects with address space qualifiers, but not 2935 // automatic variables that point to other address spaces. 2936 // ISO/IEC TR 18037 S5.1.2 2937 if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) { 2938 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 2939 return NewVD->setInvalidDecl(); 2940 } 2941 2942 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 2943 && !NewVD->hasAttr<BlocksAttr>()) 2944 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 2945 2946 bool isVM = T->isVariablyModifiedType(); 2947 if (isVM || NewVD->hasAttr<CleanupAttr>() || 2948 NewVD->hasAttr<BlocksAttr>()) 2949 setFunctionHasBranchProtectedScope(); 2950 2951 if ((isVM && NewVD->hasLinkage()) || 2952 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 2953 bool SizeIsNegative; 2954 llvm::APSInt Oversized; 2955 QualType FixedTy = 2956 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 2957 Oversized); 2958 2959 if (FixedTy.isNull() && T->isVariableArrayType()) { 2960 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 2961 // FIXME: This won't give the correct result for 2962 // int a[10][n]; 2963 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 2964 2965 if (NewVD->isFileVarDecl()) 2966 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 2967 << SizeRange; 2968 else if (NewVD->getStorageClass() == VarDecl::Static) 2969 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 2970 << SizeRange; 2971 else 2972 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 2973 << SizeRange; 2974 return NewVD->setInvalidDecl(); 2975 } 2976 2977 if (FixedTy.isNull()) { 2978 if (NewVD->isFileVarDecl()) 2979 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 2980 else 2981 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 2982 return NewVD->setInvalidDecl(); 2983 } 2984 2985 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 2986 NewVD->setType(FixedTy); 2987 } 2988 2989 if (Previous.empty() && NewVD->isExternC()) { 2990 // Since we did not find anything by this name and we're declaring 2991 // an extern "C" variable, look for a non-visible extern "C" 2992 // declaration with the same name. 2993 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 2994 = LocallyScopedExternalDecls.find(NewVD->getDeclName()); 2995 if (Pos != LocallyScopedExternalDecls.end()) 2996 Previous.addDecl(Pos->second); 2997 } 2998 2999 if (T->isVoidType() && !NewVD->hasExternalStorage()) { 3000 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 3001 << T; 3002 return NewVD->setInvalidDecl(); 3003 } 3004 3005 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 3006 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 3007 return NewVD->setInvalidDecl(); 3008 } 3009 3010 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 3011 Diag(NewVD->getLocation(), diag::err_block_on_vm); 3012 return NewVD->setInvalidDecl(); 3013 } 3014 3015 // Function pointers and references cannot have qualified function type, only 3016 // function pointer-to-members can do that. 3017 QualType Pointee; 3018 unsigned PtrOrRef = 0; 3019 if (const PointerType *Ptr = T->getAs<PointerType>()) 3020 Pointee = Ptr->getPointeeType(); 3021 else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) { 3022 Pointee = Ref->getPointeeType(); 3023 PtrOrRef = 1; 3024 } 3025 if (!Pointee.isNull() && Pointee->isFunctionProtoType() && 3026 Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) { 3027 Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer) 3028 << PtrOrRef; 3029 return NewVD->setInvalidDecl(); 3030 } 3031 3032 if (!Previous.empty()) { 3033 Redeclaration = true; 3034 MergeVarDecl(NewVD, Previous); 3035 } 3036} 3037 3038/// \brief Data used with FindOverriddenMethod 3039struct FindOverriddenMethodData { 3040 Sema *S; 3041 CXXMethodDecl *Method; 3042}; 3043 3044/// \brief Member lookup function that determines whether a given C++ 3045/// method overrides a method in a base class, to be used with 3046/// CXXRecordDecl::lookupInBases(). 3047static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 3048 CXXBasePath &Path, 3049 void *UserData) { 3050 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 3051 3052 FindOverriddenMethodData *Data 3053 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 3054 3055 DeclarationName Name = Data->Method->getDeclName(); 3056 3057 // FIXME: Do we care about other names here too? 3058 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 3059 // We really want to find the base class destructor here. 3060 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 3061 CanQualType CT = Data->S->Context.getCanonicalType(T); 3062 3063 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 3064 } 3065 3066 for (Path.Decls = BaseRecord->lookup(Name); 3067 Path.Decls.first != Path.Decls.second; 3068 ++Path.Decls.first) { 3069 NamedDecl *D = *Path.Decls.first; 3070 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 3071 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 3072 return true; 3073 } 3074 } 3075 3076 return false; 3077} 3078 3079/// AddOverriddenMethods - See if a method overrides any in the base classes, 3080/// and if so, check that it's a valid override and remember it. 3081void Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 3082 // Look for virtual methods in base classes that this method might override. 3083 CXXBasePaths Paths; 3084 FindOverriddenMethodData Data; 3085 Data.Method = MD; 3086 Data.S = this; 3087 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 3088 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 3089 E = Paths.found_decls_end(); I != E; ++I) { 3090 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 3091 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 3092 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 3093 !CheckOverridingFunctionAttributes(MD, OldMD)) 3094 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 3095 } 3096 } 3097 } 3098} 3099 3100NamedDecl* 3101Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 3102 QualType R, TypeSourceInfo *TInfo, 3103 LookupResult &Previous, 3104 MultiTemplateParamsArg TemplateParamLists, 3105 bool IsFunctionDefinition, bool &Redeclaration) { 3106 assert(R.getTypePtr()->isFunctionType()); 3107 3108 // TODO: consider using NameInfo for diagnostic. 3109 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3110 DeclarationName Name = NameInfo.getName(); 3111 FunctionDecl::StorageClass SC = FunctionDecl::None; 3112 switch (D.getDeclSpec().getStorageClassSpec()) { 3113 default: assert(0 && "Unknown storage class!"); 3114 case DeclSpec::SCS_auto: 3115 case DeclSpec::SCS_register: 3116 case DeclSpec::SCS_mutable: 3117 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 3118 diag::err_typecheck_sclass_func); 3119 D.setInvalidType(); 3120 break; 3121 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break; 3122 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break; 3123 case DeclSpec::SCS_static: { 3124 if (CurContext->getLookupContext()->isFunctionOrMethod()) { 3125 // C99 6.7.1p5: 3126 // The declaration of an identifier for a function that has 3127 // block scope shall have no explicit storage-class specifier 3128 // other than extern 3129 // See also (C++ [dcl.stc]p4). 3130 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 3131 diag::err_static_block_func); 3132 SC = FunctionDecl::None; 3133 } else 3134 SC = FunctionDecl::Static; 3135 break; 3136 } 3137 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break; 3138 } 3139 3140 if (D.getDeclSpec().isThreadSpecified()) 3141 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 3142 3143 bool isFriend = D.getDeclSpec().isFriendSpecified(); 3144 bool isInline = D.getDeclSpec().isInlineSpecified(); 3145 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 3146 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 3147 3148 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 3149 FunctionDecl::StorageClass SCAsWritten 3150 = StorageClassSpecToFunctionDeclStorageClass(SCSpec); 3151 3152 // Check that the return type is not an abstract class type. 3153 // For record types, this is done by the AbstractClassUsageDiagnoser once 3154 // the class has been completely parsed. 3155 if (!DC->isRecord() && 3156 RequireNonAbstractType(D.getIdentifierLoc(), 3157 R->getAs<FunctionType>()->getResultType(), 3158 diag::err_abstract_type_in_decl, 3159 AbstractReturnType)) 3160 D.setInvalidType(); 3161 3162 // Do not allow returning a objc interface by-value. 3163 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) { 3164 Diag(D.getIdentifierLoc(), 3165 diag::err_object_cannot_be_passed_returned_by_value) << 0 3166 << R->getAs<FunctionType>()->getResultType(); 3167 D.setInvalidType(); 3168 } 3169 3170 bool isVirtualOkay = false; 3171 FunctionDecl *NewFD; 3172 3173 if (isFriend) { 3174 // C++ [class.friend]p5 3175 // A function can be defined in a friend declaration of a 3176 // class . . . . Such a function is implicitly inline. 3177 isInline |= IsFunctionDefinition; 3178 } 3179 3180 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 3181 // This is a C++ constructor declaration. 3182 assert(DC->isRecord() && 3183 "Constructors can only be declared in a member context"); 3184 3185 R = CheckConstructorDeclarator(D, R, SC); 3186 3187 // Create the new declaration 3188 NewFD = CXXConstructorDecl::Create(Context, 3189 cast<CXXRecordDecl>(DC), 3190 NameInfo, R, TInfo, 3191 isExplicit, isInline, 3192 /*isImplicitlyDeclared=*/false); 3193 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 3194 // This is a C++ destructor declaration. 3195 if (DC->isRecord()) { 3196 R = CheckDestructorDeclarator(D, R, SC); 3197 3198 NewFD = CXXDestructorDecl::Create(Context, 3199 cast<CXXRecordDecl>(DC), 3200 NameInfo, R, 3201 isInline, 3202 /*isImplicitlyDeclared=*/false); 3203 NewFD->setTypeSourceInfo(TInfo); 3204 3205 isVirtualOkay = true; 3206 } else { 3207 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 3208 3209 // Create a FunctionDecl to satisfy the function definition parsing 3210 // code path. 3211 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(), 3212 Name, R, TInfo, SC, SCAsWritten, isInline, 3213 /*hasPrototype=*/true); 3214 D.setInvalidType(); 3215 } 3216 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 3217 if (!DC->isRecord()) { 3218 Diag(D.getIdentifierLoc(), 3219 diag::err_conv_function_not_member); 3220 return 0; 3221 } 3222 3223 CheckConversionDeclarator(D, R, SC); 3224 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC), 3225 NameInfo, R, TInfo, 3226 isInline, isExplicit); 3227 3228 isVirtualOkay = true; 3229 } else if (DC->isRecord()) { 3230 // If the of the function is the same as the name of the record, then this 3231 // must be an invalid constructor that has a return type. 3232 // (The parser checks for a return type and makes the declarator a 3233 // constructor if it has no return type). 3234 // must have an invalid constructor that has a return type 3235 if (Name.getAsIdentifierInfo() && 3236 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 3237 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 3238 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 3239 << SourceRange(D.getIdentifierLoc()); 3240 return 0; 3241 } 3242 3243 bool isStatic = SC == FunctionDecl::Static; 3244 3245 // [class.free]p1: 3246 // Any allocation function for a class T is a static member 3247 // (even if not explicitly declared static). 3248 if (Name.getCXXOverloadedOperator() == OO_New || 3249 Name.getCXXOverloadedOperator() == OO_Array_New) 3250 isStatic = true; 3251 3252 // [class.free]p6 Any deallocation function for a class X is a static member 3253 // (even if not explicitly declared static). 3254 if (Name.getCXXOverloadedOperator() == OO_Delete || 3255 Name.getCXXOverloadedOperator() == OO_Array_Delete) 3256 isStatic = true; 3257 3258 // This is a C++ method declaration. 3259 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC), 3260 NameInfo, R, TInfo, 3261 isStatic, SCAsWritten, isInline); 3262 3263 isVirtualOkay = !isStatic; 3264 } else { 3265 // Determine whether the function was written with a 3266 // prototype. This true when: 3267 // - we're in C++ (where every function has a prototype), 3268 // - there is a prototype in the declarator, or 3269 // - the type R of the function is some kind of typedef or other reference 3270 // to a type name (which eventually refers to a function type). 3271 bool HasPrototype = 3272 getLangOptions().CPlusPlus || 3273 (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) || 3274 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 3275 3276 NewFD = FunctionDecl::Create(Context, DC, 3277 NameInfo, R, TInfo, SC, SCAsWritten, isInline, 3278 HasPrototype); 3279 } 3280 3281 if (D.isInvalidType()) 3282 NewFD->setInvalidDecl(); 3283 3284 SetNestedNameSpecifier(NewFD, D); 3285 3286 // Set the lexical context. If the declarator has a C++ 3287 // scope specifier, or is the object of a friend declaration, the 3288 // lexical context will be different from the semantic context. 3289 NewFD->setLexicalDeclContext(CurContext); 3290 3291 // Match up the template parameter lists with the scope specifier, then 3292 // determine whether we have a template or a template specialization. 3293 FunctionTemplateDecl *FunctionTemplate = 0; 3294 bool isExplicitSpecialization = false; 3295 bool isFunctionTemplateSpecialization = false; 3296 unsigned NumMatchedTemplateParamLists = TemplateParamLists.size(); 3297 bool Invalid = false; 3298 if (TemplateParameterList *TemplateParams 3299 = MatchTemplateParametersToScopeSpecifier( 3300 D.getDeclSpec().getSourceRange().getBegin(), 3301 D.getCXXScopeSpec(), 3302 (TemplateParameterList**)TemplateParamLists.get(), 3303 TemplateParamLists.size(), 3304 isFriend, 3305 isExplicitSpecialization, 3306 Invalid)) { 3307 // All but one template parameter lists have been matching. 3308 --NumMatchedTemplateParamLists; 3309 3310 if (TemplateParams->size() > 0) { 3311 // This is a function template 3312 3313 // Check that we can declare a template here. 3314 if (CheckTemplateDeclScope(S, TemplateParams)) 3315 return 0; 3316 3317 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 3318 NewFD->getLocation(), 3319 Name, TemplateParams, 3320 NewFD); 3321 FunctionTemplate->setLexicalDeclContext(CurContext); 3322 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 3323 } else { 3324 // This is a function template specialization. 3325 isFunctionTemplateSpecialization = true; 3326 3327 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 3328 if (isFriend && isFunctionTemplateSpecialization) { 3329 // We want to remove the "template<>", found here. 3330 SourceRange RemoveRange = TemplateParams->getSourceRange(); 3331 3332 // If we remove the template<> and the name is not a 3333 // template-id, we're actually silently creating a problem: 3334 // the friend declaration will refer to an untemplated decl, 3335 // and clearly the user wants a template specialization. So 3336 // we need to insert '<>' after the name. 3337 SourceLocation InsertLoc; 3338 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 3339 InsertLoc = D.getName().getSourceRange().getEnd(); 3340 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 3341 } 3342 3343 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 3344 << Name << RemoveRange 3345 << FixItHint::CreateRemoval(RemoveRange) 3346 << FixItHint::CreateInsertion(InsertLoc, "<>"); 3347 } 3348 } 3349 } 3350 3351 if (NumMatchedTemplateParamLists > 0 && D.getCXXScopeSpec().isSet()) { 3352 NewFD->setTemplateParameterListsInfo(Context, 3353 NumMatchedTemplateParamLists, 3354 (TemplateParameterList**)TemplateParamLists.release()); 3355 } 3356 3357 if (Invalid) { 3358 NewFD->setInvalidDecl(); 3359 if (FunctionTemplate) 3360 FunctionTemplate->setInvalidDecl(); 3361 } 3362 3363 // C++ [dcl.fct.spec]p5: 3364 // The virtual specifier shall only be used in declarations of 3365 // nonstatic class member functions that appear within a 3366 // member-specification of a class declaration; see 10.3. 3367 // 3368 if (isVirtual && !NewFD->isInvalidDecl()) { 3369 if (!isVirtualOkay) { 3370 Diag(D.getDeclSpec().getVirtualSpecLoc(), 3371 diag::err_virtual_non_function); 3372 } else if (!CurContext->isRecord()) { 3373 // 'virtual' was specified outside of the class. 3374 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class) 3375 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 3376 } else { 3377 // Okay: Add virtual to the method. 3378 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC); 3379 CurClass->setMethodAsVirtual(NewFD); 3380 } 3381 } 3382 3383 // C++ [dcl.fct.spec]p3: 3384 // The inline specifier shall not appear on a block scope function declaration. 3385 if (isInline && !NewFD->isInvalidDecl() && getLangOptions().CPlusPlus) { 3386 if (CurContext->isFunctionOrMethod()) { 3387 // 'inline' is not allowed on block scope function declaration. 3388 Diag(D.getDeclSpec().getInlineSpecLoc(), 3389 diag::err_inline_declaration_block_scope) << Name 3390 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 3391 } 3392 } 3393 3394 // C++ [dcl.fct.spec]p6: 3395 // The explicit specifier shall be used only in the declaration of a 3396 // constructor or conversion function within its class definition; see 12.3.1 3397 // and 12.3.2. 3398 if (isExplicit && !NewFD->isInvalidDecl()) { 3399 if (!CurContext->isRecord()) { 3400 // 'explicit' was specified outside of the class. 3401 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3402 diag::err_explicit_out_of_class) 3403 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 3404 } else if (!isa<CXXConstructorDecl>(NewFD) && 3405 !isa<CXXConversionDecl>(NewFD)) { 3406 // 'explicit' was specified on a function that wasn't a constructor 3407 // or conversion function. 3408 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3409 diag::err_explicit_non_ctor_or_conv_function) 3410 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 3411 } 3412 } 3413 3414 // Filter out previous declarations that don't match the scope. 3415 FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage()); 3416 3417 if (isFriend) { 3418 // DC is the namespace in which the function is being declared. 3419 assert((DC->isFileContext() || !Previous.empty()) && 3420 "previously-undeclared friend function being created " 3421 "in a non-namespace context"); 3422 3423 // For now, claim that the objects have no previous declaration. 3424 if (FunctionTemplate) { 3425 FunctionTemplate->setObjectOfFriendDecl(false); 3426 FunctionTemplate->setAccess(AS_public); 3427 } 3428 NewFD->setObjectOfFriendDecl(false); 3429 NewFD->setAccess(AS_public); 3430 } 3431 3432 if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) && 3433 !CurContext->isRecord()) { 3434 // C++ [class.static]p1: 3435 // A data or function member of a class may be declared static 3436 // in a class definition, in which case it is a static member of 3437 // the class. 3438 3439 // Complain about the 'static' specifier if it's on an out-of-line 3440 // member function definition. 3441 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 3442 diag::err_static_out_of_line) 3443 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 3444 } 3445 3446 // Handle GNU asm-label extension (encoded as an attribute). 3447 if (Expr *E = (Expr*) D.getAsmLabel()) { 3448 // The parser guarantees this is a string. 3449 StringLiteral *SE = cast<StringLiteral>(E); 3450 NewFD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString())); 3451 } 3452 3453 // Copy the parameter declarations from the declarator D to the function 3454 // declaration NewFD, if they are available. First scavenge them into Params. 3455 llvm::SmallVector<ParmVarDecl*, 16> Params; 3456 if (D.getNumTypeObjects() > 0) { 3457 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 3458 3459 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 3460 // function that takes no arguments, not a function that takes a 3461 // single void argument. 3462 // We let through "const void" here because Sema::GetTypeForDeclarator 3463 // already checks for that case. 3464 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 3465 FTI.ArgInfo[0].Param && 3466 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) { 3467 // Empty arg list, don't push any params. 3468 ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>(); 3469 3470 // In C++, the empty parameter-type-list must be spelled "void"; a 3471 // typedef of void is not permitted. 3472 if (getLangOptions().CPlusPlus && 3473 Param->getType().getUnqualifiedType() != Context.VoidTy) 3474 Diag(Param->getLocation(), diag::err_param_typedef_of_void); 3475 // FIXME: Leaks decl? 3476 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 3477 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 3478 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>(); 3479 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 3480 Param->setDeclContext(NewFD); 3481 Params.push_back(Param); 3482 3483 if (Param->isInvalidDecl()) 3484 NewFD->setInvalidDecl(); 3485 } 3486 } 3487 3488 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 3489 // When we're declaring a function with a typedef, typeof, etc as in the 3490 // following example, we'll need to synthesize (unnamed) 3491 // parameters for use in the declaration. 3492 // 3493 // @code 3494 // typedef void fn(int); 3495 // fn f; 3496 // @endcode 3497 3498 // Synthesize a parameter for each argument type. 3499 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 3500 AE = FT->arg_type_end(); AI != AE; ++AI) { 3501 ParmVarDecl *Param = 3502 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 3503 Params.push_back(Param); 3504 } 3505 } else { 3506 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 3507 "Should not need args for typedef of non-prototype fn"); 3508 } 3509 // Finally, we know we have the right number of parameters, install them. 3510 NewFD->setParams(Params.data(), Params.size()); 3511 3512 // If the declarator is a template-id, translate the parser's template 3513 // argument list into our AST format. 3514 bool HasExplicitTemplateArgs = false; 3515 TemplateArgumentListInfo TemplateArgs; 3516 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 3517 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 3518 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 3519 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 3520 ASTTemplateArgsPtr TemplateArgsPtr(*this, 3521 TemplateId->getTemplateArgs(), 3522 TemplateId->NumArgs); 3523 translateTemplateArguments(TemplateArgsPtr, 3524 TemplateArgs); 3525 TemplateArgsPtr.release(); 3526 3527 HasExplicitTemplateArgs = true; 3528 3529 if (FunctionTemplate) { 3530 // FIXME: Diagnose function template with explicit template 3531 // arguments. 3532 HasExplicitTemplateArgs = false; 3533 } else if (!isFunctionTemplateSpecialization && 3534 !D.getDeclSpec().isFriendSpecified()) { 3535 // We have encountered something that the user meant to be a 3536 // specialization (because it has explicitly-specified template 3537 // arguments) but that was not introduced with a "template<>" (or had 3538 // too few of them). 3539 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 3540 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 3541 << FixItHint::CreateInsertion( 3542 D.getDeclSpec().getSourceRange().getBegin(), 3543 "template<> "); 3544 isFunctionTemplateSpecialization = true; 3545 } else { 3546 // "friend void foo<>(int);" is an implicit specialization decl. 3547 isFunctionTemplateSpecialization = true; 3548 } 3549 } else if (isFriend && isFunctionTemplateSpecialization) { 3550 // This combination is only possible in a recovery case; the user 3551 // wrote something like: 3552 // template <> friend void foo(int); 3553 // which we're recovering from as if the user had written: 3554 // friend void foo<>(int); 3555 // Go ahead and fake up a template id. 3556 HasExplicitTemplateArgs = true; 3557 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 3558 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 3559 } 3560 3561 // If it's a friend (and only if it's a friend), it's possible 3562 // that either the specialized function type or the specialized 3563 // template is dependent, and therefore matching will fail. In 3564 // this case, don't check the specialization yet. 3565 if (isFunctionTemplateSpecialization && isFriend && 3566 (NewFD->getType()->isDependentType() || DC->isDependentContext())) { 3567 assert(HasExplicitTemplateArgs && 3568 "friend function specialization without template args"); 3569 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 3570 Previous)) 3571 NewFD->setInvalidDecl(); 3572 } else if (isFunctionTemplateSpecialization) { 3573 if (CheckFunctionTemplateSpecialization(NewFD, 3574 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 3575 Previous)) 3576 NewFD->setInvalidDecl(); 3577 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 3578 if (CheckMemberSpecialization(NewFD, Previous)) 3579 NewFD->setInvalidDecl(); 3580 } 3581 3582 // Perform semantic checking on the function declaration. 3583 bool OverloadableAttrRequired = false; // FIXME: HACK! 3584 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization, 3585 Redeclaration, /*FIXME:*/OverloadableAttrRequired); 3586 3587 assert((NewFD->isInvalidDecl() || !Redeclaration || 3588 Previous.getResultKind() != LookupResult::FoundOverloaded) && 3589 "previous declaration set still overloaded"); 3590 3591 NamedDecl *PrincipalDecl = (FunctionTemplate 3592 ? cast<NamedDecl>(FunctionTemplate) 3593 : NewFD); 3594 3595 if (isFriend && Redeclaration) { 3596 AccessSpecifier Access = AS_public; 3597 if (!NewFD->isInvalidDecl()) 3598 Access = NewFD->getPreviousDeclaration()->getAccess(); 3599 3600 NewFD->setAccess(Access); 3601 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 3602 3603 PrincipalDecl->setObjectOfFriendDecl(true); 3604 } 3605 3606 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 3607 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 3608 PrincipalDecl->setNonMemberOperator(); 3609 3610 // If we have a function template, check the template parameter 3611 // list. This will check and merge default template arguments. 3612 if (FunctionTemplate) { 3613 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration(); 3614 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 3615 PrevTemplate? PrevTemplate->getTemplateParameters() : 0, 3616 D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate 3617 : TPC_FunctionTemplate); 3618 } 3619 3620 if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) { 3621 // Fake up an access specifier if it's supposed to be a class member. 3622 if (!Redeclaration && isa<CXXRecordDecl>(NewFD->getDeclContext())) 3623 NewFD->setAccess(AS_public); 3624 3625 // An out-of-line member function declaration must also be a 3626 // definition (C++ [dcl.meaning]p1). 3627 // Note that this is not the case for explicit specializations of 3628 // function templates or member functions of class templates, per 3629 // C++ [temp.expl.spec]p2. We also allow these declarations as an extension 3630 // for compatibility with old SWIG code which likes to generate them. 3631 if (!IsFunctionDefinition && !isFriend && 3632 !isFunctionTemplateSpecialization && !isExplicitSpecialization) { 3633 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 3634 << D.getCXXScopeSpec().getRange(); 3635 } 3636 if (!Redeclaration && !(isFriend && CurContext->isDependentContext())) { 3637 // The user tried to provide an out-of-line definition for a 3638 // function that is a member of a class or namespace, but there 3639 // was no such member function declared (C++ [class.mfct]p2, 3640 // C++ [namespace.memdef]p2). For example: 3641 // 3642 // class X { 3643 // void f() const; 3644 // }; 3645 // 3646 // void X::f() { } // ill-formed 3647 // 3648 // Complain about this problem, and attempt to suggest close 3649 // matches (e.g., those that differ only in cv-qualifiers and 3650 // whether the parameter types are references). 3651 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match) 3652 << Name << DC << D.getCXXScopeSpec().getRange(); 3653 NewFD->setInvalidDecl(); 3654 3655 LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName, 3656 ForRedeclaration); 3657 LookupQualifiedName(Prev, DC); 3658 assert(!Prev.isAmbiguous() && 3659 "Cannot have an ambiguity in previous-declaration lookup"); 3660 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 3661 Func != FuncEnd; ++Func) { 3662 if (isa<FunctionDecl>(*Func) && 3663 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD)) 3664 Diag((*Func)->getLocation(), diag::note_member_def_close_match); 3665 } 3666 } 3667 } 3668 3669 // Handle attributes. We need to have merged decls when handling attributes 3670 // (for example to check for conflicts, etc). 3671 // FIXME: This needs to happen before we merge declarations. Then, 3672 // let attribute merging cope with attribute conflicts. 3673 ProcessDeclAttributes(S, NewFD, D); 3674 3675 // attributes declared post-definition are currently ignored 3676 if (Redeclaration && Previous.isSingleResult()) { 3677 const FunctionDecl *Def; 3678 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl()); 3679 if (PrevFD && PrevFD->hasBody(Def) && D.hasAttributes()) { 3680 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition); 3681 Diag(Def->getLocation(), diag::note_previous_definition); 3682 } 3683 } 3684 3685 AddKnownFunctionAttributes(NewFD); 3686 3687 if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) { 3688 // If a function name is overloadable in C, then every function 3689 // with that name must be marked "overloadable". 3690 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 3691 << Redeclaration << NewFD; 3692 if (!Previous.empty()) 3693 Diag(Previous.getRepresentativeDecl()->getLocation(), 3694 diag::note_attribute_overloadable_prev_overload); 3695 NewFD->addAttr(::new (Context) OverloadableAttr()); 3696 } 3697 3698 if (NewFD->hasAttr<OverloadableAttr>() && 3699 !NewFD->getType()->getAs<FunctionProtoType>()) { 3700 Diag(NewFD->getLocation(), 3701 diag::err_attribute_overloadable_no_prototype) 3702 << NewFD; 3703 3704 // Turn this into a variadic function with no parameters. 3705 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 3706 QualType R = Context.getFunctionType(FT->getResultType(), 3707 0, 0, true, 0, false, false, 0, 0, 3708 FT->getExtInfo()); 3709 NewFD->setType(R); 3710 } 3711 3712 // If there's a #pragma GCC visibility in scope, and this isn't a class 3713 // member, set the visibility of this function. 3714 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord()) 3715 AddPushedVisibilityAttribute(NewFD); 3716 3717 // If this is a locally-scoped extern C function, update the 3718 // map of such names. 3719 if (CurContext->isFunctionOrMethod() && NewFD->isExternC() 3720 && !NewFD->isInvalidDecl()) 3721 RegisterLocallyScopedExternCDecl(NewFD, Previous, S); 3722 3723 // Set this FunctionDecl's range up to the right paren. 3724 NewFD->setLocEnd(D.getSourceRange().getEnd()); 3725 3726 if (FunctionTemplate && NewFD->isInvalidDecl()) 3727 FunctionTemplate->setInvalidDecl(); 3728 3729 if (FunctionTemplate) 3730 return FunctionTemplate; 3731 3732 MarkUnusedFileScopedDecl(NewFD); 3733 3734 return NewFD; 3735} 3736 3737/// \brief Perform semantic checking of a new function declaration. 3738/// 3739/// Performs semantic analysis of the new function declaration 3740/// NewFD. This routine performs all semantic checking that does not 3741/// require the actual declarator involved in the declaration, and is 3742/// used both for the declaration of functions as they are parsed 3743/// (called via ActOnDeclarator) and for the declaration of functions 3744/// that have been instantiated via C++ template instantiation (called 3745/// via InstantiateDecl). 3746/// 3747/// \param IsExplicitSpecialiation whether this new function declaration is 3748/// an explicit specialization of the previous declaration. 3749/// 3750/// This sets NewFD->isInvalidDecl() to true if there was an error. 3751void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 3752 LookupResult &Previous, 3753 bool IsExplicitSpecialization, 3754 bool &Redeclaration, 3755 bool &OverloadableAttrRequired) { 3756 // If NewFD is already known erroneous, don't do any of this checking. 3757 if (NewFD->isInvalidDecl()) { 3758 // If this is a class member, mark the class invalid immediately. 3759 // This avoids some consistency errors later. 3760 if (isa<CXXMethodDecl>(NewFD)) 3761 cast<CXXMethodDecl>(NewFD)->getParent()->setInvalidDecl(); 3762 3763 return; 3764 } 3765 3766 if (NewFD->getResultType()->isVariablyModifiedType()) { 3767 // Functions returning a variably modified type violate C99 6.7.5.2p2 3768 // because all functions have linkage. 3769 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 3770 return NewFD->setInvalidDecl(); 3771 } 3772 3773 if (NewFD->isMain()) 3774 CheckMain(NewFD); 3775 3776 // Check for a previous declaration of this name. 3777 if (Previous.empty() && NewFD->isExternC()) { 3778 // Since we did not find anything by this name and we're declaring 3779 // an extern "C" function, look for a non-visible extern "C" 3780 // declaration with the same name. 3781 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 3782 = LocallyScopedExternalDecls.find(NewFD->getDeclName()); 3783 if (Pos != LocallyScopedExternalDecls.end()) 3784 Previous.addDecl(Pos->second); 3785 } 3786 3787 // Merge or overload the declaration with an existing declaration of 3788 // the same name, if appropriate. 3789 if (!Previous.empty()) { 3790 // Determine whether NewFD is an overload of PrevDecl or 3791 // a declaration that requires merging. If it's an overload, 3792 // there's no more work to do here; we'll just add the new 3793 // function to the scope. 3794 3795 NamedDecl *OldDecl = 0; 3796 if (!AllowOverloadingOfFunction(Previous, Context)) { 3797 Redeclaration = true; 3798 OldDecl = Previous.getFoundDecl(); 3799 } else { 3800 if (!getLangOptions().CPlusPlus) 3801 OverloadableAttrRequired = true; 3802 3803 switch (CheckOverload(S, NewFD, Previous, OldDecl, 3804 /*NewIsUsingDecl*/ false)) { 3805 case Ovl_Match: 3806 Redeclaration = true; 3807 break; 3808 3809 case Ovl_NonFunction: 3810 Redeclaration = true; 3811 break; 3812 3813 case Ovl_Overload: 3814 Redeclaration = false; 3815 break; 3816 } 3817 } 3818 3819 if (Redeclaration) { 3820 // NewFD and OldDecl represent declarations that need to be 3821 // merged. 3822 if (MergeFunctionDecl(NewFD, OldDecl)) 3823 return NewFD->setInvalidDecl(); 3824 3825 Previous.clear(); 3826 Previous.addDecl(OldDecl); 3827 3828 if (FunctionTemplateDecl *OldTemplateDecl 3829 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 3830 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 3831 FunctionTemplateDecl *NewTemplateDecl 3832 = NewFD->getDescribedFunctionTemplate(); 3833 assert(NewTemplateDecl && "Template/non-template mismatch"); 3834 if (CXXMethodDecl *Method 3835 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 3836 Method->setAccess(OldTemplateDecl->getAccess()); 3837 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 3838 } 3839 3840 // If this is an explicit specialization of a member that is a function 3841 // template, mark it as a member specialization. 3842 if (IsExplicitSpecialization && 3843 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 3844 NewTemplateDecl->setMemberSpecialization(); 3845 assert(OldTemplateDecl->isMemberSpecialization()); 3846 } 3847 } else { 3848 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions 3849 NewFD->setAccess(OldDecl->getAccess()); 3850 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 3851 } 3852 } 3853 } 3854 3855 // Semantic checking for this function declaration (in isolation). 3856 if (getLangOptions().CPlusPlus) { 3857 // C++-specific checks. 3858 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 3859 CheckConstructor(Constructor); 3860 } else if (CXXDestructorDecl *Destructor = 3861 dyn_cast<CXXDestructorDecl>(NewFD)) { 3862 CXXRecordDecl *Record = Destructor->getParent(); 3863 QualType ClassType = Context.getTypeDeclType(Record); 3864 3865 // FIXME: Shouldn't we be able to perform this check even when the class 3866 // type is dependent? Both gcc and edg can handle that. 3867 if (!ClassType->isDependentType()) { 3868 DeclarationName Name 3869 = Context.DeclarationNames.getCXXDestructorName( 3870 Context.getCanonicalType(ClassType)); 3871// NewFD->getDeclName().dump(); 3872// Name.dump(); 3873 if (NewFD->getDeclName() != Name) { 3874 Diag(NewFD->getLocation(), diag::err_destructor_name); 3875 return NewFD->setInvalidDecl(); 3876 } 3877 } 3878 3879 Record->setUserDeclaredDestructor(true); 3880 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no 3881 // user-defined destructor. 3882 Record->setPOD(false); 3883 3884 // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly- 3885 // declared destructor. 3886 // FIXME: C++0x: don't do this for "= default" destructors 3887 Record->setHasTrivialDestructor(false); 3888 } else if (CXXConversionDecl *Conversion 3889 = dyn_cast<CXXConversionDecl>(NewFD)) { 3890 ActOnConversionDeclarator(Conversion); 3891 } 3892 3893 // Find any virtual functions that this function overrides. 3894 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 3895 if (!Method->isFunctionTemplateSpecialization() && 3896 !Method->getDescribedFunctionTemplate()) 3897 AddOverriddenMethods(Method->getParent(), Method); 3898 } 3899 3900 // Extra checking for C++ overloaded operators (C++ [over.oper]). 3901 if (NewFD->isOverloadedOperator() && 3902 CheckOverloadedOperatorDeclaration(NewFD)) 3903 return NewFD->setInvalidDecl(); 3904 3905 // Extra checking for C++0x literal operators (C++0x [over.literal]). 3906 if (NewFD->getLiteralIdentifier() && 3907 CheckLiteralOperatorDeclaration(NewFD)) 3908 return NewFD->setInvalidDecl(); 3909 3910 // In C++, check default arguments now that we have merged decls. Unless 3911 // the lexical context is the class, because in this case this is done 3912 // during delayed parsing anyway. 3913 if (!CurContext->isRecord()) 3914 CheckCXXDefaultArguments(NewFD); 3915 } 3916} 3917 3918void Sema::CheckMain(FunctionDecl* FD) { 3919 // C++ [basic.start.main]p3: A program that declares main to be inline 3920 // or static is ill-formed. 3921 // C99 6.7.4p4: In a hosted environment, the inline function specifier 3922 // shall not appear in a declaration of main. 3923 // static main is not an error under C99, but we should warn about it. 3924 bool isInline = FD->isInlineSpecified(); 3925 bool isStatic = FD->getStorageClass() == FunctionDecl::Static; 3926 if (isInline || isStatic) { 3927 unsigned diagID = diag::warn_unusual_main_decl; 3928 if (isInline || getLangOptions().CPlusPlus) 3929 diagID = diag::err_unusual_main_decl; 3930 3931 int which = isStatic + (isInline << 1) - 1; 3932 Diag(FD->getLocation(), diagID) << which; 3933 } 3934 3935 QualType T = FD->getType(); 3936 assert(T->isFunctionType() && "function decl is not of function type"); 3937 const FunctionType* FT = T->getAs<FunctionType>(); 3938 3939 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 3940 // TODO: add a replacement fixit to turn the return type into 'int'. 3941 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 3942 FD->setInvalidDecl(true); 3943 } 3944 3945 // Treat protoless main() as nullary. 3946 if (isa<FunctionNoProtoType>(FT)) return; 3947 3948 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 3949 unsigned nparams = FTP->getNumArgs(); 3950 assert(FD->getNumParams() == nparams); 3951 3952 bool HasExtraParameters = (nparams > 3); 3953 3954 // Darwin passes an undocumented fourth argument of type char**. If 3955 // other platforms start sprouting these, the logic below will start 3956 // getting shifty. 3957 if (nparams == 4 && 3958 Context.Target.getTriple().getOS() == llvm::Triple::Darwin) 3959 HasExtraParameters = false; 3960 3961 if (HasExtraParameters) { 3962 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 3963 FD->setInvalidDecl(true); 3964 nparams = 3; 3965 } 3966 3967 // FIXME: a lot of the following diagnostics would be improved 3968 // if we had some location information about types. 3969 3970 QualType CharPP = 3971 Context.getPointerType(Context.getPointerType(Context.CharTy)); 3972 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 3973 3974 for (unsigned i = 0; i < nparams; ++i) { 3975 QualType AT = FTP->getArgType(i); 3976 3977 bool mismatch = true; 3978 3979 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 3980 mismatch = false; 3981 else if (Expected[i] == CharPP) { 3982 // As an extension, the following forms are okay: 3983 // char const ** 3984 // char const * const * 3985 // char * const * 3986 3987 QualifierCollector qs; 3988 const PointerType* PT; 3989 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 3990 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 3991 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) { 3992 qs.removeConst(); 3993 mismatch = !qs.empty(); 3994 } 3995 } 3996 3997 if (mismatch) { 3998 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 3999 // TODO: suggest replacing given type with expected type 4000 FD->setInvalidDecl(true); 4001 } 4002 } 4003 4004 if (nparams == 1 && !FD->isInvalidDecl()) { 4005 Diag(FD->getLocation(), diag::warn_main_one_arg); 4006 } 4007} 4008 4009bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 4010 // FIXME: Need strict checking. In C89, we need to check for 4011 // any assignment, increment, decrement, function-calls, or 4012 // commas outside of a sizeof. In C99, it's the same list, 4013 // except that the aforementioned are allowed in unevaluated 4014 // expressions. Everything else falls under the 4015 // "may accept other forms of constant expressions" exception. 4016 // (We never end up here for C++, so the constant expression 4017 // rules there don't matter.) 4018 if (Init->isConstantInitializer(Context, false)) 4019 return false; 4020 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 4021 << Init->getSourceRange(); 4022 return true; 4023} 4024 4025void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) { 4026 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false); 4027} 4028 4029/// AddInitializerToDecl - Adds the initializer Init to the 4030/// declaration dcl. If DirectInit is true, this is C++ direct 4031/// initialization rather than copy initialization. 4032void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) { 4033 Decl *RealDecl = dcl.getAs<Decl>(); 4034 // If there is no declaration, there was an error parsing it. Just ignore 4035 // the initializer. 4036 if (RealDecl == 0) 4037 return; 4038 4039 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 4040 // With declarators parsed the way they are, the parser cannot 4041 // distinguish between a normal initializer and a pure-specifier. 4042 // Thus this grotesque test. 4043 IntegerLiteral *IL; 4044 Expr *Init = static_cast<Expr *>(init.get()); 4045 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 4046 Context.getCanonicalType(IL->getType()) == Context.IntTy) 4047 CheckPureMethod(Method, Init->getSourceRange()); 4048 else { 4049 Diag(Method->getLocation(), diag::err_member_function_initialization) 4050 << Method->getDeclName() << Init->getSourceRange(); 4051 Method->setInvalidDecl(); 4052 } 4053 return; 4054 } 4055 4056 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 4057 if (!VDecl) { 4058 if (getLangOptions().CPlusPlus && 4059 RealDecl->getLexicalDeclContext()->isRecord() && 4060 isa<NamedDecl>(RealDecl)) 4061 Diag(RealDecl->getLocation(), diag::err_member_initialization) 4062 << cast<NamedDecl>(RealDecl)->getDeclName(); 4063 else 4064 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 4065 RealDecl->setInvalidDecl(); 4066 return; 4067 } 4068 4069 // A definition must end up with a complete type, which means it must be 4070 // complete with the restriction that an array type might be completed by the 4071 // initializer; note that later code assumes this restriction. 4072 QualType BaseDeclType = VDecl->getType(); 4073 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 4074 BaseDeclType = Array->getElementType(); 4075 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 4076 diag::err_typecheck_decl_incomplete_type)) { 4077 RealDecl->setInvalidDecl(); 4078 return; 4079 } 4080 4081 // The variable can not have an abstract class type. 4082 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 4083 diag::err_abstract_type_in_decl, 4084 AbstractVariableType)) 4085 VDecl->setInvalidDecl(); 4086 4087 const VarDecl *Def; 4088 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 4089 Diag(VDecl->getLocation(), diag::err_redefinition) 4090 << VDecl->getDeclName(); 4091 Diag(Def->getLocation(), diag::note_previous_definition); 4092 VDecl->setInvalidDecl(); 4093 return; 4094 } 4095 4096 if (getLangOptions().CPlusPlus && VDecl->hasLocalStorage()) 4097 setFunctionHasBranchProtectedScope(); 4098 4099 // Take ownership of the expression, now that we're sure we have somewhere 4100 // to put it. 4101 Expr *Init = init.takeAs<Expr>(); 4102 assert(Init && "missing initializer"); 4103 4104 // Capture the variable that is being initialized and the style of 4105 // initialization. 4106 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 4107 4108 // FIXME: Poor source location information. 4109 InitializationKind Kind 4110 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(), 4111 Init->getLocStart(), 4112 Init->getLocEnd()) 4113 : InitializationKind::CreateCopy(VDecl->getLocation(), 4114 Init->getLocStart()); 4115 4116 // Get the decls type and save a reference for later, since 4117 // CheckInitializerTypes may change it. 4118 QualType DclT = VDecl->getType(), SavT = DclT; 4119 if (VDecl->isBlockVarDecl()) { 4120 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5 4121 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 4122 VDecl->setInvalidDecl(); 4123 } else if (!VDecl->isInvalidDecl()) { 4124 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 4125 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 4126 MultiExprArg(*this, (void**)&Init, 1), 4127 &DclT); 4128 if (Result.isInvalid()) { 4129 VDecl->setInvalidDecl(); 4130 return; 4131 } 4132 4133 Init = Result.takeAs<Expr>(); 4134 4135 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 4136 // Don't check invalid declarations to avoid emitting useless diagnostics. 4137 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 4138 if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4. 4139 CheckForConstantInitializer(Init, DclT); 4140 } 4141 } 4142 } else if (VDecl->isStaticDataMember() && 4143 VDecl->getLexicalDeclContext()->isRecord()) { 4144 // This is an in-class initialization for a static data member, e.g., 4145 // 4146 // struct S { 4147 // static const int value = 17; 4148 // }; 4149 4150 // Attach the initializer 4151 VDecl->setInit(Init); 4152 4153 // C++ [class.mem]p4: 4154 // A member-declarator can contain a constant-initializer only 4155 // if it declares a static member (9.4) of const integral or 4156 // const enumeration type, see 9.4.2. 4157 QualType T = VDecl->getType(); 4158 if (!T->isDependentType() && 4159 (!Context.getCanonicalType(T).isConstQualified() || 4160 !T->isIntegralOrEnumerationType())) { 4161 Diag(VDecl->getLocation(), diag::err_member_initialization) 4162 << VDecl->getDeclName() << Init->getSourceRange(); 4163 VDecl->setInvalidDecl(); 4164 } else { 4165 // C++ [class.static.data]p4: 4166 // If a static data member is of const integral or const 4167 // enumeration type, its declaration in the class definition 4168 // can specify a constant-initializer which shall be an 4169 // integral constant expression (5.19). 4170 if (!Init->isTypeDependent() && 4171 !Init->getType()->isIntegralOrEnumerationType()) { 4172 // We have a non-dependent, non-integral or enumeration type. 4173 Diag(Init->getSourceRange().getBegin(), 4174 diag::err_in_class_initializer_non_integral_type) 4175 << Init->getType() << Init->getSourceRange(); 4176 VDecl->setInvalidDecl(); 4177 } else if (!Init->isTypeDependent() && !Init->isValueDependent()) { 4178 // Check whether the expression is a constant expression. 4179 llvm::APSInt Value; 4180 SourceLocation Loc; 4181 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) { 4182 Diag(Loc, diag::err_in_class_initializer_non_constant) 4183 << Init->getSourceRange(); 4184 VDecl->setInvalidDecl(); 4185 } else if (!VDecl->getType()->isDependentType()) 4186 ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast); 4187 } 4188 } 4189 } else if (VDecl->isFileVarDecl()) { 4190 if (VDecl->getStorageClass() == VarDecl::Extern && 4191 (!getLangOptions().CPlusPlus || 4192 !Context.getBaseElementType(VDecl->getType()).isConstQualified())) 4193 Diag(VDecl->getLocation(), diag::warn_extern_init); 4194 if (!VDecl->isInvalidDecl()) { 4195 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 4196 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 4197 MultiExprArg(*this, (void**)&Init, 1), 4198 &DclT); 4199 if (Result.isInvalid()) { 4200 VDecl->setInvalidDecl(); 4201 return; 4202 } 4203 4204 Init = Result.takeAs<Expr>(); 4205 } 4206 4207 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 4208 // Don't check invalid declarations to avoid emitting useless diagnostics. 4209 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 4210 // C99 6.7.8p4. All file scoped initializers need to be constant. 4211 CheckForConstantInitializer(Init, DclT); 4212 } 4213 } 4214 // If the type changed, it means we had an incomplete type that was 4215 // completed by the initializer. For example: 4216 // int ary[] = { 1, 3, 5 }; 4217 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 4218 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 4219 VDecl->setType(DclT); 4220 Init->setType(DclT); 4221 } 4222 4223 Init = MaybeCreateCXXExprWithTemporaries(Init); 4224 // Attach the initializer to the decl. 4225 VDecl->setInit(Init); 4226 4227 if (getLangOptions().CPlusPlus) { 4228 if (!VDecl->isInvalidDecl() && 4229 !VDecl->getDeclContext()->isDependentContext() && 4230 VDecl->hasGlobalStorage() && 4231 !Init->isConstantInitializer(Context, 4232 VDecl->getType()->isReferenceType())) 4233 Diag(VDecl->getLocation(), diag::warn_global_constructor) 4234 << Init->getSourceRange(); 4235 4236 // Make sure we mark the destructor as used if necessary. 4237 QualType InitType = VDecl->getType(); 4238 while (const ArrayType *Array = Context.getAsArrayType(InitType)) 4239 InitType = Context.getBaseElementType(Array); 4240 if (const RecordType *Record = InitType->getAs<RecordType>()) 4241 FinalizeVarWithDestructor(VDecl, Record); 4242 } 4243 4244 return; 4245} 4246 4247/// ActOnInitializerError - Given that there was an error parsing an 4248/// initializer for the given declaration, try to return to some form 4249/// of sanity. 4250void Sema::ActOnInitializerError(DeclPtrTy dcl) { 4251 // Our main concern here is re-establishing invariants like "a 4252 // variable's type is either dependent or complete". 4253 Decl *D = dcl.getAs<Decl>(); 4254 if (!D || D->isInvalidDecl()) return; 4255 4256 VarDecl *VD = dyn_cast<VarDecl>(D); 4257 if (!VD) return; 4258 4259 QualType Ty = VD->getType(); 4260 if (Ty->isDependentType()) return; 4261 4262 // Require a complete type. 4263 if (RequireCompleteType(VD->getLocation(), 4264 Context.getBaseElementType(Ty), 4265 diag::err_typecheck_decl_incomplete_type)) { 4266 VD->setInvalidDecl(); 4267 return; 4268 } 4269 4270 // Require an abstract type. 4271 if (RequireNonAbstractType(VD->getLocation(), Ty, 4272 diag::err_abstract_type_in_decl, 4273 AbstractVariableType)) { 4274 VD->setInvalidDecl(); 4275 return; 4276 } 4277 4278 // Don't bother complaining about constructors or destructors, 4279 // though. 4280} 4281 4282void Sema::ActOnUninitializedDecl(DeclPtrTy dcl, 4283 bool TypeContainsUndeducedAuto) { 4284 Decl *RealDecl = dcl.getAs<Decl>(); 4285 4286 // If there is no declaration, there was an error parsing it. Just ignore it. 4287 if (RealDecl == 0) 4288 return; 4289 4290 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 4291 QualType Type = Var->getType(); 4292 4293 // C++0x [dcl.spec.auto]p3 4294 if (TypeContainsUndeducedAuto) { 4295 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 4296 << Var->getDeclName() << Type; 4297 Var->setInvalidDecl(); 4298 return; 4299 } 4300 4301 switch (Var->isThisDeclarationADefinition()) { 4302 case VarDecl::Definition: 4303 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 4304 break; 4305 4306 // We have an out-of-line definition of a static data member 4307 // that has an in-class initializer, so we type-check this like 4308 // a declaration. 4309 // 4310 // Fall through 4311 4312 case VarDecl::DeclarationOnly: 4313 // It's only a declaration. 4314 4315 // Block scope. C99 6.7p7: If an identifier for an object is 4316 // declared with no linkage (C99 6.2.2p6), the type for the 4317 // object shall be complete. 4318 if (!Type->isDependentType() && Var->isBlockVarDecl() && 4319 !Var->getLinkage() && !Var->isInvalidDecl() && 4320 RequireCompleteType(Var->getLocation(), Type, 4321 diag::err_typecheck_decl_incomplete_type)) 4322 Var->setInvalidDecl(); 4323 4324 // Make sure that the type is not abstract. 4325 if (!Type->isDependentType() && !Var->isInvalidDecl() && 4326 RequireNonAbstractType(Var->getLocation(), Type, 4327 diag::err_abstract_type_in_decl, 4328 AbstractVariableType)) 4329 Var->setInvalidDecl(); 4330 return; 4331 4332 case VarDecl::TentativeDefinition: 4333 // File scope. C99 6.9.2p2: A declaration of an identifier for an 4334 // object that has file scope without an initializer, and without a 4335 // storage-class specifier or with the storage-class specifier "static", 4336 // constitutes a tentative definition. Note: A tentative definition with 4337 // external linkage is valid (C99 6.2.2p5). 4338 if (!Var->isInvalidDecl()) { 4339 if (const IncompleteArrayType *ArrayT 4340 = Context.getAsIncompleteArrayType(Type)) { 4341 if (RequireCompleteType(Var->getLocation(), 4342 ArrayT->getElementType(), 4343 diag::err_illegal_decl_array_incomplete_type)) 4344 Var->setInvalidDecl(); 4345 } else if (Var->getStorageClass() == VarDecl::Static) { 4346 // C99 6.9.2p3: If the declaration of an identifier for an object is 4347 // a tentative definition and has internal linkage (C99 6.2.2p3), the 4348 // declared type shall not be an incomplete type. 4349 // NOTE: code such as the following 4350 // static struct s; 4351 // struct s { int a; }; 4352 // is accepted by gcc. Hence here we issue a warning instead of 4353 // an error and we do not invalidate the static declaration. 4354 // NOTE: to avoid multiple warnings, only check the first declaration. 4355 if (Var->getPreviousDeclaration() == 0) 4356 RequireCompleteType(Var->getLocation(), Type, 4357 diag::ext_typecheck_decl_incomplete_type); 4358 } 4359 } 4360 4361 // Record the tentative definition; we're done. 4362 if (!Var->isInvalidDecl()) 4363 TentativeDefinitions.push_back(Var); 4364 return; 4365 } 4366 4367 // Provide a specific diagnostic for uninitialized variable 4368 // definitions with incomplete array type. 4369 if (Type->isIncompleteArrayType()) { 4370 Diag(Var->getLocation(), 4371 diag::err_typecheck_incomplete_array_needs_initializer); 4372 Var->setInvalidDecl(); 4373 return; 4374 } 4375 4376 // Provide a specific diagnostic for uninitialized variable 4377 // definitions with reference type. 4378 if (Type->isReferenceType()) { 4379 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 4380 << Var->getDeclName() 4381 << SourceRange(Var->getLocation(), Var->getLocation()); 4382 Var->setInvalidDecl(); 4383 return; 4384 } 4385 4386 // Do not attempt to type-check the default initializer for a 4387 // variable with dependent type. 4388 if (Type->isDependentType()) 4389 return; 4390 4391 if (Var->isInvalidDecl()) 4392 return; 4393 4394 if (RequireCompleteType(Var->getLocation(), 4395 Context.getBaseElementType(Type), 4396 diag::err_typecheck_decl_incomplete_type)) { 4397 Var->setInvalidDecl(); 4398 return; 4399 } 4400 4401 // The variable can not have an abstract class type. 4402 if (RequireNonAbstractType(Var->getLocation(), Type, 4403 diag::err_abstract_type_in_decl, 4404 AbstractVariableType)) { 4405 Var->setInvalidDecl(); 4406 return; 4407 } 4408 4409 const RecordType *Record 4410 = Context.getBaseElementType(Type)->getAs<RecordType>(); 4411 if (Record && getLangOptions().CPlusPlus && !getLangOptions().CPlusPlus0x && 4412 cast<CXXRecordDecl>(Record->getDecl())->isPOD()) { 4413 // C++03 [dcl.init]p9: 4414 // If no initializer is specified for an object, and the 4415 // object is of (possibly cv-qualified) non-POD class type (or 4416 // array thereof), the object shall be default-initialized; if 4417 // the object is of const-qualified type, the underlying class 4418 // type shall have a user-declared default 4419 // constructor. Otherwise, if no initializer is specified for 4420 // a non- static object, the object and its subobjects, if 4421 // any, have an indeterminate initial value); if the object 4422 // or any of its subobjects are of const-qualified type, the 4423 // program is ill-formed. 4424 // FIXME: DPG thinks it is very fishy that C++0x disables this. 4425 } else { 4426 // Check for jumps past the implicit initializer. C++0x 4427 // clarifies that this applies to a "variable with automatic 4428 // storage duration", not a "local variable". 4429 if (getLangOptions().CPlusPlus && Var->hasLocalStorage()) 4430 setFunctionHasBranchProtectedScope(); 4431 4432 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 4433 InitializationKind Kind 4434 = InitializationKind::CreateDefault(Var->getLocation()); 4435 4436 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0); 4437 OwningExprResult Init = InitSeq.Perform(*this, Entity, Kind, 4438 MultiExprArg(*this, 0, 0)); 4439 if (Init.isInvalid()) 4440 Var->setInvalidDecl(); 4441 else if (Init.get()) { 4442 Var->setInit(MaybeCreateCXXExprWithTemporaries(Init.takeAs<Expr>())); 4443 4444 if (getLangOptions().CPlusPlus && !Var->isInvalidDecl() && 4445 Var->hasGlobalStorage() && 4446 !Var->getDeclContext()->isDependentContext() && 4447 !Var->getInit()->isConstantInitializer(Context, false)) 4448 Diag(Var->getLocation(), diag::warn_global_constructor); 4449 } 4450 } 4451 4452 if (!Var->isInvalidDecl() && getLangOptions().CPlusPlus && Record) 4453 FinalizeVarWithDestructor(Var, Record); 4454 } 4455} 4456 4457Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 4458 DeclPtrTy *Group, 4459 unsigned NumDecls) { 4460 llvm::SmallVector<Decl*, 8> Decls; 4461 4462 if (DS.isTypeSpecOwned()) 4463 Decls.push_back((Decl*)DS.getTypeRep()); 4464 4465 for (unsigned i = 0; i != NumDecls; ++i) 4466 if (Decl *D = Group[i].getAs<Decl>()) 4467 Decls.push_back(D); 4468 4469 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, 4470 Decls.data(), Decls.size())); 4471} 4472 4473 4474/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 4475/// to introduce parameters into function prototype scope. 4476Sema::DeclPtrTy 4477Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 4478 const DeclSpec &DS = D.getDeclSpec(); 4479 4480 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 4481 VarDecl::StorageClass StorageClass = VarDecl::None; 4482 VarDecl::StorageClass StorageClassAsWritten = VarDecl::None; 4483 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 4484 StorageClass = VarDecl::Register; 4485 StorageClassAsWritten = VarDecl::Register; 4486 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 4487 Diag(DS.getStorageClassSpecLoc(), 4488 diag::err_invalid_storage_class_in_func_decl); 4489 D.getMutableDeclSpec().ClearStorageClassSpecs(); 4490 } 4491 4492 if (D.getDeclSpec().isThreadSpecified()) 4493 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 4494 4495 DiagnoseFunctionSpecifiers(D); 4496 4497 // Check that there are no default arguments inside the type of this 4498 // parameter (C++ only). 4499 if (getLangOptions().CPlusPlus) 4500 CheckExtraCXXDefaultArguments(D); 4501 4502 TagDecl *OwnedDecl = 0; 4503 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedDecl); 4504 QualType parmDeclType = TInfo->getType(); 4505 4506 if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) { 4507 // C++ [dcl.fct]p6: 4508 // Types shall not be defined in return or parameter types. 4509 Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type) 4510 << Context.getTypeDeclType(OwnedDecl); 4511 } 4512 4513 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 4514 IdentifierInfo *II = D.getIdentifier(); 4515 if (II) { 4516 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 4517 ForRedeclaration); 4518 LookupName(R, S); 4519 if (R.isSingleResult()) { 4520 NamedDecl *PrevDecl = R.getFoundDecl(); 4521 if (PrevDecl->isTemplateParameter()) { 4522 // Maybe we will complain about the shadowed template parameter. 4523 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 4524 // Just pretend that we didn't see the previous declaration. 4525 PrevDecl = 0; 4526 } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) { 4527 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 4528 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4529 4530 // Recover by removing the name 4531 II = 0; 4532 D.SetIdentifier(0, D.getIdentifierLoc()); 4533 D.setInvalidType(true); 4534 } 4535 } 4536 } 4537 4538 // Temporarily put parameter variables in the translation unit, not 4539 // the enclosing context. This prevents them from accidentally 4540 // looking like class members in C++. 4541 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 4542 TInfo, parmDeclType, II, 4543 D.getIdentifierLoc(), 4544 StorageClass, StorageClassAsWritten); 4545 4546 if (D.isInvalidType()) 4547 New->setInvalidDecl(); 4548 4549 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 4550 if (D.getCXXScopeSpec().isSet()) { 4551 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 4552 << D.getCXXScopeSpec().getRange(); 4553 New->setInvalidDecl(); 4554 } 4555 4556 // Add the parameter declaration into this scope. 4557 S->AddDecl(DeclPtrTy::make(New)); 4558 if (II) 4559 IdResolver.AddDecl(New); 4560 4561 ProcessDeclAttributes(S, New, D); 4562 4563 if (New->hasAttr<BlocksAttr>()) { 4564 Diag(New->getLocation(), diag::err_block_on_nonlocal); 4565 } 4566 return DeclPtrTy::make(New); 4567} 4568 4569/// \brief Synthesizes a variable for a parameter arising from a 4570/// typedef. 4571ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 4572 SourceLocation Loc, 4573 QualType T) { 4574 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, 0, 4575 T, Context.getTrivialTypeSourceInfo(T, Loc), 4576 VarDecl::None, VarDecl::None, 0); 4577 Param->setImplicit(); 4578 return Param; 4579} 4580 4581ParmVarDecl *Sema::CheckParameter(DeclContext *DC, 4582 TypeSourceInfo *TSInfo, QualType T, 4583 IdentifierInfo *Name, 4584 SourceLocation NameLoc, 4585 VarDecl::StorageClass StorageClass, 4586 VarDecl::StorageClass StorageClassAsWritten) { 4587 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, NameLoc, Name, 4588 adjustParameterType(T), TSInfo, 4589 StorageClass, StorageClassAsWritten, 4590 0); 4591 4592 // Parameters can not be abstract class types. 4593 // For record types, this is done by the AbstractClassUsageDiagnoser once 4594 // the class has been completely parsed. 4595 if (!CurContext->isRecord() && 4596 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 4597 AbstractParamType)) 4598 New->setInvalidDecl(); 4599 4600 // Parameter declarators cannot be interface types. All ObjC objects are 4601 // passed by reference. 4602 if (T->isObjCObjectType()) { 4603 Diag(NameLoc, 4604 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T; 4605 New->setInvalidDecl(); 4606 } 4607 4608 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 4609 // duration shall not be qualified by an address-space qualifier." 4610 // Since all parameters have automatic store duration, they can not have 4611 // an address space. 4612 if (T.getAddressSpace() != 0) { 4613 Diag(NameLoc, diag::err_arg_with_address_space); 4614 New->setInvalidDecl(); 4615 } 4616 4617 return New; 4618} 4619 4620void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 4621 SourceLocation LocAfterDecls) { 4622 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 4623 "Not a function declarator!"); 4624 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 4625 4626 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 4627 // for a K&R function. 4628 if (!FTI.hasPrototype) { 4629 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 4630 --i; 4631 if (FTI.ArgInfo[i].Param == 0) { 4632 llvm::SmallString<256> Code; 4633 llvm::raw_svector_ostream(Code) << " int " 4634 << FTI.ArgInfo[i].Ident->getName() 4635 << ";\n"; 4636 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 4637 << FTI.ArgInfo[i].Ident 4638 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 4639 4640 // Implicitly declare the argument as type 'int' for lack of a better 4641 // type. 4642 DeclSpec DS; 4643 const char* PrevSpec; // unused 4644 unsigned DiagID; // unused 4645 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 4646 PrevSpec, DiagID); 4647 Declarator ParamD(DS, Declarator::KNRTypeListContext); 4648 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 4649 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 4650 } 4651 } 4652 } 4653} 4654 4655Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, 4656 Declarator &D) { 4657 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 4658 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 4659 "Not a function declarator!"); 4660 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 4661 4662 if (FTI.hasPrototype) { 4663 // FIXME: Diagnose arguments without names in C. 4664 } 4665 4666 Scope *ParentScope = FnBodyScope->getParent(); 4667 4668 DeclPtrTy DP = HandleDeclarator(ParentScope, D, 4669 MultiTemplateParamsArg(*this), 4670 /*IsFunctionDefinition=*/true); 4671 return ActOnStartOfFunctionDef(FnBodyScope, DP); 4672} 4673 4674static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) { 4675 // Don't warn about invalid declarations. 4676 if (FD->isInvalidDecl()) 4677 return false; 4678 4679 // Or declarations that aren't global. 4680 if (!FD->isGlobal()) 4681 return false; 4682 4683 // Don't warn about C++ member functions. 4684 if (isa<CXXMethodDecl>(FD)) 4685 return false; 4686 4687 // Don't warn about 'main'. 4688 if (FD->isMain()) 4689 return false; 4690 4691 // Don't warn about inline functions. 4692 if (FD->isInlineSpecified()) 4693 return false; 4694 4695 // Don't warn about function templates. 4696 if (FD->getDescribedFunctionTemplate()) 4697 return false; 4698 4699 // Don't warn about function template specializations. 4700 if (FD->isFunctionTemplateSpecialization()) 4701 return false; 4702 4703 bool MissingPrototype = true; 4704 for (const FunctionDecl *Prev = FD->getPreviousDeclaration(); 4705 Prev; Prev = Prev->getPreviousDeclaration()) { 4706 // Ignore any declarations that occur in function or method 4707 // scope, because they aren't visible from the header. 4708 if (Prev->getDeclContext()->isFunctionOrMethod()) 4709 continue; 4710 4711 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 4712 break; 4713 } 4714 4715 return MissingPrototype; 4716} 4717 4718Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) { 4719 // Clear the last template instantiation error context. 4720 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 4721 4722 if (!D) 4723 return D; 4724 FunctionDecl *FD = 0; 4725 4726 if (FunctionTemplateDecl *FunTmpl 4727 = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>())) 4728 FD = FunTmpl->getTemplatedDecl(); 4729 else 4730 FD = cast<FunctionDecl>(D.getAs<Decl>()); 4731 4732 // Enter a new function scope 4733 PushFunctionScope(); 4734 4735 // See if this is a redefinition. 4736 // But don't complain if we're in GNU89 mode and the previous definition 4737 // was an extern inline function. 4738 const FunctionDecl *Definition; 4739 if (FD->hasBody(Definition) && 4740 !canRedefineFunction(Definition, getLangOptions())) { 4741 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 4742 Diag(Definition->getLocation(), diag::note_previous_definition); 4743 } 4744 4745 // Builtin functions cannot be defined. 4746 if (unsigned BuiltinID = FD->getBuiltinID()) { 4747 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 4748 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 4749 FD->setInvalidDecl(); 4750 } 4751 } 4752 4753 // The return type of a function definition must be complete 4754 // (C99 6.9.1p3, C++ [dcl.fct]p6). 4755 QualType ResultType = FD->getResultType(); 4756 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 4757 !FD->isInvalidDecl() && 4758 RequireCompleteType(FD->getLocation(), ResultType, 4759 diag::err_func_def_incomplete_result)) 4760 FD->setInvalidDecl(); 4761 4762 // GNU warning -Wmissing-prototypes: 4763 // Warn if a global function is defined without a previous 4764 // prototype declaration. This warning is issued even if the 4765 // definition itself provides a prototype. The aim is to detect 4766 // global functions that fail to be declared in header files. 4767 if (ShouldWarnAboutMissingPrototype(FD)) 4768 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 4769 4770 if (FnBodyScope) 4771 PushDeclContext(FnBodyScope, FD); 4772 4773 // Check the validity of our function parameters 4774 CheckParmsForFunctionDef(FD); 4775 4776 bool ShouldCheckShadow = 4777 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored; 4778 4779 // Introduce our parameters into the function scope 4780 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 4781 ParmVarDecl *Param = FD->getParamDecl(p); 4782 Param->setOwningFunction(FD); 4783 4784 // If this has an identifier, add it to the scope stack. 4785 if (Param->getIdentifier() && FnBodyScope) { 4786 if (ShouldCheckShadow) 4787 CheckShadow(FnBodyScope, Param); 4788 4789 PushOnScopeChains(Param, FnBodyScope); 4790 } 4791 } 4792 4793 // Checking attributes of current function definition 4794 // dllimport attribute. 4795 if (FD->getAttr<DLLImportAttr>() && 4796 (!FD->getAttr<DLLExportAttr>())) { 4797 // dllimport attribute cannot be applied to definition. 4798 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) { 4799 Diag(FD->getLocation(), 4800 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 4801 << "dllimport"; 4802 FD->setInvalidDecl(); 4803 return DeclPtrTy::make(FD); 4804 } 4805 4806 // Visual C++ appears to not think this is an issue, so only issue 4807 // a warning when Microsoft extensions are disabled. 4808 if (!LangOpts.Microsoft) { 4809 // If a symbol previously declared dllimport is later defined, the 4810 // attribute is ignored in subsequent references, and a warning is 4811 // emitted. 4812 Diag(FD->getLocation(), 4813 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 4814 << FD->getName() << "dllimport"; 4815 } 4816 } 4817 return DeclPtrTy::make(FD); 4818} 4819 4820/// \brief Given the set of return statements within a function body, 4821/// compute the variables that are subject to the named return value 4822/// optimization. 4823/// 4824/// Each of the variables that is subject to the named return value 4825/// optimization will be marked as NRVO variables in the AST, and any 4826/// return statement that has a marked NRVO variable as its NRVO candidate can 4827/// use the named return value optimization. 4828/// 4829/// This function applies a very simplistic algorithm for NRVO: if every return 4830/// statement in the function has the same NRVO candidate, that candidate is 4831/// the NRVO variable. 4832/// 4833/// FIXME: Employ a smarter algorithm that accounts for multiple return 4834/// statements and the lifetimes of the NRVO candidates. We should be able to 4835/// find a maximal set of NRVO variables. 4836static void ComputeNRVO(Stmt *Body, ReturnStmt **Returns, unsigned NumReturns) { 4837 const VarDecl *NRVOCandidate = 0; 4838 for (unsigned I = 0; I != NumReturns; ++I) { 4839 if (!Returns[I]->getNRVOCandidate()) 4840 return; 4841 4842 if (!NRVOCandidate) 4843 NRVOCandidate = Returns[I]->getNRVOCandidate(); 4844 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 4845 return; 4846 } 4847 4848 if (NRVOCandidate) 4849 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 4850} 4851 4852Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) { 4853 return ActOnFinishFunctionBody(D, move(BodyArg), false); 4854} 4855 4856Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg, 4857 bool IsInstantiation) { 4858 Decl *dcl = D.getAs<Decl>(); 4859 Stmt *Body = BodyArg.takeAs<Stmt>(); 4860 4861 FunctionDecl *FD = 0; 4862 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 4863 if (FunTmpl) 4864 FD = FunTmpl->getTemplatedDecl(); 4865 else 4866 FD = dyn_cast_or_null<FunctionDecl>(dcl); 4867 4868 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 4869 4870 if (FD) { 4871 FD->setBody(Body); 4872 if (FD->isMain()) { 4873 // C and C++ allow for main to automagically return 0. 4874 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3. 4875 FD->setHasImplicitReturnZero(true); 4876 WP.disableCheckFallThrough(); 4877 } 4878 4879 if (!FD->isInvalidDecl()) { 4880 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 4881 4882 // If this is a constructor, we need a vtable. 4883 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 4884 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 4885 4886 ComputeNRVO(Body, FunctionScopes.back()->Returns.data(), 4887 FunctionScopes.back()->Returns.size()); 4888 } 4889 4890 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 4891 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 4892 assert(MD == getCurMethodDecl() && "Method parsing confused"); 4893 MD->setBody(Body); 4894 MD->setEndLoc(Body->getLocEnd()); 4895 if (!MD->isInvalidDecl()) 4896 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 4897 } else { 4898 return DeclPtrTy(); 4899 } 4900 4901 // Verify and clean out per-function state. 4902 4903 // Check goto/label use. 4904 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 4905 I = getLabelMap().begin(), E = getLabelMap().end(); I != E; ++I) { 4906 LabelStmt *L = I->second; 4907 4908 // Verify that we have no forward references left. If so, there was a goto 4909 // or address of a label taken, but no definition of it. Label fwd 4910 // definitions are indicated with a null substmt. 4911 if (L->getSubStmt() != 0) 4912 continue; 4913 4914 // Emit error. 4915 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName(); 4916 4917 // At this point, we have gotos that use the bogus label. Stitch it into 4918 // the function body so that they aren't leaked and that the AST is well 4919 // formed. 4920 if (Body == 0) { 4921 // The whole function wasn't parsed correctly. 4922 continue; 4923 } 4924 4925 // Otherwise, the body is valid: we want to stitch the label decl into the 4926 // function somewhere so that it is properly owned and so that the goto 4927 // has a valid target. Do this by creating a new compound stmt with the 4928 // label in it. 4929 4930 // Give the label a sub-statement. 4931 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc())); 4932 4933 CompoundStmt *Compound = isa<CXXTryStmt>(Body) ? 4934 cast<CXXTryStmt>(Body)->getTryBlock() : 4935 cast<CompoundStmt>(Body); 4936 llvm::SmallVector<Stmt*, 64> Elements(Compound->body_begin(), 4937 Compound->body_end()); 4938 Elements.push_back(L); 4939 Compound->setStmts(Context, Elements.data(), Elements.size()); 4940 } 4941 4942 if (Body) { 4943 // C++ constructors that have function-try-blocks can't have return 4944 // statements in the handlers of that block. (C++ [except.handle]p14) 4945 // Verify this. 4946 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 4947 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 4948 4949 // Verify that that gotos and switch cases don't jump into scopes illegally. 4950 // Verify that that gotos and switch cases don't jump into scopes illegally. 4951 if (FunctionNeedsScopeChecking() && 4952 !dcl->isInvalidDecl() && 4953 !hasAnyErrorsInThisFunction()) 4954 DiagnoseInvalidJumps(Body); 4955 4956 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 4957 if (!Destructor->getParent()->isDependentType()) 4958 CheckDestructor(Destructor); 4959 4960 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 4961 Destructor->getParent()); 4962 } 4963 4964 // If any errors have occurred, clear out any temporaries that may have 4965 // been leftover. This ensures that these temporaries won't be picked up for 4966 // deletion in some later function. 4967 if (PP.getDiagnostics().hasErrorOccurred()) 4968 ExprTemporaries.clear(); 4969 else if (!isa<FunctionTemplateDecl>(dcl)) { 4970 // Since the body is valid, issue any analysis-based warnings that are 4971 // enabled. 4972 QualType ResultType; 4973 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) { 4974 ResultType = FD->getResultType(); 4975 } 4976 else { 4977 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(dcl); 4978 ResultType = MD->getResultType(); 4979 } 4980 AnalysisWarnings.IssueWarnings(WP, dcl); 4981 } 4982 4983 assert(ExprTemporaries.empty() && "Leftover temporaries in function"); 4984 } 4985 4986 if (!IsInstantiation) 4987 PopDeclContext(); 4988 4989 PopFunctionOrBlockScope(); 4990 4991 // If any errors have occurred, clear out any temporaries that may have 4992 // been leftover. This ensures that these temporaries won't be picked up for 4993 // deletion in some later function. 4994 if (getDiagnostics().hasErrorOccurred()) 4995 ExprTemporaries.clear(); 4996 4997 return D; 4998} 4999 5000/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 5001/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 5002NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 5003 IdentifierInfo &II, Scope *S) { 5004 // Before we produce a declaration for an implicitly defined 5005 // function, see whether there was a locally-scoped declaration of 5006 // this name as a function or variable. If so, use that 5007 // (non-visible) declaration, and complain about it. 5008 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 5009 = LocallyScopedExternalDecls.find(&II); 5010 if (Pos != LocallyScopedExternalDecls.end()) { 5011 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 5012 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 5013 return Pos->second; 5014 } 5015 5016 // Extension in C99. Legal in C90, but warn about it. 5017 if (II.getName().startswith("__builtin_")) 5018 Diag(Loc, diag::warn_builtin_unknown) << &II; 5019 else if (getLangOptions().C99) 5020 Diag(Loc, diag::ext_implicit_function_decl) << &II; 5021 else 5022 Diag(Loc, diag::warn_implicit_function_decl) << &II; 5023 5024 // Set a Declarator for the implicit definition: int foo(); 5025 const char *Dummy; 5026 DeclSpec DS; 5027 unsigned DiagID; 5028 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 5029 Error = Error; // Silence warning. 5030 assert(!Error && "Error setting up implicit decl!"); 5031 Declarator D(DS, Declarator::BlockContext); 5032 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0, 5033 0, 0, false, SourceLocation(), 5034 false, 0,0,0, Loc, Loc, D), 5035 SourceLocation()); 5036 D.SetIdentifier(&II, Loc); 5037 5038 // Insert this function into translation-unit scope. 5039 5040 DeclContext *PrevDC = CurContext; 5041 CurContext = Context.getTranslationUnitDecl(); 5042 5043 FunctionDecl *FD = 5044 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>()); 5045 FD->setImplicit(); 5046 5047 CurContext = PrevDC; 5048 5049 AddKnownFunctionAttributes(FD); 5050 5051 return FD; 5052} 5053 5054/// \brief Adds any function attributes that we know a priori based on 5055/// the declaration of this function. 5056/// 5057/// These attributes can apply both to implicitly-declared builtins 5058/// (like __builtin___printf_chk) or to library-declared functions 5059/// like NSLog or printf. 5060void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 5061 if (FD->isInvalidDecl()) 5062 return; 5063 5064 // If this is a built-in function, map its builtin attributes to 5065 // actual attributes. 5066 if (unsigned BuiltinID = FD->getBuiltinID()) { 5067 // Handle printf-formatting attributes. 5068 unsigned FormatIdx; 5069 bool HasVAListArg; 5070 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 5071 if (!FD->getAttr<FormatAttr>()) 5072 FD->addAttr(::new (Context) FormatAttr(Context, "printf", FormatIdx+1, 5073 HasVAListArg ? 0 : FormatIdx+2)); 5074 } 5075 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 5076 HasVAListArg)) { 5077 if (!FD->getAttr<FormatAttr>()) 5078 FD->addAttr(::new (Context) FormatAttr(Context, "scanf", FormatIdx+1, 5079 HasVAListArg ? 0 : FormatIdx+2)); 5080 } 5081 5082 // Mark const if we don't care about errno and that is the only 5083 // thing preventing the function from being const. This allows 5084 // IRgen to use LLVM intrinsics for such functions. 5085 if (!getLangOptions().MathErrno && 5086 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 5087 if (!FD->getAttr<ConstAttr>()) 5088 FD->addAttr(::new (Context) ConstAttr()); 5089 } 5090 5091 if (Context.BuiltinInfo.isNoReturn(BuiltinID)) 5092 FD->setType(Context.getNoReturnType(FD->getType())); 5093 if (Context.BuiltinInfo.isNoThrow(BuiltinID)) 5094 FD->addAttr(::new (Context) NoThrowAttr()); 5095 if (Context.BuiltinInfo.isConst(BuiltinID)) 5096 FD->addAttr(::new (Context) ConstAttr()); 5097 } 5098 5099 IdentifierInfo *Name = FD->getIdentifier(); 5100 if (!Name) 5101 return; 5102 if ((!getLangOptions().CPlusPlus && 5103 FD->getDeclContext()->isTranslationUnit()) || 5104 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 5105 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 5106 LinkageSpecDecl::lang_c)) { 5107 // Okay: this could be a libc/libm/Objective-C function we know 5108 // about. 5109 } else 5110 return; 5111 5112 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) { 5113 // FIXME: NSLog and NSLogv should be target specific 5114 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) { 5115 // FIXME: We known better than our headers. 5116 const_cast<FormatAttr *>(Format)->setType(Context, "printf"); 5117 } else 5118 FD->addAttr(::new (Context) FormatAttr(Context, "printf", 1, 5119 Name->isStr("NSLogv") ? 0 : 2)); 5120 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 5121 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 5122 // target-specific builtins, perhaps? 5123 if (!FD->getAttr<FormatAttr>()) 5124 FD->addAttr(::new (Context) FormatAttr(Context, "printf", 2, 5125 Name->isStr("vasprintf") ? 0 : 3)); 5126 } 5127} 5128 5129TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 5130 TypeSourceInfo *TInfo) { 5131 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 5132 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 5133 5134 if (!TInfo) { 5135 assert(D.isInvalidType() && "no declarator info for valid type"); 5136 TInfo = Context.getTrivialTypeSourceInfo(T); 5137 } 5138 5139 // Scope manipulation handled by caller. 5140 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 5141 D.getIdentifierLoc(), 5142 D.getIdentifier(), 5143 TInfo); 5144 5145 if (const TagType *TT = T->getAs<TagType>()) { 5146 TagDecl *TD = TT->getDecl(); 5147 5148 // If the TagDecl that the TypedefDecl points to is an anonymous decl 5149 // keep track of the TypedefDecl. 5150 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl()) 5151 TD->setTypedefForAnonDecl(NewTD); 5152 } 5153 5154 if (D.isInvalidType()) 5155 NewTD->setInvalidDecl(); 5156 return NewTD; 5157} 5158 5159 5160/// \brief Determine whether a tag with a given kind is acceptable 5161/// as a redeclaration of the given tag declaration. 5162/// 5163/// \returns true if the new tag kind is acceptable, false otherwise. 5164bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 5165 TagTypeKind NewTag, 5166 SourceLocation NewTagLoc, 5167 const IdentifierInfo &Name) { 5168 // C++ [dcl.type.elab]p3: 5169 // The class-key or enum keyword present in the 5170 // elaborated-type-specifier shall agree in kind with the 5171 // declaration to which the name in the elaborated-type-specifier 5172 // refers. This rule also applies to the form of 5173 // elaborated-type-specifier that declares a class-name or 5174 // friend class since it can be construed as referring to the 5175 // definition of the class. Thus, in any 5176 // elaborated-type-specifier, the enum keyword shall be used to 5177 // refer to an enumeration (7.2), the union class-key shall be 5178 // used to refer to a union (clause 9), and either the class or 5179 // struct class-key shall be used to refer to a class (clause 9) 5180 // declared using the class or struct class-key. 5181 TagTypeKind OldTag = Previous->getTagKind(); 5182 if (OldTag == NewTag) 5183 return true; 5184 5185 if ((OldTag == TTK_Struct || OldTag == TTK_Class) && 5186 (NewTag == TTK_Struct || NewTag == TTK_Class)) { 5187 // Warn about the struct/class tag mismatch. 5188 bool isTemplate = false; 5189 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 5190 isTemplate = Record->getDescribedClassTemplate(); 5191 5192 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 5193 << (NewTag == TTK_Class) 5194 << isTemplate << &Name 5195 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 5196 OldTag == TTK_Class? "class" : "struct"); 5197 Diag(Previous->getLocation(), diag::note_previous_use); 5198 return true; 5199 } 5200 return false; 5201} 5202 5203/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 5204/// former case, Name will be non-null. In the later case, Name will be null. 5205/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 5206/// reference/declaration/definition of a tag. 5207Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 5208 SourceLocation KWLoc, CXXScopeSpec &SS, 5209 IdentifierInfo *Name, SourceLocation NameLoc, 5210 AttributeList *Attr, AccessSpecifier AS, 5211 MultiTemplateParamsArg TemplateParameterLists, 5212 bool &OwnedDecl, bool &IsDependent) { 5213 // If this is not a definition, it must have a name. 5214 assert((Name != 0 || TUK == TUK_Definition) && 5215 "Nameless record must be a definition!"); 5216 5217 OwnedDecl = false; 5218 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 5219 5220 // FIXME: Check explicit specializations more carefully. 5221 bool isExplicitSpecialization = false; 5222 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size(); 5223 bool Invalid = false; 5224 if (TUK != TUK_Reference) { 5225 if (TemplateParameterList *TemplateParams 5226 = MatchTemplateParametersToScopeSpecifier(KWLoc, SS, 5227 (TemplateParameterList**)TemplateParameterLists.get(), 5228 TemplateParameterLists.size(), 5229 TUK == TUK_Friend, 5230 isExplicitSpecialization, 5231 Invalid)) { 5232 // All but one template parameter lists have been matching. 5233 --NumMatchedTemplateParamLists; 5234 5235 if (TemplateParams->size() > 0) { 5236 // This is a declaration or definition of a class template (which may 5237 // be a member of another template). 5238 if (Invalid) 5239 return DeclPtrTy(); 5240 5241 OwnedDecl = false; 5242 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 5243 SS, Name, NameLoc, Attr, 5244 TemplateParams, 5245 AS); 5246 TemplateParameterLists.release(); 5247 return Result.get(); 5248 } else { 5249 // The "template<>" header is extraneous. 5250 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 5251 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 5252 isExplicitSpecialization = true; 5253 } 5254 } 5255 } 5256 5257 DeclContext *SearchDC = CurContext; 5258 DeclContext *DC = CurContext; 5259 bool isStdBadAlloc = false; 5260 5261 RedeclarationKind Redecl = ForRedeclaration; 5262 if (TUK == TUK_Friend || TUK == TUK_Reference) 5263 Redecl = NotForRedeclaration; 5264 5265 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 5266 5267 if (Name && SS.isNotEmpty()) { 5268 // We have a nested-name tag ('struct foo::bar'). 5269 5270 // Check for invalid 'foo::'. 5271 if (SS.isInvalid()) { 5272 Name = 0; 5273 goto CreateNewDecl; 5274 } 5275 5276 // If this is a friend or a reference to a class in a dependent 5277 // context, don't try to make a decl for it. 5278 if (TUK == TUK_Friend || TUK == TUK_Reference) { 5279 DC = computeDeclContext(SS, false); 5280 if (!DC) { 5281 IsDependent = true; 5282 return DeclPtrTy(); 5283 } 5284 } else { 5285 DC = computeDeclContext(SS, true); 5286 if (!DC) { 5287 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 5288 << SS.getRange(); 5289 return DeclPtrTy(); 5290 } 5291 } 5292 5293 if (RequireCompleteDeclContext(SS, DC)) 5294 return DeclPtrTy::make((Decl *)0); 5295 5296 SearchDC = DC; 5297 // Look-up name inside 'foo::'. 5298 LookupQualifiedName(Previous, DC); 5299 5300 if (Previous.isAmbiguous()) 5301 return DeclPtrTy(); 5302 5303 if (Previous.empty()) { 5304 // Name lookup did not find anything. However, if the 5305 // nested-name-specifier refers to the current instantiation, 5306 // and that current instantiation has any dependent base 5307 // classes, we might find something at instantiation time: treat 5308 // this as a dependent elaborated-type-specifier. 5309 if (Previous.wasNotFoundInCurrentInstantiation()) { 5310 IsDependent = true; 5311 return DeclPtrTy(); 5312 } 5313 5314 // A tag 'foo::bar' must already exist. 5315 Diag(NameLoc, diag::err_not_tag_in_scope) 5316 << Kind << Name << DC << SS.getRange(); 5317 Name = 0; 5318 Invalid = true; 5319 goto CreateNewDecl; 5320 } 5321 } else if (Name) { 5322 // If this is a named struct, check to see if there was a previous forward 5323 // declaration or definition. 5324 // FIXME: We're looking into outer scopes here, even when we 5325 // shouldn't be. Doing so can result in ambiguities that we 5326 // shouldn't be diagnosing. 5327 LookupName(Previous, S); 5328 5329 // Note: there used to be some attempt at recovery here. 5330 if (Previous.isAmbiguous()) 5331 return DeclPtrTy(); 5332 5333 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) { 5334 // FIXME: This makes sure that we ignore the contexts associated 5335 // with C structs, unions, and enums when looking for a matching 5336 // tag declaration or definition. See the similar lookup tweak 5337 // in Sema::LookupName; is there a better way to deal with this? 5338 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 5339 SearchDC = SearchDC->getParent(); 5340 } 5341 } 5342 5343 if (Previous.isSingleResult() && 5344 Previous.getFoundDecl()->isTemplateParameter()) { 5345 // Maybe we will complain about the shadowed template parameter. 5346 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 5347 // Just pretend that we didn't see the previous declaration. 5348 Previous.clear(); 5349 } 5350 5351 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace && 5352 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 5353 // This is a declaration of or a reference to "std::bad_alloc". 5354 isStdBadAlloc = true; 5355 5356 if (Previous.empty() && StdBadAlloc) { 5357 // std::bad_alloc has been implicitly declared (but made invisible to 5358 // name lookup). Fill in this implicit declaration as the previous 5359 // declaration, so that the declarations get chained appropriately. 5360 Previous.addDecl(getStdBadAlloc()); 5361 } 5362 } 5363 5364 // If we didn't find a previous declaration, and this is a reference 5365 // (or friend reference), move to the correct scope. In C++, we 5366 // also need to do a redeclaration lookup there, just in case 5367 // there's a shadow friend decl. 5368 if (Name && Previous.empty() && 5369 (TUK == TUK_Reference || TUK == TUK_Friend)) { 5370 if (Invalid) goto CreateNewDecl; 5371 assert(SS.isEmpty()); 5372 5373 if (TUK == TUK_Reference) { 5374 // C++ [basic.scope.pdecl]p5: 5375 // -- for an elaborated-type-specifier of the form 5376 // 5377 // class-key identifier 5378 // 5379 // if the elaborated-type-specifier is used in the 5380 // decl-specifier-seq or parameter-declaration-clause of a 5381 // function defined in namespace scope, the identifier is 5382 // declared as a class-name in the namespace that contains 5383 // the declaration; otherwise, except as a friend 5384 // declaration, the identifier is declared in the smallest 5385 // non-class, non-function-prototype scope that contains the 5386 // declaration. 5387 // 5388 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 5389 // C structs and unions. 5390 // 5391 // It is an error in C++ to declare (rather than define) an enum 5392 // type, including via an elaborated type specifier. We'll 5393 // diagnose that later; for now, declare the enum in the same 5394 // scope as we would have picked for any other tag type. 5395 // 5396 // GNU C also supports this behavior as part of its incomplete 5397 // enum types extension, while GNU C++ does not. 5398 // 5399 // Find the context where we'll be declaring the tag. 5400 // FIXME: We would like to maintain the current DeclContext as the 5401 // lexical context, 5402 while (SearchDC->isRecord()) 5403 SearchDC = SearchDC->getParent(); 5404 5405 // Find the scope where we'll be declaring the tag. 5406 while (S->isClassScope() || 5407 (getLangOptions().CPlusPlus && 5408 S->isFunctionPrototypeScope()) || 5409 ((S->getFlags() & Scope::DeclScope) == 0) || 5410 (S->getEntity() && 5411 ((DeclContext *)S->getEntity())->isTransparentContext())) 5412 S = S->getParent(); 5413 } else { 5414 assert(TUK == TUK_Friend); 5415 // C++ [namespace.memdef]p3: 5416 // If a friend declaration in a non-local class first declares a 5417 // class or function, the friend class or function is a member of 5418 // the innermost enclosing namespace. 5419 SearchDC = SearchDC->getEnclosingNamespaceContext(); 5420 } 5421 5422 // In C++, we need to do a redeclaration lookup to properly 5423 // diagnose some problems. 5424 if (getLangOptions().CPlusPlus) { 5425 Previous.setRedeclarationKind(ForRedeclaration); 5426 LookupQualifiedName(Previous, SearchDC); 5427 } 5428 } 5429 5430 if (!Previous.empty()) { 5431 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 5432 5433 // It's okay to have a tag decl in the same scope as a typedef 5434 // which hides a tag decl in the same scope. Finding this 5435 // insanity with a redeclaration lookup can only actually happen 5436 // in C++. 5437 // 5438 // This is also okay for elaborated-type-specifiers, which is 5439 // technically forbidden by the current standard but which is 5440 // okay according to the likely resolution of an open issue; 5441 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 5442 if (getLangOptions().CPlusPlus) { 5443 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(PrevDecl)) { 5444 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 5445 TagDecl *Tag = TT->getDecl(); 5446 if (Tag->getDeclName() == Name && 5447 Tag->getDeclContext()->getLookupContext() 5448 ->Equals(TD->getDeclContext()->getLookupContext())) { 5449 PrevDecl = Tag; 5450 Previous.clear(); 5451 Previous.addDecl(Tag); 5452 } 5453 } 5454 } 5455 } 5456 5457 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 5458 // If this is a use of a previous tag, or if the tag is already declared 5459 // in the same scope (so that the definition/declaration completes or 5460 // rementions the tag), reuse the decl. 5461 if (TUK == TUK_Reference || TUK == TUK_Friend || 5462 isDeclInScope(PrevDecl, SearchDC, S)) { 5463 // Make sure that this wasn't declared as an enum and now used as a 5464 // struct or something similar. 5465 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) { 5466 bool SafeToContinue 5467 = (PrevTagDecl->getTagKind() != TTK_Enum && 5468 Kind != TTK_Enum); 5469 if (SafeToContinue) 5470 Diag(KWLoc, diag::err_use_with_wrong_tag) 5471 << Name 5472 << FixItHint::CreateReplacement(SourceRange(KWLoc), 5473 PrevTagDecl->getKindName()); 5474 else 5475 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 5476 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 5477 5478 if (SafeToContinue) 5479 Kind = PrevTagDecl->getTagKind(); 5480 else { 5481 // Recover by making this an anonymous redefinition. 5482 Name = 0; 5483 Previous.clear(); 5484 Invalid = true; 5485 } 5486 } 5487 5488 if (!Invalid) { 5489 // If this is a use, just return the declaration we found. 5490 5491 // FIXME: In the future, return a variant or some other clue 5492 // for the consumer of this Decl to know it doesn't own it. 5493 // For our current ASTs this shouldn't be a problem, but will 5494 // need to be changed with DeclGroups. 5495 if ((TUK == TUK_Reference && !PrevTagDecl->getFriendObjectKind()) || 5496 TUK == TUK_Friend) 5497 return DeclPtrTy::make(PrevTagDecl); 5498 5499 // Diagnose attempts to redefine a tag. 5500 if (TUK == TUK_Definition) { 5501 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 5502 // If we're defining a specialization and the previous definition 5503 // is from an implicit instantiation, don't emit an error 5504 // here; we'll catch this in the general case below. 5505 if (!isExplicitSpecialization || 5506 !isa<CXXRecordDecl>(Def) || 5507 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind() 5508 == TSK_ExplicitSpecialization) { 5509 Diag(NameLoc, diag::err_redefinition) << Name; 5510 Diag(Def->getLocation(), diag::note_previous_definition); 5511 // If this is a redefinition, recover by making this 5512 // struct be anonymous, which will make any later 5513 // references get the previous definition. 5514 Name = 0; 5515 Previous.clear(); 5516 Invalid = true; 5517 } 5518 } else { 5519 // If the type is currently being defined, complain 5520 // about a nested redefinition. 5521 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 5522 if (Tag->isBeingDefined()) { 5523 Diag(NameLoc, diag::err_nested_redefinition) << Name; 5524 Diag(PrevTagDecl->getLocation(), 5525 diag::note_previous_definition); 5526 Name = 0; 5527 Previous.clear(); 5528 Invalid = true; 5529 } 5530 } 5531 5532 // Okay, this is definition of a previously declared or referenced 5533 // tag PrevDecl. We're going to create a new Decl for it. 5534 } 5535 } 5536 // If we get here we have (another) forward declaration or we 5537 // have a definition. Just create a new decl. 5538 5539 } else { 5540 // If we get here, this is a definition of a new tag type in a nested 5541 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 5542 // new decl/type. We set PrevDecl to NULL so that the entities 5543 // have distinct types. 5544 Previous.clear(); 5545 } 5546 // If we get here, we're going to create a new Decl. If PrevDecl 5547 // is non-NULL, it's a definition of the tag declared by 5548 // PrevDecl. If it's NULL, we have a new definition. 5549 5550 5551 // Otherwise, PrevDecl is not a tag, but was found with tag 5552 // lookup. This is only actually possible in C++, where a few 5553 // things like templates still live in the tag namespace. 5554 } else { 5555 assert(getLangOptions().CPlusPlus); 5556 5557 // Use a better diagnostic if an elaborated-type-specifier 5558 // found the wrong kind of type on the first 5559 // (non-redeclaration) lookup. 5560 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 5561 !Previous.isForRedeclaration()) { 5562 unsigned Kind = 0; 5563 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 5564 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2; 5565 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 5566 Diag(PrevDecl->getLocation(), diag::note_declared_at); 5567 Invalid = true; 5568 5569 // Otherwise, only diagnose if the declaration is in scope. 5570 } else if (!isDeclInScope(PrevDecl, SearchDC, S)) { 5571 // do nothing 5572 5573 // Diagnose implicit declarations introduced by elaborated types. 5574 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 5575 unsigned Kind = 0; 5576 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 5577 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2; 5578 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 5579 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 5580 Invalid = true; 5581 5582 // Otherwise it's a declaration. Call out a particularly common 5583 // case here. 5584 } else if (isa<TypedefDecl>(PrevDecl)) { 5585 Diag(NameLoc, diag::err_tag_definition_of_typedef) 5586 << Name 5587 << cast<TypedefDecl>(PrevDecl)->getUnderlyingType(); 5588 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 5589 Invalid = true; 5590 5591 // Otherwise, diagnose. 5592 } else { 5593 // The tag name clashes with something else in the target scope, 5594 // issue an error and recover by making this tag be anonymous. 5595 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 5596 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5597 Name = 0; 5598 Invalid = true; 5599 } 5600 5601 // The existing declaration isn't relevant to us; we're in a 5602 // new scope, so clear out the previous declaration. 5603 Previous.clear(); 5604 } 5605 } 5606 5607CreateNewDecl: 5608 5609 TagDecl *PrevDecl = 0; 5610 if (Previous.isSingleResult()) 5611 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 5612 5613 // If there is an identifier, use the location of the identifier as the 5614 // location of the decl, otherwise use the location of the struct/union 5615 // keyword. 5616 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 5617 5618 // Otherwise, create a new declaration. If there is a previous 5619 // declaration of the same entity, the two will be linked via 5620 // PrevDecl. 5621 TagDecl *New; 5622 5623 if (Kind == TTK_Enum) { 5624 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 5625 // enum X { A, B, C } D; D should chain to X. 5626 New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc, 5627 cast_or_null<EnumDecl>(PrevDecl)); 5628 // If this is an undefined enum, warn. 5629 if (TUK != TUK_Definition && !Invalid) { 5630 TagDecl *Def; 5631 if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 5632 Diag(Loc, diag::ext_forward_ref_enum_def) 5633 << New; 5634 Diag(Def->getLocation(), diag::note_previous_definition); 5635 } else { 5636 Diag(Loc, 5637 getLangOptions().CPlusPlus? diag::err_forward_ref_enum 5638 : diag::ext_forward_ref_enum); 5639 } 5640 } 5641 } else { 5642 // struct/union/class 5643 5644 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 5645 // struct X { int A; } D; D should chain to X. 5646 if (getLangOptions().CPlusPlus) { 5647 // FIXME: Look for a way to use RecordDecl for simple structs. 5648 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc, 5649 cast_or_null<CXXRecordDecl>(PrevDecl)); 5650 5651 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 5652 StdBadAlloc = cast<CXXRecordDecl>(New); 5653 } else 5654 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc, 5655 cast_or_null<RecordDecl>(PrevDecl)); 5656 } 5657 5658 // Maybe add qualifier info. 5659 if (SS.isNotEmpty()) { 5660 if (SS.isSet()) { 5661 NestedNameSpecifier *NNS 5662 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 5663 New->setQualifierInfo(NNS, SS.getRange()); 5664 if (NumMatchedTemplateParamLists > 0) { 5665 New->setTemplateParameterListsInfo(Context, 5666 NumMatchedTemplateParamLists, 5667 (TemplateParameterList**) TemplateParameterLists.release()); 5668 } 5669 } 5670 else 5671 Invalid = true; 5672 } 5673 5674 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 5675 // Add alignment attributes if necessary; these attributes are checked when 5676 // the ASTContext lays out the structure. 5677 // 5678 // It is important for implementing the correct semantics that this 5679 // happen here (in act on tag decl). The #pragma pack stack is 5680 // maintained as a result of parser callbacks which can occur at 5681 // many points during the parsing of a struct declaration (because 5682 // the #pragma tokens are effectively skipped over during the 5683 // parsing of the struct). 5684 AddAlignmentAttributesForRecord(RD); 5685 } 5686 5687 // If this is a specialization of a member class (of a class template), 5688 // check the specialization. 5689 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 5690 Invalid = true; 5691 5692 if (Invalid) 5693 New->setInvalidDecl(); 5694 5695 if (Attr) 5696 ProcessDeclAttributeList(S, New, Attr); 5697 5698 // If we're declaring or defining a tag in function prototype scope 5699 // in C, note that this type can only be used within the function. 5700 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus) 5701 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 5702 5703 // Set the lexical context. If the tag has a C++ scope specifier, the 5704 // lexical context will be different from the semantic context. 5705 New->setLexicalDeclContext(CurContext); 5706 5707 // Mark this as a friend decl if applicable. 5708 if (TUK == TUK_Friend) 5709 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty()); 5710 5711 // Set the access specifier. 5712 if (!Invalid && SearchDC->isRecord()) 5713 SetMemberAccessSpecifier(New, PrevDecl, AS); 5714 5715 if (TUK == TUK_Definition) 5716 New->startDefinition(); 5717 5718 // If this has an identifier, add it to the scope stack. 5719 if (TUK == TUK_Friend) { 5720 // We might be replacing an existing declaration in the lookup tables; 5721 // if so, borrow its access specifier. 5722 if (PrevDecl) 5723 New->setAccess(PrevDecl->getAccess()); 5724 5725 DeclContext *DC = New->getDeclContext()->getLookupContext(); 5726 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false); 5727 if (Name) // can be null along some error paths 5728 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 5729 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 5730 } else if (Name) { 5731 S = getNonFieldDeclScope(S); 5732 PushOnScopeChains(New, S); 5733 } else { 5734 CurContext->addDecl(New); 5735 } 5736 5737 // If this is the C FILE type, notify the AST context. 5738 if (IdentifierInfo *II = New->getIdentifier()) 5739 if (!New->isInvalidDecl() && 5740 New->getDeclContext()->getLookupContext()->isTranslationUnit() && 5741 II->isStr("FILE")) 5742 Context.setFILEDecl(New); 5743 5744 OwnedDecl = true; 5745 return DeclPtrTy::make(New); 5746} 5747 5748void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) { 5749 AdjustDeclIfTemplate(TagD); 5750 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 5751 5752 // Enter the tag context. 5753 PushDeclContext(S, Tag); 5754} 5755 5756void Sema::ActOnStartCXXMemberDeclarations(Scope *S, DeclPtrTy TagD, 5757 SourceLocation LBraceLoc) { 5758 AdjustDeclIfTemplate(TagD); 5759 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD.getAs<Decl>()); 5760 5761 FieldCollector->StartClass(); 5762 5763 if (!Record->getIdentifier()) 5764 return; 5765 5766 // C++ [class]p2: 5767 // [...] The class-name is also inserted into the scope of the 5768 // class itself; this is known as the injected-class-name. For 5769 // purposes of access checking, the injected-class-name is treated 5770 // as if it were a public member name. 5771 CXXRecordDecl *InjectedClassName 5772 = CXXRecordDecl::Create(Context, Record->getTagKind(), 5773 CurContext, Record->getLocation(), 5774 Record->getIdentifier(), 5775 Record->getTagKeywordLoc(), 5776 Record); 5777 InjectedClassName->setImplicit(); 5778 InjectedClassName->setAccess(AS_public); 5779 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 5780 InjectedClassName->setDescribedClassTemplate(Template); 5781 PushOnScopeChains(InjectedClassName, S); 5782 assert(InjectedClassName->isInjectedClassName() && 5783 "Broken injected-class-name"); 5784} 5785 5786void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD, 5787 SourceLocation RBraceLoc) { 5788 AdjustDeclIfTemplate(TagD); 5789 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 5790 Tag->setRBraceLoc(RBraceLoc); 5791 5792 if (isa<CXXRecordDecl>(Tag)) 5793 FieldCollector->FinishClass(); 5794 5795 // Exit this scope of this tag's definition. 5796 PopDeclContext(); 5797 5798 // Notify the consumer that we've defined a tag. 5799 Consumer.HandleTagDeclDefinition(Tag); 5800} 5801 5802void Sema::ActOnTagDefinitionError(Scope *S, DeclPtrTy TagD) { 5803 AdjustDeclIfTemplate(TagD); 5804 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 5805 Tag->setInvalidDecl(); 5806 5807 // We're undoing ActOnTagStartDefinition here, not 5808 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 5809 // the FieldCollector. 5810 5811 PopDeclContext(); 5812} 5813 5814// Note that FieldName may be null for anonymous bitfields. 5815bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 5816 QualType FieldTy, const Expr *BitWidth, 5817 bool *ZeroWidth) { 5818 // Default to true; that shouldn't confuse checks for emptiness 5819 if (ZeroWidth) 5820 *ZeroWidth = true; 5821 5822 // C99 6.7.2.1p4 - verify the field type. 5823 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 5824 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 5825 // Handle incomplete types with specific error. 5826 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 5827 return true; 5828 if (FieldName) 5829 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 5830 << FieldName << FieldTy << BitWidth->getSourceRange(); 5831 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 5832 << FieldTy << BitWidth->getSourceRange(); 5833 } 5834 5835 // If the bit-width is type- or value-dependent, don't try to check 5836 // it now. 5837 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 5838 return false; 5839 5840 llvm::APSInt Value; 5841 if (VerifyIntegerConstantExpression(BitWidth, &Value)) 5842 return true; 5843 5844 if (Value != 0 && ZeroWidth) 5845 *ZeroWidth = false; 5846 5847 // Zero-width bitfield is ok for anonymous field. 5848 if (Value == 0 && FieldName) 5849 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 5850 5851 if (Value.isSigned() && Value.isNegative()) { 5852 if (FieldName) 5853 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 5854 << FieldName << Value.toString(10); 5855 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 5856 << Value.toString(10); 5857 } 5858 5859 if (!FieldTy->isDependentType()) { 5860 uint64_t TypeSize = Context.getTypeSize(FieldTy); 5861 if (Value.getZExtValue() > TypeSize) { 5862 if (!getLangOptions().CPlusPlus) { 5863 if (FieldName) 5864 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 5865 << FieldName << (unsigned)Value.getZExtValue() 5866 << (unsigned)TypeSize; 5867 5868 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 5869 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 5870 } 5871 5872 if (FieldName) 5873 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 5874 << FieldName << (unsigned)Value.getZExtValue() 5875 << (unsigned)TypeSize; 5876 else 5877 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 5878 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 5879 } 5880 } 5881 5882 return false; 5883} 5884 5885/// ActOnField - Each field of a struct/union/class is passed into this in order 5886/// to create a FieldDecl object for it. 5887Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD, 5888 SourceLocation DeclStart, 5889 Declarator &D, ExprTy *BitfieldWidth) { 5890 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()), 5891 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 5892 AS_public); 5893 return DeclPtrTy::make(Res); 5894} 5895 5896/// HandleField - Analyze a field of a C struct or a C++ data member. 5897/// 5898FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 5899 SourceLocation DeclStart, 5900 Declarator &D, Expr *BitWidth, 5901 AccessSpecifier AS) { 5902 IdentifierInfo *II = D.getIdentifier(); 5903 SourceLocation Loc = DeclStart; 5904 if (II) Loc = D.getIdentifierLoc(); 5905 5906 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5907 QualType T = TInfo->getType(); 5908 if (getLangOptions().CPlusPlus) 5909 CheckExtraCXXDefaultArguments(D); 5910 5911 DiagnoseFunctionSpecifiers(D); 5912 5913 if (D.getDeclSpec().isThreadSpecified()) 5914 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 5915 5916 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 5917 ForRedeclaration); 5918 5919 if (PrevDecl && PrevDecl->isTemplateParameter()) { 5920 // Maybe we will complain about the shadowed template parameter. 5921 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 5922 // Just pretend that we didn't see the previous declaration. 5923 PrevDecl = 0; 5924 } 5925 5926 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 5927 PrevDecl = 0; 5928 5929 bool Mutable 5930 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 5931 SourceLocation TSSL = D.getSourceRange().getBegin(); 5932 FieldDecl *NewFD 5933 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL, 5934 AS, PrevDecl, &D); 5935 5936 if (NewFD->isInvalidDecl()) 5937 Record->setInvalidDecl(); 5938 5939 if (NewFD->isInvalidDecl() && PrevDecl) { 5940 // Don't introduce NewFD into scope; there's already something 5941 // with the same name in the same scope. 5942 } else if (II) { 5943 PushOnScopeChains(NewFD, S); 5944 } else 5945 Record->addDecl(NewFD); 5946 5947 return NewFD; 5948} 5949 5950/// \brief Build a new FieldDecl and check its well-formedness. 5951/// 5952/// This routine builds a new FieldDecl given the fields name, type, 5953/// record, etc. \p PrevDecl should refer to any previous declaration 5954/// with the same name and in the same scope as the field to be 5955/// created. 5956/// 5957/// \returns a new FieldDecl. 5958/// 5959/// \todo The Declarator argument is a hack. It will be removed once 5960FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 5961 TypeSourceInfo *TInfo, 5962 RecordDecl *Record, SourceLocation Loc, 5963 bool Mutable, Expr *BitWidth, 5964 SourceLocation TSSL, 5965 AccessSpecifier AS, NamedDecl *PrevDecl, 5966 Declarator *D) { 5967 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5968 bool InvalidDecl = false; 5969 if (D) InvalidDecl = D->isInvalidType(); 5970 5971 // If we receive a broken type, recover by assuming 'int' and 5972 // marking this declaration as invalid. 5973 if (T.isNull()) { 5974 InvalidDecl = true; 5975 T = Context.IntTy; 5976 } 5977 5978 QualType EltTy = Context.getBaseElementType(T); 5979 if (!EltTy->isDependentType() && 5980 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 5981 // Fields of incomplete type force their record to be invalid. 5982 Record->setInvalidDecl(); 5983 InvalidDecl = true; 5984 } 5985 5986 // C99 6.7.2.1p8: A member of a structure or union may have any type other 5987 // than a variably modified type. 5988 if (!InvalidDecl && T->isVariablyModifiedType()) { 5989 bool SizeIsNegative; 5990 llvm::APSInt Oversized; 5991 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context, 5992 SizeIsNegative, 5993 Oversized); 5994 if (!FixedTy.isNull()) { 5995 Diag(Loc, diag::warn_illegal_constant_array_size); 5996 T = FixedTy; 5997 } else { 5998 if (SizeIsNegative) 5999 Diag(Loc, diag::err_typecheck_negative_array_size); 6000 else if (Oversized.getBoolValue()) 6001 Diag(Loc, diag::err_array_too_large) 6002 << Oversized.toString(10); 6003 else 6004 Diag(Loc, diag::err_typecheck_field_variable_size); 6005 InvalidDecl = true; 6006 } 6007 } 6008 6009 // Fields can not have abstract class types 6010 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 6011 diag::err_abstract_type_in_decl, 6012 AbstractFieldType)) 6013 InvalidDecl = true; 6014 6015 bool ZeroWidth = false; 6016 // If this is declared as a bit-field, check the bit-field. 6017 if (!InvalidDecl && BitWidth && 6018 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) { 6019 InvalidDecl = true; 6020 DeleteExpr(BitWidth); 6021 BitWidth = 0; 6022 ZeroWidth = false; 6023 } 6024 6025 // Check that 'mutable' is consistent with the type of the declaration. 6026 if (!InvalidDecl && Mutable) { 6027 unsigned DiagID = 0; 6028 if (T->isReferenceType()) 6029 DiagID = diag::err_mutable_reference; 6030 else if (T.isConstQualified()) 6031 DiagID = diag::err_mutable_const; 6032 6033 if (DiagID) { 6034 SourceLocation ErrLoc = Loc; 6035 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 6036 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 6037 Diag(ErrLoc, DiagID); 6038 Mutable = false; 6039 InvalidDecl = true; 6040 } 6041 } 6042 6043 FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo, 6044 BitWidth, Mutable); 6045 if (InvalidDecl) 6046 NewFD->setInvalidDecl(); 6047 6048 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 6049 Diag(Loc, diag::err_duplicate_member) << II; 6050 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 6051 NewFD->setInvalidDecl(); 6052 } 6053 6054 if (!InvalidDecl && getLangOptions().CPlusPlus) { 6055 CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record); 6056 6057 if (!T->isPODType()) 6058 CXXRecord->setPOD(false); 6059 if (!ZeroWidth) 6060 CXXRecord->setEmpty(false); 6061 6062 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 6063 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 6064 if (RDecl->getDefinition()) { 6065 if (!RDecl->hasTrivialConstructor()) 6066 CXXRecord->setHasTrivialConstructor(false); 6067 if (!RDecl->hasTrivialCopyConstructor()) 6068 CXXRecord->setHasTrivialCopyConstructor(false); 6069 if (!RDecl->hasTrivialCopyAssignment()) 6070 CXXRecord->setHasTrivialCopyAssignment(false); 6071 if (!RDecl->hasTrivialDestructor()) 6072 CXXRecord->setHasTrivialDestructor(false); 6073 6074 // C++ 9.5p1: An object of a class with a non-trivial 6075 // constructor, a non-trivial copy constructor, a non-trivial 6076 // destructor, or a non-trivial copy assignment operator 6077 // cannot be a member of a union, nor can an array of such 6078 // objects. 6079 // TODO: C++0x alters this restriction significantly. 6080 if (Record->isUnion() && CheckNontrivialField(NewFD)) 6081 NewFD->setInvalidDecl(); 6082 } 6083 } 6084 } 6085 6086 // FIXME: We need to pass in the attributes given an AST 6087 // representation, not a parser representation. 6088 if (D) 6089 // FIXME: What to pass instead of TUScope? 6090 ProcessDeclAttributes(TUScope, NewFD, *D); 6091 6092 if (T.isObjCGCWeak()) 6093 Diag(Loc, diag::warn_attribute_weak_on_field); 6094 6095 NewFD->setAccess(AS); 6096 6097 // C++ [dcl.init.aggr]p1: 6098 // An aggregate is an array or a class (clause 9) with [...] no 6099 // private or protected non-static data members (clause 11). 6100 // A POD must be an aggregate. 6101 if (getLangOptions().CPlusPlus && 6102 (AS == AS_private || AS == AS_protected)) { 6103 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 6104 CXXRecord->setAggregate(false); 6105 CXXRecord->setPOD(false); 6106 } 6107 6108 return NewFD; 6109} 6110 6111bool Sema::CheckNontrivialField(FieldDecl *FD) { 6112 assert(FD); 6113 assert(getLangOptions().CPlusPlus && "valid check only for C++"); 6114 6115 if (FD->isInvalidDecl()) 6116 return true; 6117 6118 QualType EltTy = Context.getBaseElementType(FD->getType()); 6119 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 6120 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 6121 if (RDecl->getDefinition()) { 6122 // We check for copy constructors before constructors 6123 // because otherwise we'll never get complaints about 6124 // copy constructors. 6125 6126 CXXSpecialMember member = CXXInvalid; 6127 if (!RDecl->hasTrivialCopyConstructor()) 6128 member = CXXCopyConstructor; 6129 else if (!RDecl->hasTrivialConstructor()) 6130 member = CXXConstructor; 6131 else if (!RDecl->hasTrivialCopyAssignment()) 6132 member = CXXCopyAssignment; 6133 else if (!RDecl->hasTrivialDestructor()) 6134 member = CXXDestructor; 6135 6136 if (member != CXXInvalid) { 6137 Diag(FD->getLocation(), diag::err_illegal_union_or_anon_struct_member) 6138 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 6139 DiagnoseNontrivial(RT, member); 6140 return true; 6141 } 6142 } 6143 } 6144 6145 return false; 6146} 6147 6148/// DiagnoseNontrivial - Given that a class has a non-trivial 6149/// special member, figure out why. 6150void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) { 6151 QualType QT(T, 0U); 6152 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl()); 6153 6154 // Check whether the member was user-declared. 6155 switch (member) { 6156 case CXXInvalid: 6157 break; 6158 6159 case CXXConstructor: 6160 if (RD->hasUserDeclaredConstructor()) { 6161 typedef CXXRecordDecl::ctor_iterator ctor_iter; 6162 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){ 6163 const FunctionDecl *body = 0; 6164 ci->hasBody(body); 6165 if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) { 6166 SourceLocation CtorLoc = ci->getLocation(); 6167 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 6168 return; 6169 } 6170 } 6171 6172 assert(0 && "found no user-declared constructors"); 6173 return; 6174 } 6175 break; 6176 6177 case CXXCopyConstructor: 6178 if (RD->hasUserDeclaredCopyConstructor()) { 6179 SourceLocation CtorLoc = 6180 RD->getCopyConstructor(Context, 0)->getLocation(); 6181 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 6182 return; 6183 } 6184 break; 6185 6186 case CXXCopyAssignment: 6187 if (RD->hasUserDeclaredCopyAssignment()) { 6188 // FIXME: this should use the location of the copy 6189 // assignment, not the type. 6190 SourceLocation TyLoc = RD->getSourceRange().getBegin(); 6191 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member; 6192 return; 6193 } 6194 break; 6195 6196 case CXXDestructor: 6197 if (RD->hasUserDeclaredDestructor()) { 6198 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation(); 6199 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member; 6200 return; 6201 } 6202 break; 6203 } 6204 6205 typedef CXXRecordDecl::base_class_iterator base_iter; 6206 6207 // Virtual bases and members inhibit trivial copying/construction, 6208 // but not trivial destruction. 6209 if (member != CXXDestructor) { 6210 // Check for virtual bases. vbases includes indirect virtual bases, 6211 // so we just iterate through the direct bases. 6212 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) 6213 if (bi->isVirtual()) { 6214 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 6215 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1; 6216 return; 6217 } 6218 6219 // Check for virtual methods. 6220 typedef CXXRecordDecl::method_iterator meth_iter; 6221 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me; 6222 ++mi) { 6223 if (mi->isVirtual()) { 6224 SourceLocation MLoc = mi->getSourceRange().getBegin(); 6225 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0; 6226 return; 6227 } 6228 } 6229 } 6230 6231 bool (CXXRecordDecl::*hasTrivial)() const; 6232 switch (member) { 6233 case CXXConstructor: 6234 hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break; 6235 case CXXCopyConstructor: 6236 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break; 6237 case CXXCopyAssignment: 6238 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break; 6239 case CXXDestructor: 6240 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break; 6241 default: 6242 assert(0 && "unexpected special member"); return; 6243 } 6244 6245 // Check for nontrivial bases (and recurse). 6246 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) { 6247 const RecordType *BaseRT = bi->getType()->getAs<RecordType>(); 6248 assert(BaseRT && "Don't know how to handle dependent bases"); 6249 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl()); 6250 if (!(BaseRecTy->*hasTrivial)()) { 6251 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 6252 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member; 6253 DiagnoseNontrivial(BaseRT, member); 6254 return; 6255 } 6256 } 6257 6258 // Check for nontrivial members (and recurse). 6259 typedef RecordDecl::field_iterator field_iter; 6260 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe; 6261 ++fi) { 6262 QualType EltTy = Context.getBaseElementType((*fi)->getType()); 6263 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) { 6264 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl()); 6265 6266 if (!(EltRD->*hasTrivial)()) { 6267 SourceLocation FLoc = (*fi)->getLocation(); 6268 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member; 6269 DiagnoseNontrivial(EltRT, member); 6270 return; 6271 } 6272 } 6273 } 6274 6275 assert(0 && "found no explanation for non-trivial member"); 6276} 6277 6278/// TranslateIvarVisibility - Translate visibility from a token ID to an 6279/// AST enum value. 6280static ObjCIvarDecl::AccessControl 6281TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 6282 switch (ivarVisibility) { 6283 default: assert(0 && "Unknown visitibility kind"); 6284 case tok::objc_private: return ObjCIvarDecl::Private; 6285 case tok::objc_public: return ObjCIvarDecl::Public; 6286 case tok::objc_protected: return ObjCIvarDecl::Protected; 6287 case tok::objc_package: return ObjCIvarDecl::Package; 6288 } 6289} 6290 6291/// ActOnIvar - Each ivar field of an objective-c class is passed into this 6292/// in order to create an IvarDecl object for it. 6293Sema::DeclPtrTy Sema::ActOnIvar(Scope *S, 6294 SourceLocation DeclStart, 6295 DeclPtrTy IntfDecl, 6296 Declarator &D, ExprTy *BitfieldWidth, 6297 tok::ObjCKeywordKind Visibility) { 6298 6299 IdentifierInfo *II = D.getIdentifier(); 6300 Expr *BitWidth = (Expr*)BitfieldWidth; 6301 SourceLocation Loc = DeclStart; 6302 if (II) Loc = D.getIdentifierLoc(); 6303 6304 // FIXME: Unnamed fields can be handled in various different ways, for 6305 // example, unnamed unions inject all members into the struct namespace! 6306 6307 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6308 QualType T = TInfo->getType(); 6309 6310 if (BitWidth) { 6311 // 6.7.2.1p3, 6.7.2.1p4 6312 if (VerifyBitField(Loc, II, T, BitWidth)) { 6313 D.setInvalidType(); 6314 DeleteExpr(BitWidth); 6315 BitWidth = 0; 6316 } 6317 } else { 6318 // Not a bitfield. 6319 6320 // validate II. 6321 6322 } 6323 if (T->isReferenceType()) { 6324 Diag(Loc, diag::err_ivar_reference_type); 6325 D.setInvalidType(); 6326 } 6327 // C99 6.7.2.1p8: A member of a structure or union may have any type other 6328 // than a variably modified type. 6329 else if (T->isVariablyModifiedType()) { 6330 Diag(Loc, diag::err_typecheck_ivar_variable_size); 6331 D.setInvalidType(); 6332 } 6333 6334 // Get the visibility (access control) for this ivar. 6335 ObjCIvarDecl::AccessControl ac = 6336 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 6337 : ObjCIvarDecl::None; 6338 // Must set ivar's DeclContext to its enclosing interface. 6339 ObjCContainerDecl *EnclosingDecl = IntfDecl.getAs<ObjCContainerDecl>(); 6340 ObjCContainerDecl *EnclosingContext; 6341 if (ObjCImplementationDecl *IMPDecl = 6342 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 6343 // Case of ivar declared in an implementation. Context is that of its class. 6344 EnclosingContext = IMPDecl->getClassInterface(); 6345 assert(EnclosingContext && "Implementation has no class interface!"); 6346 } else { 6347 if (ObjCCategoryDecl *CDecl = 6348 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 6349 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) { 6350 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 6351 return DeclPtrTy(); 6352 } 6353 } 6354 EnclosingContext = EnclosingDecl; 6355 } 6356 6357 // Construct the decl. 6358 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, 6359 EnclosingContext, Loc, II, T, 6360 TInfo, ac, (Expr *)BitfieldWidth); 6361 6362 if (II) { 6363 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 6364 ForRedeclaration); 6365 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 6366 && !isa<TagDecl>(PrevDecl)) { 6367 Diag(Loc, diag::err_duplicate_member) << II; 6368 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 6369 NewID->setInvalidDecl(); 6370 } 6371 } 6372 6373 // Process attributes attached to the ivar. 6374 ProcessDeclAttributes(S, NewID, D); 6375 6376 if (D.isInvalidType()) 6377 NewID->setInvalidDecl(); 6378 6379 if (II) { 6380 // FIXME: When interfaces are DeclContexts, we'll need to add 6381 // these to the interface. 6382 S->AddDecl(DeclPtrTy::make(NewID)); 6383 IdResolver.AddDecl(NewID); 6384 } 6385 6386 return DeclPtrTy::make(NewID); 6387} 6388 6389void Sema::ActOnFields(Scope* S, 6390 SourceLocation RecLoc, DeclPtrTy RecDecl, 6391 DeclPtrTy *Fields, unsigned NumFields, 6392 SourceLocation LBrac, SourceLocation RBrac, 6393 AttributeList *Attr) { 6394 Decl *EnclosingDecl = RecDecl.getAs<Decl>(); 6395 assert(EnclosingDecl && "missing record or interface decl"); 6396 6397 // If the decl this is being inserted into is invalid, then it may be a 6398 // redeclaration or some other bogus case. Don't try to add fields to it. 6399 if (EnclosingDecl->isInvalidDecl()) { 6400 // FIXME: Deallocate fields? 6401 return; 6402 } 6403 6404 6405 // Verify that all the fields are okay. 6406 unsigned NumNamedMembers = 0; 6407 llvm::SmallVector<FieldDecl*, 32> RecFields; 6408 6409 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 6410 for (unsigned i = 0; i != NumFields; ++i) { 6411 FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>()); 6412 6413 // Get the type for the field. 6414 Type *FDTy = FD->getType().getTypePtr(); 6415 6416 if (!FD->isAnonymousStructOrUnion()) { 6417 // Remember all fields written by the user. 6418 RecFields.push_back(FD); 6419 } 6420 6421 // If the field is already invalid for some reason, don't emit more 6422 // diagnostics about it. 6423 if (FD->isInvalidDecl()) { 6424 EnclosingDecl->setInvalidDecl(); 6425 continue; 6426 } 6427 6428 // C99 6.7.2.1p2: 6429 // A structure or union shall not contain a member with 6430 // incomplete or function type (hence, a structure shall not 6431 // contain an instance of itself, but may contain a pointer to 6432 // an instance of itself), except that the last member of a 6433 // structure with more than one named member may have incomplete 6434 // array type; such a structure (and any union containing, 6435 // possibly recursively, a member that is such a structure) 6436 // shall not be a member of a structure or an element of an 6437 // array. 6438 if (FDTy->isFunctionType()) { 6439 // Field declared as a function. 6440 Diag(FD->getLocation(), diag::err_field_declared_as_function) 6441 << FD->getDeclName(); 6442 FD->setInvalidDecl(); 6443 EnclosingDecl->setInvalidDecl(); 6444 continue; 6445 } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 && 6446 Record && Record->isStruct()) { 6447 // Flexible array member. 6448 if (NumNamedMembers < 1) { 6449 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 6450 << FD->getDeclName(); 6451 FD->setInvalidDecl(); 6452 EnclosingDecl->setInvalidDecl(); 6453 continue; 6454 } 6455 if (!FD->getType()->isDependentType() && 6456 !Context.getBaseElementType(FD->getType())->isPODType()) { 6457 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type) 6458 << FD->getDeclName() << FD->getType(); 6459 FD->setInvalidDecl(); 6460 EnclosingDecl->setInvalidDecl(); 6461 continue; 6462 } 6463 6464 // Okay, we have a legal flexible array member at the end of the struct. 6465 if (Record) 6466 Record->setHasFlexibleArrayMember(true); 6467 } else if (!FDTy->isDependentType() && 6468 RequireCompleteType(FD->getLocation(), FD->getType(), 6469 diag::err_field_incomplete)) { 6470 // Incomplete type 6471 FD->setInvalidDecl(); 6472 EnclosingDecl->setInvalidDecl(); 6473 continue; 6474 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 6475 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 6476 // If this is a member of a union, then entire union becomes "flexible". 6477 if (Record && Record->isUnion()) { 6478 Record->setHasFlexibleArrayMember(true); 6479 } else { 6480 // If this is a struct/class and this is not the last element, reject 6481 // it. Note that GCC supports variable sized arrays in the middle of 6482 // structures. 6483 if (i != NumFields-1) 6484 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 6485 << FD->getDeclName() << FD->getType(); 6486 else { 6487 // We support flexible arrays at the end of structs in 6488 // other structs as an extension. 6489 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 6490 << FD->getDeclName(); 6491 if (Record) 6492 Record->setHasFlexibleArrayMember(true); 6493 } 6494 } 6495 } 6496 if (Record && FDTTy->getDecl()->hasObjectMember()) 6497 Record->setHasObjectMember(true); 6498 } else if (FDTy->isObjCObjectType()) { 6499 /// A field cannot be an Objective-c object 6500 Diag(FD->getLocation(), diag::err_statically_allocated_object); 6501 FD->setInvalidDecl(); 6502 EnclosingDecl->setInvalidDecl(); 6503 continue; 6504 } else if (getLangOptions().ObjC1 && 6505 getLangOptions().getGCMode() != LangOptions::NonGC && 6506 Record && 6507 (FD->getType()->isObjCObjectPointerType() || 6508 FD->getType().isObjCGCStrong())) 6509 Record->setHasObjectMember(true); 6510 else if (Context.getAsArrayType(FD->getType())) { 6511 QualType BaseType = Context.getBaseElementType(FD->getType()); 6512 if (Record && BaseType->isRecordType() && 6513 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 6514 Record->setHasObjectMember(true); 6515 } 6516 // Keep track of the number of named members. 6517 if (FD->getIdentifier()) 6518 ++NumNamedMembers; 6519 } 6520 6521 // Okay, we successfully defined 'Record'. 6522 if (Record) { 6523 Record->completeDefinition(); 6524 } else { 6525 ObjCIvarDecl **ClsFields = 6526 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 6527 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 6528 ID->setLocEnd(RBrac); 6529 // Add ivar's to class's DeclContext. 6530 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 6531 ClsFields[i]->setLexicalDeclContext(ID); 6532 ID->addDecl(ClsFields[i]); 6533 } 6534 // Must enforce the rule that ivars in the base classes may not be 6535 // duplicates. 6536 if (ID->getSuperClass()) 6537 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 6538 } else if (ObjCImplementationDecl *IMPDecl = 6539 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 6540 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 6541 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 6542 // Ivar declared in @implementation never belongs to the implementation. 6543 // Only it is in implementation's lexical context. 6544 ClsFields[I]->setLexicalDeclContext(IMPDecl); 6545 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 6546 } else if (ObjCCategoryDecl *CDecl = 6547 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 6548 // case of ivars in class extension; all other cases have been 6549 // reported as errors elsewhere. 6550 // FIXME. Class extension does not have a LocEnd field. 6551 // CDecl->setLocEnd(RBrac); 6552 // Add ivar's to class extension's DeclContext. 6553 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 6554 ClsFields[i]->setLexicalDeclContext(CDecl); 6555 CDecl->addDecl(ClsFields[i]); 6556 } 6557 } 6558 } 6559 6560 if (Attr) 6561 ProcessDeclAttributeList(S, Record, Attr); 6562 6563 // If there's a #pragma GCC visibility in scope, and this isn't a subclass, 6564 // set the visibility of this record. 6565 if (Record && !Record->getDeclContext()->isRecord()) 6566 AddPushedVisibilityAttribute(Record); 6567} 6568 6569/// \brief Determine whether the given integral value is representable within 6570/// the given type T. 6571static bool isRepresentableIntegerValue(ASTContext &Context, 6572 llvm::APSInt &Value, 6573 QualType T) { 6574 assert(T->isIntegralType(Context) && "Integral type required!"); 6575 unsigned BitWidth = Context.getIntWidth(T); 6576 6577 if (Value.isUnsigned() || Value.isNonNegative()) 6578 return Value.getActiveBits() < BitWidth; 6579 6580 return Value.getMinSignedBits() <= BitWidth; 6581} 6582 6583// \brief Given an integral type, return the next larger integral type 6584// (or a NULL type of no such type exists). 6585static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 6586 // FIXME: Int128/UInt128 support, which also needs to be introduced into 6587 // enum checking below. 6588 assert(T->isIntegralType(Context) && "Integral type required!"); 6589 const unsigned NumTypes = 4; 6590 QualType SignedIntegralTypes[NumTypes] = { 6591 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 6592 }; 6593 QualType UnsignedIntegralTypes[NumTypes] = { 6594 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 6595 Context.UnsignedLongLongTy 6596 }; 6597 6598 unsigned BitWidth = Context.getTypeSize(T); 6599 QualType *Types = T->isSignedIntegerType()? SignedIntegralTypes 6600 : UnsignedIntegralTypes; 6601 for (unsigned I = 0; I != NumTypes; ++I) 6602 if (Context.getTypeSize(Types[I]) > BitWidth) 6603 return Types[I]; 6604 6605 return QualType(); 6606} 6607 6608EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 6609 EnumConstantDecl *LastEnumConst, 6610 SourceLocation IdLoc, 6611 IdentifierInfo *Id, 6612 ExprArg val) { 6613 Expr *Val = (Expr *)val.get(); 6614 6615 unsigned IntWidth = Context.Target.getIntWidth(); 6616 llvm::APSInt EnumVal(IntWidth); 6617 QualType EltTy; 6618 if (Val) { 6619 if (Enum->isDependentType() || Val->isTypeDependent()) 6620 EltTy = Context.DependentTy; 6621 else { 6622 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 6623 SourceLocation ExpLoc; 6624 if (!Val->isValueDependent() && 6625 VerifyIntegerConstantExpression(Val, &EnumVal)) { 6626 Val = 0; 6627 } else { 6628 if (!getLangOptions().CPlusPlus) { 6629 // C99 6.7.2.2p2: 6630 // The expression that defines the value of an enumeration constant 6631 // shall be an integer constant expression that has a value 6632 // representable as an int. 6633 6634 // Complain if the value is not representable in an int. 6635 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 6636 Diag(IdLoc, diag::ext_enum_value_not_int) 6637 << EnumVal.toString(10) << Val->getSourceRange() 6638 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 6639 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 6640 // Force the type of the expression to 'int'. 6641 ImpCastExprToType(Val, Context.IntTy, CastExpr::CK_IntegralCast); 6642 6643 if (Val != val.get()) { 6644 val.release(); 6645 val = Val; 6646 } 6647 } 6648 } 6649 6650 // C++0x [dcl.enum]p5: 6651 // If the underlying type is not fixed, the type of each enumerator 6652 // is the type of its initializing value: 6653 // - If an initializer is specified for an enumerator, the 6654 // initializing value has the same type as the expression. 6655 EltTy = Val->getType(); 6656 } 6657 } 6658 } 6659 6660 if (!Val) { 6661 if (Enum->isDependentType()) 6662 EltTy = Context.DependentTy; 6663 else if (!LastEnumConst) { 6664 // C++0x [dcl.enum]p5: 6665 // If the underlying type is not fixed, the type of each enumerator 6666 // is the type of its initializing value: 6667 // - If no initializer is specified for the first enumerator, the 6668 // initializing value has an unspecified integral type. 6669 // 6670 // GCC uses 'int' for its unspecified integral type, as does 6671 // C99 6.7.2.2p3. 6672 EltTy = Context.IntTy; 6673 } else { 6674 // Assign the last value + 1. 6675 EnumVal = LastEnumConst->getInitVal(); 6676 ++EnumVal; 6677 EltTy = LastEnumConst->getType(); 6678 6679 // Check for overflow on increment. 6680 if (EnumVal < LastEnumConst->getInitVal()) { 6681 // C++0x [dcl.enum]p5: 6682 // If the underlying type is not fixed, the type of each enumerator 6683 // is the type of its initializing value: 6684 // 6685 // - Otherwise the type of the initializing value is the same as 6686 // the type of the initializing value of the preceding enumerator 6687 // unless the incremented value is not representable in that type, 6688 // in which case the type is an unspecified integral type 6689 // sufficient to contain the incremented value. If no such type 6690 // exists, the program is ill-formed. 6691 QualType T = getNextLargerIntegralType(Context, EltTy); 6692 if (T.isNull()) { 6693 // There is no integral type larger enough to represent this 6694 // value. Complain, then allow the value to wrap around. 6695 EnumVal = LastEnumConst->getInitVal(); 6696 EnumVal.zext(EnumVal.getBitWidth() * 2); 6697 Diag(IdLoc, diag::warn_enumerator_too_large) 6698 << EnumVal.toString(10); 6699 } else { 6700 EltTy = T; 6701 } 6702 6703 // Retrieve the last enumerator's value, extent that type to the 6704 // type that is supposed to be large enough to represent the incremented 6705 // value, then increment. 6706 EnumVal = LastEnumConst->getInitVal(); 6707 EnumVal.setIsSigned(EltTy->isSignedIntegerType()); 6708 EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 6709 ++EnumVal; 6710 6711 // If we're not in C++, diagnose the overflow of enumerator values, 6712 // which in C99 means that the enumerator value is not representable in 6713 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 6714 // permits enumerator values that are representable in some larger 6715 // integral type. 6716 if (!getLangOptions().CPlusPlus && !T.isNull()) 6717 Diag(IdLoc, diag::warn_enum_value_overflow); 6718 } else if (!getLangOptions().CPlusPlus && 6719 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 6720 // Enforce C99 6.7.2.2p2 even when we compute the next value. 6721 Diag(IdLoc, diag::ext_enum_value_not_int) 6722 << EnumVal.toString(10) << 1; 6723 } 6724 } 6725 } 6726 6727 if (!EltTy->isDependentType()) { 6728 // Make the enumerator value match the signedness and size of the 6729 // enumerator's type. 6730 EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 6731 EnumVal.setIsSigned(EltTy->isSignedIntegerType()); 6732 } 6733 6734 val.release(); 6735 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 6736 Val, EnumVal); 6737} 6738 6739 6740Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl, 6741 DeclPtrTy lastEnumConst, 6742 SourceLocation IdLoc, 6743 IdentifierInfo *Id, 6744 SourceLocation EqualLoc, ExprTy *val) { 6745 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>()); 6746 EnumConstantDecl *LastEnumConst = 6747 cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>()); 6748 Expr *Val = static_cast<Expr*>(val); 6749 6750 // The scope passed in may not be a decl scope. Zip up the scope tree until 6751 // we find one that is. 6752 S = getNonFieldDeclScope(S); 6753 6754 // Verify that there isn't already something declared with this name in this 6755 // scope. 6756 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 6757 ForRedeclaration); 6758 if (PrevDecl && PrevDecl->isTemplateParameter()) { 6759 // Maybe we will complain about the shadowed template parameter. 6760 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 6761 // Just pretend that we didn't see the previous declaration. 6762 PrevDecl = 0; 6763 } 6764 6765 if (PrevDecl) { 6766 // When in C++, we may get a TagDecl with the same name; in this case the 6767 // enum constant will 'hide' the tag. 6768 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 6769 "Received TagDecl when not in C++!"); 6770 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 6771 if (isa<EnumConstantDecl>(PrevDecl)) 6772 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 6773 else 6774 Diag(IdLoc, diag::err_redefinition) << Id; 6775 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6776 return DeclPtrTy(); 6777 } 6778 } 6779 6780 EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst, 6781 IdLoc, Id, Owned(Val)); 6782 6783 // Register this decl in the current scope stack. 6784 if (New) { 6785 New->setAccess(TheEnumDecl->getAccess()); 6786 PushOnScopeChains(New, S); 6787 } 6788 6789 return DeclPtrTy::make(New); 6790} 6791 6792void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 6793 SourceLocation RBraceLoc, DeclPtrTy EnumDeclX, 6794 DeclPtrTy *Elements, unsigned NumElements, 6795 Scope *S, AttributeList *Attr) { 6796 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>()); 6797 QualType EnumType = Context.getTypeDeclType(Enum); 6798 6799 if (Attr) 6800 ProcessDeclAttributeList(S, Enum, Attr); 6801 6802 if (Enum->isDependentType()) { 6803 for (unsigned i = 0; i != NumElements; ++i) { 6804 EnumConstantDecl *ECD = 6805 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>()); 6806 if (!ECD) continue; 6807 6808 ECD->setType(EnumType); 6809 } 6810 6811 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 6812 return; 6813 } 6814 6815 // TODO: If the result value doesn't fit in an int, it must be a long or long 6816 // long value. ISO C does not support this, but GCC does as an extension, 6817 // emit a warning. 6818 unsigned IntWidth = Context.Target.getIntWidth(); 6819 unsigned CharWidth = Context.Target.getCharWidth(); 6820 unsigned ShortWidth = Context.Target.getShortWidth(); 6821 6822 // Verify that all the values are okay, compute the size of the values, and 6823 // reverse the list. 6824 unsigned NumNegativeBits = 0; 6825 unsigned NumPositiveBits = 0; 6826 6827 // Keep track of whether all elements have type int. 6828 bool AllElementsInt = true; 6829 6830 for (unsigned i = 0; i != NumElements; ++i) { 6831 EnumConstantDecl *ECD = 6832 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>()); 6833 if (!ECD) continue; // Already issued a diagnostic. 6834 6835 const llvm::APSInt &InitVal = ECD->getInitVal(); 6836 6837 // Keep track of the size of positive and negative values. 6838 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 6839 NumPositiveBits = std::max(NumPositiveBits, 6840 (unsigned)InitVal.getActiveBits()); 6841 else 6842 NumNegativeBits = std::max(NumNegativeBits, 6843 (unsigned)InitVal.getMinSignedBits()); 6844 6845 // Keep track of whether every enum element has type int (very commmon). 6846 if (AllElementsInt) 6847 AllElementsInt = ECD->getType() == Context.IntTy; 6848 } 6849 6850 // Figure out the type that should be used for this enum. 6851 // FIXME: Support -fshort-enums. 6852 QualType BestType; 6853 unsigned BestWidth; 6854 6855 // C++0x N3000 [conv.prom]p3: 6856 // An rvalue of an unscoped enumeration type whose underlying 6857 // type is not fixed can be converted to an rvalue of the first 6858 // of the following types that can represent all the values of 6859 // the enumeration: int, unsigned int, long int, unsigned long 6860 // int, long long int, or unsigned long long int. 6861 // C99 6.4.4.3p2: 6862 // An identifier declared as an enumeration constant has type int. 6863 // The C99 rule is modified by a gcc extension 6864 QualType BestPromotionType; 6865 6866 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 6867 6868 if (NumNegativeBits) { 6869 // If there is a negative value, figure out the smallest integer type (of 6870 // int/long/longlong) that fits. 6871 // If it's packed, check also if it fits a char or a short. 6872 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 6873 BestType = Context.SignedCharTy; 6874 BestWidth = CharWidth; 6875 } else if (Packed && NumNegativeBits <= ShortWidth && 6876 NumPositiveBits < ShortWidth) { 6877 BestType = Context.ShortTy; 6878 BestWidth = ShortWidth; 6879 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 6880 BestType = Context.IntTy; 6881 BestWidth = IntWidth; 6882 } else { 6883 BestWidth = Context.Target.getLongWidth(); 6884 6885 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 6886 BestType = Context.LongTy; 6887 } else { 6888 BestWidth = Context.Target.getLongLongWidth(); 6889 6890 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 6891 Diag(Enum->getLocation(), diag::warn_enum_too_large); 6892 BestType = Context.LongLongTy; 6893 } 6894 } 6895 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 6896 } else { 6897 // If there is no negative value, figure out the smallest type that fits 6898 // all of the enumerator values. 6899 // If it's packed, check also if it fits a char or a short. 6900 if (Packed && NumPositiveBits <= CharWidth) { 6901 BestType = Context.UnsignedCharTy; 6902 BestPromotionType = Context.IntTy; 6903 BestWidth = CharWidth; 6904 } else if (Packed && NumPositiveBits <= ShortWidth) { 6905 BestType = Context.UnsignedShortTy; 6906 BestPromotionType = Context.IntTy; 6907 BestWidth = ShortWidth; 6908 } else if (NumPositiveBits <= IntWidth) { 6909 BestType = Context.UnsignedIntTy; 6910 BestWidth = IntWidth; 6911 BestPromotionType 6912 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 6913 ? Context.UnsignedIntTy : Context.IntTy; 6914 } else if (NumPositiveBits <= 6915 (BestWidth = Context.Target.getLongWidth())) { 6916 BestType = Context.UnsignedLongTy; 6917 BestPromotionType 6918 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 6919 ? Context.UnsignedLongTy : Context.LongTy; 6920 } else { 6921 BestWidth = Context.Target.getLongLongWidth(); 6922 assert(NumPositiveBits <= BestWidth && 6923 "How could an initializer get larger than ULL?"); 6924 BestType = Context.UnsignedLongLongTy; 6925 BestPromotionType 6926 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 6927 ? Context.UnsignedLongLongTy : Context.LongLongTy; 6928 } 6929 } 6930 6931 // Loop over all of the enumerator constants, changing their types to match 6932 // the type of the enum if needed. 6933 for (unsigned i = 0; i != NumElements; ++i) { 6934 EnumConstantDecl *ECD = 6935 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>()); 6936 if (!ECD) continue; // Already issued a diagnostic. 6937 6938 // Standard C says the enumerators have int type, but we allow, as an 6939 // extension, the enumerators to be larger than int size. If each 6940 // enumerator value fits in an int, type it as an int, otherwise type it the 6941 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 6942 // that X has type 'int', not 'unsigned'. 6943 6944 // Determine whether the value fits into an int. 6945 llvm::APSInt InitVal = ECD->getInitVal(); 6946 6947 // If it fits into an integer type, force it. Otherwise force it to match 6948 // the enum decl type. 6949 QualType NewTy; 6950 unsigned NewWidth; 6951 bool NewSign; 6952 if (!getLangOptions().CPlusPlus && 6953 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 6954 NewTy = Context.IntTy; 6955 NewWidth = IntWidth; 6956 NewSign = true; 6957 } else if (ECD->getType() == BestType) { 6958 // Already the right type! 6959 if (getLangOptions().CPlusPlus) 6960 // C++ [dcl.enum]p4: Following the closing brace of an 6961 // enum-specifier, each enumerator has the type of its 6962 // enumeration. 6963 ECD->setType(EnumType); 6964 continue; 6965 } else { 6966 NewTy = BestType; 6967 NewWidth = BestWidth; 6968 NewSign = BestType->isSignedIntegerType(); 6969 } 6970 6971 // Adjust the APSInt value. 6972 InitVal.extOrTrunc(NewWidth); 6973 InitVal.setIsSigned(NewSign); 6974 ECD->setInitVal(InitVal); 6975 6976 // Adjust the Expr initializer and type. 6977 if (ECD->getInitExpr()) 6978 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 6979 CastExpr::CK_IntegralCast, 6980 ECD->getInitExpr(), 6981 /*base paths*/ 0, 6982 ImplicitCastExpr::RValue)); 6983 if (getLangOptions().CPlusPlus) 6984 // C++ [dcl.enum]p4: Following the closing brace of an 6985 // enum-specifier, each enumerator has the type of its 6986 // enumeration. 6987 ECD->setType(EnumType); 6988 else 6989 ECD->setType(NewTy); 6990 } 6991 6992 Enum->completeDefinition(BestType, BestPromotionType, 6993 NumPositiveBits, NumNegativeBits); 6994} 6995 6996Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc, 6997 ExprArg expr) { 6998 StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>()); 6999 7000 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 7001 Loc, AsmString); 7002 CurContext->addDecl(New); 7003 return DeclPtrTy::make(New); 7004} 7005 7006void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 7007 SourceLocation PragmaLoc, 7008 SourceLocation NameLoc) { 7009 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 7010 7011 if (PrevDecl) { 7012 PrevDecl->addAttr(::new (Context) WeakAttr()); 7013 } else { 7014 (void)WeakUndeclaredIdentifiers.insert( 7015 std::pair<IdentifierInfo*,WeakInfo> 7016 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 7017 } 7018} 7019 7020void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 7021 IdentifierInfo* AliasName, 7022 SourceLocation PragmaLoc, 7023 SourceLocation NameLoc, 7024 SourceLocation AliasNameLoc) { 7025 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 7026 LookupOrdinaryName); 7027 WeakInfo W = WeakInfo(Name, NameLoc); 7028 7029 if (PrevDecl) { 7030 if (!PrevDecl->hasAttr<AliasAttr>()) 7031 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 7032 DeclApplyPragmaWeak(TUScope, ND, W); 7033 } else { 7034 (void)WeakUndeclaredIdentifiers.insert( 7035 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 7036 } 7037} 7038