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