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