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