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