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