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