SemaDecl.cpp revision a93c934af4fbf97cbe8e649d82e68ccacfe57c95
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) && cast<FunctionDecl>(D)->isOutOfLine()) || 383 (isa<VarDecl>(D) && cast<VarDecl>(D)->isOutOfLine())) 384 return; 385 386 // If this replaces anything in the current scope, 387 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 388 IEnd = IdResolver.end(); 389 for (; I != IEnd; ++I) { 390 if (S->isDeclScope(DeclPtrTy::make(*I)) && D->declarationReplaces(*I)) { 391 S->RemoveDecl(DeclPtrTy::make(*I)); 392 IdResolver.RemoveDecl(*I); 393 394 // Should only need to replace one decl. 395 break; 396 } 397 } 398 399 S->AddDecl(DeclPtrTy::make(D)); 400 IdResolver.AddDecl(D); 401} 402 403bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) { 404 return IdResolver.isDeclInScope(D, Ctx, Context, S); 405} 406 407static bool isOutOfScopePreviousDeclaration(NamedDecl *, 408 DeclContext*, 409 ASTContext&); 410 411/// Filters out lookup results that don't fall within the given scope 412/// as determined by isDeclInScope. 413static void FilterLookupForScope(Sema &SemaRef, LookupResult &R, 414 DeclContext *Ctx, Scope *S, 415 bool ConsiderLinkage) { 416 LookupResult::Filter F = R.makeFilter(); 417 while (F.hasNext()) { 418 NamedDecl *D = F.next(); 419 420 if (SemaRef.isDeclInScope(D, Ctx, S)) 421 continue; 422 423 if (ConsiderLinkage && 424 isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context)) 425 continue; 426 427 F.erase(); 428 } 429 430 F.done(); 431} 432 433static bool isUsingDecl(NamedDecl *D) { 434 return isa<UsingShadowDecl>(D) || 435 isa<UnresolvedUsingTypenameDecl>(D) || 436 isa<UnresolvedUsingValueDecl>(D); 437} 438 439/// Removes using shadow declarations from the lookup results. 440static void RemoveUsingDecls(LookupResult &R) { 441 LookupResult::Filter F = R.makeFilter(); 442 while (F.hasNext()) 443 if (isUsingDecl(F.next())) 444 F.erase(); 445 446 F.done(); 447} 448 449static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 450 if (D->isUsed() || D->hasAttr<UnusedAttr>()) 451 return false; 452 453 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 454 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) { 455 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 456 if (!RD->hasTrivialConstructor()) 457 return false; 458 if (!RD->hasTrivialDestructor()) 459 return false; 460 } 461 } 462 } 463 464 return (isa<VarDecl>(D) && !isa<ParmVarDecl>(D) && 465 !isa<ImplicitParamDecl>(D) && 466 D->getDeclContext()->isFunctionOrMethod()); 467} 468 469void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 470 if (S->decl_empty()) return; 471 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 472 "Scope shouldn't contain decls!"); 473 474 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 475 I != E; ++I) { 476 Decl *TmpD = (*I).getAs<Decl>(); 477 assert(TmpD && "This decl didn't get pushed??"); 478 479 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 480 NamedDecl *D = cast<NamedDecl>(TmpD); 481 482 if (!D->getDeclName()) continue; 483 484 // Diagnose unused variables in this scope. 485 if (ShouldDiagnoseUnusedDecl(D)) 486 Diag(D->getLocation(), diag::warn_unused_variable) << D->getDeclName(); 487 488 // Remove this name from our lexical scope. 489 IdResolver.RemoveDecl(D); 490 } 491} 492 493/// getObjCInterfaceDecl - Look up a for a class declaration in the scope. 494/// return 0 if one not found. 495ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) { 496 // The third "scope" argument is 0 since we aren't enabling lazy built-in 497 // creation from this context. 498 NamedDecl *IDecl = LookupSingleName(TUScope, Id, LookupOrdinaryName); 499 500 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 501} 502 503/// getNonFieldDeclScope - Retrieves the innermost scope, starting 504/// from S, where a non-field would be declared. This routine copes 505/// with the difference between C and C++ scoping rules in structs and 506/// unions. For example, the following code is well-formed in C but 507/// ill-formed in C++: 508/// @code 509/// struct S6 { 510/// enum { BAR } e; 511/// }; 512/// 513/// void test_S6() { 514/// struct S6 a; 515/// a.e = BAR; 516/// } 517/// @endcode 518/// For the declaration of BAR, this routine will return a different 519/// scope. The scope S will be the scope of the unnamed enumeration 520/// within S6. In C++, this routine will return the scope associated 521/// with S6, because the enumeration's scope is a transparent 522/// context but structures can contain non-field names. In C, this 523/// routine will return the translation unit scope, since the 524/// enumeration's scope is a transparent context and structures cannot 525/// contain non-field names. 526Scope *Sema::getNonFieldDeclScope(Scope *S) { 527 while (((S->getFlags() & Scope::DeclScope) == 0) || 528 (S->getEntity() && 529 ((DeclContext *)S->getEntity())->isTransparentContext()) || 530 (S->isClassScope() && !getLangOptions().CPlusPlus)) 531 S = S->getParent(); 532 return S; 533} 534 535void Sema::InitBuiltinVaListType() { 536 if (!Context.getBuiltinVaListType().isNull()) 537 return; 538 539 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list"); 540 NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, LookupOrdinaryName); 541 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl); 542 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef)); 543} 544 545/// LazilyCreateBuiltin - The specified Builtin-ID was first used at 546/// file scope. lazily create a decl for it. ForRedeclaration is true 547/// if we're creating this built-in in anticipation of redeclaring the 548/// built-in. 549NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 550 Scope *S, bool ForRedeclaration, 551 SourceLocation Loc) { 552 Builtin::ID BID = (Builtin::ID)bid; 553 554 if (Context.BuiltinInfo.hasVAListUse(BID)) 555 InitBuiltinVaListType(); 556 557 ASTContext::GetBuiltinTypeError Error; 558 QualType R = Context.GetBuiltinType(BID, Error); 559 switch (Error) { 560 case ASTContext::GE_None: 561 // Okay 562 break; 563 564 case ASTContext::GE_Missing_stdio: 565 if (ForRedeclaration) 566 Diag(Loc, diag::err_implicit_decl_requires_stdio) 567 << Context.BuiltinInfo.GetName(BID); 568 return 0; 569 570 case ASTContext::GE_Missing_setjmp: 571 if (ForRedeclaration) 572 Diag(Loc, diag::err_implicit_decl_requires_setjmp) 573 << Context.BuiltinInfo.GetName(BID); 574 return 0; 575 } 576 577 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 578 Diag(Loc, diag::ext_implicit_lib_function_decl) 579 << Context.BuiltinInfo.GetName(BID) 580 << R; 581 if (Context.BuiltinInfo.getHeaderName(BID) && 582 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl) 583 != Diagnostic::Ignored) 584 Diag(Loc, diag::note_please_include_header) 585 << Context.BuiltinInfo.getHeaderName(BID) 586 << Context.BuiltinInfo.GetName(BID); 587 } 588 589 FunctionDecl *New = FunctionDecl::Create(Context, 590 Context.getTranslationUnitDecl(), 591 Loc, II, R, /*TInfo=*/0, 592 FunctionDecl::Extern, false, 593 /*hasPrototype=*/true); 594 New->setImplicit(); 595 596 // Create Decl objects for each parameter, adding them to the 597 // FunctionDecl. 598 if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 599 llvm::SmallVector<ParmVarDecl*, 16> Params; 600 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) 601 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0, 602 FT->getArgType(i), /*TInfo=*/0, 603 VarDecl::None, 0)); 604 New->setParams(Context, Params.data(), Params.size()); 605 } 606 607 AddKnownFunctionAttributes(New); 608 609 // TUScope is the translation-unit scope to insert this function into. 610 // FIXME: This is hideous. We need to teach PushOnScopeChains to 611 // relate Scopes to DeclContexts, and probably eliminate CurContext 612 // entirely, but we're not there yet. 613 DeclContext *SavedContext = CurContext; 614 CurContext = Context.getTranslationUnitDecl(); 615 PushOnScopeChains(New, TUScope); 616 CurContext = SavedContext; 617 return New; 618} 619 620/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the 621/// same name and scope as a previous declaration 'Old'. Figure out 622/// how to resolve this situation, merging decls or emitting 623/// diagnostics as appropriate. If there was an error, set New to be invalid. 624/// 625void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) { 626 // If the new decl is known invalid already, don't bother doing any 627 // merging checks. 628 if (New->isInvalidDecl()) return; 629 630 // Allow multiple definitions for ObjC built-in typedefs. 631 // FIXME: Verify the underlying types are equivalent! 632 if (getLangOptions().ObjC1) { 633 const IdentifierInfo *TypeID = New->getIdentifier(); 634 switch (TypeID->getLength()) { 635 default: break; 636 case 2: 637 if (!TypeID->isStr("id")) 638 break; 639 Context.ObjCIdRedefinitionType = New->getUnderlyingType(); 640 // Install the built-in type for 'id', ignoring the current definition. 641 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 642 return; 643 case 5: 644 if (!TypeID->isStr("Class")) 645 break; 646 Context.ObjCClassRedefinitionType = New->getUnderlyingType(); 647 // Install the built-in type for 'Class', ignoring the current definition. 648 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 649 return; 650 case 3: 651 if (!TypeID->isStr("SEL")) 652 break; 653 Context.ObjCSelRedefinitionType = New->getUnderlyingType(); 654 // Install the built-in type for 'SEL', ignoring the current definition. 655 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 656 return; 657 case 8: 658 if (!TypeID->isStr("Protocol")) 659 break; 660 Context.setObjCProtoType(New->getUnderlyingType()); 661 return; 662 } 663 // Fall through - the typedef name was not a builtin type. 664 } 665 666 // Verify the old decl was also a type. 667 TypeDecl *Old = 0; 668 if (!OldDecls.isSingleResult() || 669 !(Old = dyn_cast<TypeDecl>(OldDecls.getFoundDecl()))) { 670 Diag(New->getLocation(), diag::err_redefinition_different_kind) 671 << New->getDeclName(); 672 673 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 674 if (OldD->getLocation().isValid()) 675 Diag(OldD->getLocation(), diag::note_previous_definition); 676 677 return New->setInvalidDecl(); 678 } 679 680 // If the old declaration is invalid, just give up here. 681 if (Old->isInvalidDecl()) 682 return New->setInvalidDecl(); 683 684 // Determine the "old" type we'll use for checking and diagnostics. 685 QualType OldType; 686 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old)) 687 OldType = OldTypedef->getUnderlyingType(); 688 else 689 OldType = Context.getTypeDeclType(Old); 690 691 // If the typedef types are not identical, reject them in all languages and 692 // with any extensions enabled. 693 694 if (OldType != New->getUnderlyingType() && 695 Context.getCanonicalType(OldType) != 696 Context.getCanonicalType(New->getUnderlyingType())) { 697 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 698 << New->getUnderlyingType() << OldType; 699 if (Old->getLocation().isValid()) 700 Diag(Old->getLocation(), diag::note_previous_definition); 701 return New->setInvalidDecl(); 702 } 703 704 if (getLangOptions().Microsoft) 705 return; 706 707 // C++ [dcl.typedef]p2: 708 // In a given non-class scope, a typedef specifier can be used to 709 // redefine the name of any type declared in that scope to refer 710 // to the type to which it already refers. 711 if (getLangOptions().CPlusPlus) { 712 if (!isa<CXXRecordDecl>(CurContext)) 713 return; 714 Diag(New->getLocation(), diag::err_redefinition) 715 << New->getDeclName(); 716 Diag(Old->getLocation(), diag::note_previous_definition); 717 return New->setInvalidDecl(); 718 } 719 720 // If we have a redefinition of a typedef in C, emit a warning. This warning 721 // is normally mapped to an error, but can be controlled with 722 // -Wtypedef-redefinition. If either the original or the redefinition is 723 // in a system header, don't emit this for compatibility with GCC. 724 if (PP.getDiagnostics().getSuppressSystemWarnings() && 725 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 726 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 727 return; 728 729 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 730 << New->getDeclName(); 731 Diag(Old->getLocation(), diag::note_previous_definition); 732 return; 733} 734 735/// DeclhasAttr - returns true if decl Declaration already has the target 736/// attribute. 737static bool 738DeclHasAttr(const Decl *decl, const Attr *target) { 739 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext()) 740 if (attr->getKind() == target->getKind()) 741 return true; 742 743 return false; 744} 745 746/// MergeAttributes - append attributes from the Old decl to the New one. 747static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) { 748 for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) { 749 if (!DeclHasAttr(New, attr) && attr->isMerged()) { 750 Attr *NewAttr = attr->clone(C); 751 NewAttr->setInherited(true); 752 New->addAttr(NewAttr); 753 } 754 } 755} 756 757/// Used in MergeFunctionDecl to keep track of function parameters in 758/// C. 759struct GNUCompatibleParamWarning { 760 ParmVarDecl *OldParm; 761 ParmVarDecl *NewParm; 762 QualType PromotedType; 763}; 764 765 766/// getSpecialMember - get the special member enum for a method. 767static Sema::CXXSpecialMember getSpecialMember(ASTContext &Ctx, 768 const CXXMethodDecl *MD) { 769 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 770 if (Ctor->isDefaultConstructor()) 771 return Sema::CXXDefaultConstructor; 772 if (Ctor->isCopyConstructor(Ctx)) 773 return Sema::CXXCopyConstructor; 774 } 775 776 if (isa<CXXDestructorDecl>(MD)) 777 return Sema::CXXDestructor; 778 779 assert(MD->isCopyAssignment() && "Must have copy assignment operator"); 780 return Sema::CXXCopyAssignment; 781} 782 783/// MergeFunctionDecl - We just parsed a function 'New' from 784/// declarator D which has the same name and scope as a previous 785/// declaration 'Old'. Figure out how to resolve this situation, 786/// merging decls or emitting diagnostics as appropriate. 787/// 788/// In C++, New and Old must be declarations that are not 789/// overloaded. Use IsOverload to determine whether New and Old are 790/// overloaded, and to select the Old declaration that New should be 791/// merged with. 792/// 793/// Returns true if there was an error, false otherwise. 794bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) { 795 // Verify the old decl was also a function. 796 FunctionDecl *Old = 0; 797 if (FunctionTemplateDecl *OldFunctionTemplate 798 = dyn_cast<FunctionTemplateDecl>(OldD)) 799 Old = OldFunctionTemplate->getTemplatedDecl(); 800 else 801 Old = dyn_cast<FunctionDecl>(OldD); 802 if (!Old) { 803 Diag(New->getLocation(), diag::err_redefinition_different_kind) 804 << New->getDeclName(); 805 Diag(OldD->getLocation(), diag::note_previous_definition); 806 return true; 807 } 808 809 // Determine whether the previous declaration was a definition, 810 // implicit declaration, or a declaration. 811 diag::kind PrevDiag; 812 if (Old->isThisDeclarationADefinition()) 813 PrevDiag = diag::note_previous_definition; 814 else if (Old->isImplicit()) 815 PrevDiag = diag::note_previous_implicit_declaration; 816 else 817 PrevDiag = diag::note_previous_declaration; 818 819 QualType OldQType = Context.getCanonicalType(Old->getType()); 820 QualType NewQType = Context.getCanonicalType(New->getType()); 821 822 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 823 New->getStorageClass() == FunctionDecl::Static && 824 Old->getStorageClass() != FunctionDecl::Static) { 825 Diag(New->getLocation(), diag::err_static_non_static) 826 << New; 827 Diag(Old->getLocation(), PrevDiag); 828 return true; 829 } 830 831 if (getLangOptions().CPlusPlus) { 832 // (C++98 13.1p2): 833 // Certain function declarations cannot be overloaded: 834 // -- Function declarations that differ only in the return type 835 // cannot be overloaded. 836 QualType OldReturnType 837 = cast<FunctionType>(OldQType.getTypePtr())->getResultType(); 838 QualType NewReturnType 839 = cast<FunctionType>(NewQType.getTypePtr())->getResultType(); 840 if (OldReturnType != NewReturnType) { 841 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 842 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 843 return true; 844 } 845 846 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 847 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 848 if (OldMethod && NewMethod) { 849 if (!NewMethod->getFriendObjectKind() && 850 NewMethod->getLexicalDeclContext()->isRecord()) { 851 // -- Member function declarations with the same name and the 852 // same parameter types cannot be overloaded if any of them 853 // is a static member function declaration. 854 if (OldMethod->isStatic() || NewMethod->isStatic()) { 855 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 856 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 857 return true; 858 } 859 860 // C++ [class.mem]p1: 861 // [...] A member shall not be declared twice in the 862 // member-specification, except that a nested class or member 863 // class template can be declared and then later defined. 864 unsigned NewDiag; 865 if (isa<CXXConstructorDecl>(OldMethod)) 866 NewDiag = diag::err_constructor_redeclared; 867 else if (isa<CXXDestructorDecl>(NewMethod)) 868 NewDiag = diag::err_destructor_redeclared; 869 else if (isa<CXXConversionDecl>(NewMethod)) 870 NewDiag = diag::err_conv_function_redeclared; 871 else 872 NewDiag = diag::err_member_redeclared; 873 874 Diag(New->getLocation(), NewDiag); 875 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 876 } else { 877 if (OldMethod->isImplicit()) { 878 Diag(NewMethod->getLocation(), 879 diag::err_definition_of_implicitly_declared_member) 880 << New << getSpecialMember(Context, OldMethod); 881 882 Diag(OldMethod->getLocation(), 883 diag::note_previous_implicit_declaration); 884 return true; 885 } 886 } 887 } 888 889 // (C++98 8.3.5p3): 890 // All declarations for a function shall agree exactly in both the 891 // return type and the parameter-type-list. 892 if (OldQType == NewQType) 893 return MergeCompatibleFunctionDecls(New, Old); 894 895 // Fall through for conflicting redeclarations and redefinitions. 896 } 897 898 // C: Function types need to be compatible, not identical. This handles 899 // duplicate function decls like "void f(int); void f(enum X);" properly. 900 if (!getLangOptions().CPlusPlus && 901 Context.typesAreCompatible(OldQType, NewQType)) { 902 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 903 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 904 const FunctionProtoType *OldProto = 0; 905 if (isa<FunctionNoProtoType>(NewFuncType) && 906 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 907 // The old declaration provided a function prototype, but the 908 // new declaration does not. Merge in the prototype. 909 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 910 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 911 OldProto->arg_type_end()); 912 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 913 ParamTypes.data(), ParamTypes.size(), 914 OldProto->isVariadic(), 915 OldProto->getTypeQuals()); 916 New->setType(NewQType); 917 New->setHasInheritedPrototype(); 918 919 // Synthesize a parameter for each argument type. 920 llvm::SmallVector<ParmVarDecl*, 16> Params; 921 for (FunctionProtoType::arg_type_iterator 922 ParamType = OldProto->arg_type_begin(), 923 ParamEnd = OldProto->arg_type_end(); 924 ParamType != ParamEnd; ++ParamType) { 925 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 926 SourceLocation(), 0, 927 *ParamType, /*TInfo=*/0, 928 VarDecl::None, 0); 929 Param->setImplicit(); 930 Params.push_back(Param); 931 } 932 933 New->setParams(Context, Params.data(), Params.size()); 934 } 935 936 return MergeCompatibleFunctionDecls(New, Old); 937 } 938 939 // GNU C permits a K&R definition to follow a prototype declaration 940 // if the declared types of the parameters in the K&R definition 941 // match the types in the prototype declaration, even when the 942 // promoted types of the parameters from the K&R definition differ 943 // from the types in the prototype. GCC then keeps the types from 944 // the prototype. 945 // 946 // If a variadic prototype is followed by a non-variadic K&R definition, 947 // the K&R definition becomes variadic. This is sort of an edge case, but 948 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 949 // C99 6.9.1p8. 950 if (!getLangOptions().CPlusPlus && 951 Old->hasPrototype() && !New->hasPrototype() && 952 New->getType()->getAs<FunctionProtoType>() && 953 Old->getNumParams() == New->getNumParams()) { 954 llvm::SmallVector<QualType, 16> ArgTypes; 955 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings; 956 const FunctionProtoType *OldProto 957 = Old->getType()->getAs<FunctionProtoType>(); 958 const FunctionProtoType *NewProto 959 = New->getType()->getAs<FunctionProtoType>(); 960 961 // Determine whether this is the GNU C extension. 962 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 963 NewProto->getResultType()); 964 bool LooseCompatible = !MergedReturn.isNull(); 965 for (unsigned Idx = 0, End = Old->getNumParams(); 966 LooseCompatible && Idx != End; ++Idx) { 967 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 968 ParmVarDecl *NewParm = New->getParamDecl(Idx); 969 if (Context.typesAreCompatible(OldParm->getType(), 970 NewProto->getArgType(Idx))) { 971 ArgTypes.push_back(NewParm->getType()); 972 } else if (Context.typesAreCompatible(OldParm->getType(), 973 NewParm->getType())) { 974 GNUCompatibleParamWarning Warn 975 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 976 Warnings.push_back(Warn); 977 ArgTypes.push_back(NewParm->getType()); 978 } else 979 LooseCompatible = false; 980 } 981 982 if (LooseCompatible) { 983 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 984 Diag(Warnings[Warn].NewParm->getLocation(), 985 diag::ext_param_promoted_not_compatible_with_prototype) 986 << Warnings[Warn].PromotedType 987 << Warnings[Warn].OldParm->getType(); 988 Diag(Warnings[Warn].OldParm->getLocation(), 989 diag::note_previous_declaration); 990 } 991 992 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0], 993 ArgTypes.size(), 994 OldProto->isVariadic(), 0)); 995 return MergeCompatibleFunctionDecls(New, Old); 996 } 997 998 // Fall through to diagnose conflicting types. 999 } 1000 1001 // A function that has already been declared has been redeclared or defined 1002 // with a different type- show appropriate diagnostic 1003 if (unsigned BuiltinID = Old->getBuiltinID()) { 1004 // The user has declared a builtin function with an incompatible 1005 // signature. 1006 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 1007 // The function the user is redeclaring is a library-defined 1008 // function like 'malloc' or 'printf'. Warn about the 1009 // redeclaration, then pretend that we don't know about this 1010 // library built-in. 1011 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 1012 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 1013 << Old << Old->getType(); 1014 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 1015 Old->setInvalidDecl(); 1016 return false; 1017 } 1018 1019 PrevDiag = diag::note_previous_builtin_declaration; 1020 } 1021 1022 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 1023 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1024 return true; 1025} 1026 1027/// \brief Completes the merge of two function declarations that are 1028/// known to be compatible. 1029/// 1030/// This routine handles the merging of attributes and other 1031/// properties of function declarations form the old declaration to 1032/// the new declaration, once we know that New is in fact a 1033/// redeclaration of Old. 1034/// 1035/// \returns false 1036bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) { 1037 // Merge the attributes 1038 MergeAttributes(New, Old, Context); 1039 1040 // Merge the storage class. 1041 if (Old->getStorageClass() != FunctionDecl::Extern && 1042 Old->getStorageClass() != FunctionDecl::None) 1043 New->setStorageClass(Old->getStorageClass()); 1044 1045 // Merge "pure" flag. 1046 if (Old->isPure()) 1047 New->setPure(); 1048 1049 // Merge the "deleted" flag. 1050 if (Old->isDeleted()) 1051 New->setDeleted(); 1052 1053 if (getLangOptions().CPlusPlus) 1054 return MergeCXXFunctionDecl(New, Old); 1055 1056 return false; 1057} 1058 1059/// MergeVarDecl - We just parsed a variable 'New' which has the same name 1060/// and scope as a previous declaration 'Old'. Figure out how to resolve this 1061/// situation, merging decls or emitting diagnostics as appropriate. 1062/// 1063/// Tentative definition rules (C99 6.9.2p2) are checked by 1064/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 1065/// definitions here, since the initializer hasn't been attached. 1066/// 1067void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 1068 // If the new decl is already invalid, don't do any other checking. 1069 if (New->isInvalidDecl()) 1070 return; 1071 1072 // Verify the old decl was also a variable. 1073 VarDecl *Old = 0; 1074 if (!Previous.isSingleResult() || 1075 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 1076 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1077 << New->getDeclName(); 1078 Diag(Previous.getRepresentativeDecl()->getLocation(), 1079 diag::note_previous_definition); 1080 return New->setInvalidDecl(); 1081 } 1082 1083 MergeAttributes(New, Old, Context); 1084 1085 // Merge the types 1086 QualType MergedT; 1087 if (getLangOptions().CPlusPlus) { 1088 if (Context.hasSameType(New->getType(), Old->getType())) 1089 MergedT = New->getType(); 1090 // C++ [basic.types]p7: 1091 // [...] The declared type of an array object might be an array of 1092 // unknown size and therefore be incomplete at one point in a 1093 // translation unit and complete later on; [...] 1094 else if (Old->getType()->isIncompleteArrayType() && 1095 New->getType()->isArrayType()) { 1096 CanQual<ArrayType> OldArray 1097 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 1098 CanQual<ArrayType> NewArray 1099 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 1100 if (OldArray->getElementType() == NewArray->getElementType()) 1101 MergedT = New->getType(); 1102 } 1103 } else { 1104 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 1105 } 1106 if (MergedT.isNull()) { 1107 Diag(New->getLocation(), diag::err_redefinition_different_type) 1108 << New->getDeclName(); 1109 Diag(Old->getLocation(), diag::note_previous_definition); 1110 return New->setInvalidDecl(); 1111 } 1112 New->setType(MergedT); 1113 1114 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 1115 if (New->getStorageClass() == VarDecl::Static && 1116 (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) { 1117 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 1118 Diag(Old->getLocation(), diag::note_previous_definition); 1119 return New->setInvalidDecl(); 1120 } 1121 // C99 6.2.2p4: 1122 // For an identifier declared with the storage-class specifier 1123 // extern in a scope in which a prior declaration of that 1124 // identifier is visible,23) if the prior declaration specifies 1125 // internal or external linkage, the linkage of the identifier at 1126 // the later declaration is the same as the linkage specified at 1127 // the prior declaration. If no prior declaration is visible, or 1128 // if the prior declaration specifies no linkage, then the 1129 // identifier has external linkage. 1130 if (New->hasExternalStorage() && Old->hasLinkage()) 1131 /* Okay */; 1132 else if (New->getStorageClass() != VarDecl::Static && 1133 Old->getStorageClass() == VarDecl::Static) { 1134 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 1135 Diag(Old->getLocation(), diag::note_previous_definition); 1136 return New->setInvalidDecl(); 1137 } 1138 1139 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 1140 1141 // FIXME: The test for external storage here seems wrong? We still 1142 // need to check for mismatches. 1143 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 1144 // Don't complain about out-of-line definitions of static members. 1145 !(Old->getLexicalDeclContext()->isRecord() && 1146 !New->getLexicalDeclContext()->isRecord())) { 1147 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 1148 Diag(Old->getLocation(), diag::note_previous_definition); 1149 return New->setInvalidDecl(); 1150 } 1151 1152 if (New->isThreadSpecified() && !Old->isThreadSpecified()) { 1153 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 1154 Diag(Old->getLocation(), diag::note_previous_definition); 1155 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) { 1156 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 1157 Diag(Old->getLocation(), diag::note_previous_definition); 1158 } 1159 1160 // Keep a chain of previous declarations. 1161 New->setPreviousDeclaration(Old); 1162} 1163 1164/// CheckFallThrough - Check that we don't fall off the end of a 1165/// Statement that should return a value. 1166/// 1167/// \returns AlwaysFallThrough iff we always fall off the end of the statement, 1168/// MaybeFallThrough iff we might or might not fall off the end, 1169/// NeverFallThroughOrReturn iff we never fall off the end of the statement or 1170/// return. We assume NeverFallThrough iff we never fall off the end of the 1171/// statement but we may return. We assume that functions not marked noreturn 1172/// will return. 1173Sema::ControlFlowKind Sema::CheckFallThrough(Stmt *Root) { 1174 // FIXME: Eventually share this CFG object when we have other warnings based 1175 // of the CFG. This can be done using AnalysisContext. 1176 llvm::OwningPtr<CFG> cfg (CFG::buildCFG(Root, &Context)); 1177 1178 // FIXME: They should never return 0, fix that, delete this code. 1179 if (cfg == 0) 1180 // FIXME: This should be NeverFallThrough 1181 return NeverFallThroughOrReturn; 1182 // The CFG leaves in dead things, and we don't want to dead code paths to 1183 // confuse us, so we mark all live things first. 1184 std::queue<CFGBlock*> workq; 1185 llvm::BitVector live(cfg->getNumBlockIDs()); 1186 // Prep work queue 1187 workq.push(&cfg->getEntry()); 1188 // Solve 1189 while (!workq.empty()) { 1190 CFGBlock *item = workq.front(); 1191 workq.pop(); 1192 live.set(item->getBlockID()); 1193 for (CFGBlock::succ_iterator I=item->succ_begin(), 1194 E=item->succ_end(); 1195 I != E; 1196 ++I) { 1197 if ((*I) && !live[(*I)->getBlockID()]) { 1198 live.set((*I)->getBlockID()); 1199 workq.push(*I); 1200 } 1201 } 1202 } 1203 1204 // Now we know what is live, we check the live precessors of the exit block 1205 // and look for fall through paths, being careful to ignore normal returns, 1206 // and exceptional paths. 1207 bool HasLiveReturn = false; 1208 bool HasFakeEdge = false; 1209 bool HasPlainEdge = false; 1210 for (CFGBlock::pred_iterator I=cfg->getExit().pred_begin(), 1211 E = cfg->getExit().pred_end(); 1212 I != E; 1213 ++I) { 1214 CFGBlock& B = **I; 1215 if (!live[B.getBlockID()]) 1216 continue; 1217 if (B.size() == 0) { 1218 // A labeled empty statement, or the entry block... 1219 HasPlainEdge = true; 1220 continue; 1221 } 1222 Stmt *S = B[B.size()-1]; 1223 if (isa<ReturnStmt>(S)) { 1224 HasLiveReturn = true; 1225 continue; 1226 } 1227 if (isa<ObjCAtThrowStmt>(S)) { 1228 HasFakeEdge = true; 1229 continue; 1230 } 1231 if (isa<CXXThrowExpr>(S)) { 1232 HasFakeEdge = true; 1233 continue; 1234 } 1235 bool NoReturnEdge = false; 1236 if (CallExpr *C = dyn_cast<CallExpr>(S)) { 1237 Expr *CEE = C->getCallee()->IgnoreParenCasts(); 1238 if (CEE->getType().getNoReturnAttr()) { 1239 NoReturnEdge = true; 1240 HasFakeEdge = true; 1241 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) { 1242 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 1243 if (FD->hasAttr<NoReturnAttr>()) { 1244 NoReturnEdge = true; 1245 HasFakeEdge = true; 1246 } 1247 } 1248 } 1249 } 1250 // FIXME: Add noreturn message sends. 1251 if (NoReturnEdge == false) 1252 HasPlainEdge = true; 1253 } 1254 if (!HasPlainEdge) { 1255 if (HasLiveReturn) 1256 return NeverFallThrough; 1257 return NeverFallThroughOrReturn; 1258 } 1259 if (HasFakeEdge || HasLiveReturn) 1260 return MaybeFallThrough; 1261 // This says AlwaysFallThrough for calls to functions that are not marked 1262 // noreturn, that don't return. If people would like this warning to be more 1263 // accurate, such functions should be marked as noreturn. 1264 return AlwaysFallThrough; 1265} 1266 1267/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a 1268/// function that should return a value. Check that we don't fall off the end 1269/// of a noreturn function. We assume that functions and blocks not marked 1270/// noreturn will return. 1271void Sema::CheckFallThroughForFunctionDef(Decl *D, Stmt *Body) { 1272 // FIXME: Would be nice if we had a better way to control cascading errors, 1273 // but for now, avoid them. The problem is that when Parse sees: 1274 // int foo() { return a; } 1275 // The return is eaten and the Sema code sees just: 1276 // int foo() { } 1277 // which this code would then warn about. 1278 if (getDiagnostics().hasErrorOccurred()) 1279 return; 1280 1281 bool ReturnsVoid = false; 1282 bool HasNoReturn = false; 1283 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1284 // If the result type of the function is a dependent type, we don't know 1285 // whether it will be void or not, so don't 1286 if (FD->getResultType()->isDependentType()) 1287 return; 1288 if (FD->getResultType()->isVoidType()) 1289 ReturnsVoid = true; 1290 if (FD->hasAttr<NoReturnAttr>()) 1291 HasNoReturn = true; 1292 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 1293 if (MD->getResultType()->isVoidType()) 1294 ReturnsVoid = true; 1295 if (MD->hasAttr<NoReturnAttr>()) 1296 HasNoReturn = true; 1297 } 1298 1299 // Short circuit for compilation speed. 1300 if ((Diags.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function) 1301 == Diagnostic::Ignored || ReturnsVoid) 1302 && (Diags.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr) 1303 == Diagnostic::Ignored || !HasNoReturn) 1304 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block) 1305 == Diagnostic::Ignored || !ReturnsVoid)) 1306 return; 1307 // FIXME: Function try block 1308 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) { 1309 switch (CheckFallThrough(Body)) { 1310 case MaybeFallThrough: 1311 if (HasNoReturn) 1312 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function); 1313 else if (!ReturnsVoid) 1314 Diag(Compound->getRBracLoc(),diag::warn_maybe_falloff_nonvoid_function); 1315 break; 1316 case AlwaysFallThrough: 1317 if (HasNoReturn) 1318 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function); 1319 else if (!ReturnsVoid) 1320 Diag(Compound->getRBracLoc(), diag::warn_falloff_nonvoid_function); 1321 break; 1322 case NeverFallThroughOrReturn: 1323 if (ReturnsVoid && !HasNoReturn) 1324 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_function); 1325 break; 1326 case NeverFallThrough: 1327 break; 1328 } 1329 } 1330} 1331 1332/// CheckFallThroughForBlock - Check that we don't fall off the end of a block 1333/// that should return a value. Check that we don't fall off the end of a 1334/// noreturn block. We assume that functions and blocks not marked noreturn 1335/// will return. 1336void Sema::CheckFallThroughForBlock(QualType BlockTy, Stmt *Body) { 1337 // FIXME: Would be nice if we had a better way to control cascading errors, 1338 // but for now, avoid them. The problem is that when Parse sees: 1339 // int foo() { return a; } 1340 // The return is eaten and the Sema code sees just: 1341 // int foo() { } 1342 // which this code would then warn about. 1343 if (getDiagnostics().hasErrorOccurred()) 1344 return; 1345 bool ReturnsVoid = false; 1346 bool HasNoReturn = false; 1347 if (const FunctionType *FT =BlockTy->getPointeeType()->getAs<FunctionType>()){ 1348 if (FT->getResultType()->isVoidType()) 1349 ReturnsVoid = true; 1350 if (FT->getNoReturnAttr()) 1351 HasNoReturn = true; 1352 } 1353 1354 // Short circuit for compilation speed. 1355 if (ReturnsVoid 1356 && !HasNoReturn 1357 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block) 1358 == Diagnostic::Ignored || !ReturnsVoid)) 1359 return; 1360 // FIXME: Funtion try block 1361 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) { 1362 switch (CheckFallThrough(Body)) { 1363 case MaybeFallThrough: 1364 if (HasNoReturn) 1365 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr); 1366 else if (!ReturnsVoid) 1367 Diag(Compound->getRBracLoc(), diag::err_maybe_falloff_nonvoid_block); 1368 break; 1369 case AlwaysFallThrough: 1370 if (HasNoReturn) 1371 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr); 1372 else if (!ReturnsVoid) 1373 Diag(Compound->getRBracLoc(), diag::err_falloff_nonvoid_block); 1374 break; 1375 case NeverFallThroughOrReturn: 1376 if (ReturnsVoid) 1377 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_block); 1378 break; 1379 case NeverFallThrough: 1380 break; 1381 } 1382 } 1383} 1384 1385/// CheckParmsForFunctionDef - Check that the parameters of the given 1386/// function are appropriate for the definition of a function. This 1387/// takes care of any checks that cannot be performed on the 1388/// declaration itself, e.g., that the types of each of the function 1389/// parameters are complete. 1390bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) { 1391 bool HasInvalidParm = false; 1392 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 1393 ParmVarDecl *Param = FD->getParamDecl(p); 1394 1395 // C99 6.7.5.3p4: the parameters in a parameter type list in a 1396 // function declarator that is part of a function definition of 1397 // that function shall not have incomplete type. 1398 // 1399 // This is also C++ [dcl.fct]p6. 1400 if (!Param->isInvalidDecl() && 1401 RequireCompleteType(Param->getLocation(), Param->getType(), 1402 diag::err_typecheck_decl_incomplete_type)) { 1403 Param->setInvalidDecl(); 1404 HasInvalidParm = true; 1405 } 1406 1407 // C99 6.9.1p5: If the declarator includes a parameter type list, the 1408 // declaration of each parameter shall include an identifier. 1409 if (Param->getIdentifier() == 0 && 1410 !Param->isImplicit() && 1411 !getLangOptions().CPlusPlus) 1412 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 1413 } 1414 1415 return HasInvalidParm; 1416} 1417 1418/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 1419/// no declarator (e.g. "struct foo;") is parsed. 1420Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) { 1421 // FIXME: Error on auto/register at file scope 1422 // FIXME: Error on inline/virtual/explicit 1423 // FIXME: Error on invalid restrict 1424 // FIXME: Warn on useless __thread 1425 // FIXME: Warn on useless const/volatile 1426 // FIXME: Warn on useless static/extern/typedef/private_extern/mutable 1427 // FIXME: Warn on useless attributes 1428 Decl *TagD = 0; 1429 TagDecl *Tag = 0; 1430 if (DS.getTypeSpecType() == DeclSpec::TST_class || 1431 DS.getTypeSpecType() == DeclSpec::TST_struct || 1432 DS.getTypeSpecType() == DeclSpec::TST_union || 1433 DS.getTypeSpecType() == DeclSpec::TST_enum) { 1434 TagD = static_cast<Decl *>(DS.getTypeRep()); 1435 1436 if (!TagD) // We probably had an error 1437 return DeclPtrTy(); 1438 1439 // Note that the above type specs guarantee that the 1440 // type rep is a Decl, whereas in many of the others 1441 // it's a Type. 1442 Tag = dyn_cast<TagDecl>(TagD); 1443 } 1444 1445 if (DS.isFriendSpecified()) { 1446 // If we're dealing with a class template decl, assume that the 1447 // template routines are handling it. 1448 if (TagD && isa<ClassTemplateDecl>(TagD)) 1449 return DeclPtrTy(); 1450 return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0)); 1451 } 1452 1453 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 1454 // If there are attributes in the DeclSpec, apply them to the record. 1455 if (const AttributeList *AL = DS.getAttributes()) 1456 ProcessDeclAttributeList(S, Record, AL); 1457 1458 if (!Record->getDeclName() && Record->isDefinition() && 1459 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 1460 if (getLangOptions().CPlusPlus || 1461 Record->getDeclContext()->isRecord()) 1462 return BuildAnonymousStructOrUnion(S, DS, Record); 1463 1464 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators) 1465 << DS.getSourceRange(); 1466 } 1467 1468 // Microsoft allows unnamed struct/union fields. Don't complain 1469 // about them. 1470 // FIXME: Should we support Microsoft's extensions in this area? 1471 if (Record->getDeclName() && getLangOptions().Microsoft) 1472 return DeclPtrTy::make(Tag); 1473 } 1474 1475 if (!DS.isMissingDeclaratorOk() && 1476 DS.getTypeSpecType() != DeclSpec::TST_error) { 1477 // Warn about typedefs of enums without names, since this is an 1478 // extension in both Microsoft an GNU. 1479 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef && 1480 Tag && isa<EnumDecl>(Tag)) { 1481 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name) 1482 << DS.getSourceRange(); 1483 return DeclPtrTy::make(Tag); 1484 } 1485 1486 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators) 1487 << DS.getSourceRange(); 1488 return DeclPtrTy(); 1489 } 1490 1491 return DeclPtrTy::make(Tag); 1492} 1493 1494/// We are trying to introduce the given name into the given context; 1495/// check if there's an existing declaration that can't be overloaded. 1496/// 1497/// \return true if this is a forbidden redeclaration 1498bool Sema::CheckRedeclaration(DeclContext *DC, 1499 DeclarationName Name, 1500 SourceLocation NameLoc, 1501 unsigned diagnostic) { 1502 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName, 1503 ForRedeclaration); 1504 LookupQualifiedName(R, DC); 1505 1506 if (R.empty()) return false; 1507 1508 if (R.getResultKind() == LookupResult::Found && 1509 isa<TagDecl>(R.getFoundDecl())) 1510 return false; 1511 1512 // Pick a representative declaration. 1513 NamedDecl *PrevDecl = (*R.begin())->getUnderlyingDecl(); 1514 1515 Diag(NameLoc, diagnostic) << Name; 1516 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 1517 1518 return true; 1519} 1520 1521/// InjectAnonymousStructOrUnionMembers - Inject the members of the 1522/// anonymous struct or union AnonRecord into the owning context Owner 1523/// and scope S. This routine will be invoked just after we realize 1524/// that an unnamed union or struct is actually an anonymous union or 1525/// struct, e.g., 1526/// 1527/// @code 1528/// union { 1529/// int i; 1530/// float f; 1531/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 1532/// // f into the surrounding scope.x 1533/// @endcode 1534/// 1535/// This routine is recursive, injecting the names of nested anonymous 1536/// structs/unions into the owning context and scope as well. 1537bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner, 1538 RecordDecl *AnonRecord) { 1539 unsigned diagKind 1540 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 1541 : diag::err_anonymous_struct_member_redecl; 1542 1543 bool Invalid = false; 1544 for (RecordDecl::field_iterator F = AnonRecord->field_begin(), 1545 FEnd = AnonRecord->field_end(); 1546 F != FEnd; ++F) { 1547 if ((*F)->getDeclName()) { 1548 if (CheckRedeclaration(Owner, (*F)->getDeclName(), 1549 (*F)->getLocation(), diagKind)) { 1550 // C++ [class.union]p2: 1551 // The names of the members of an anonymous union shall be 1552 // distinct from the names of any other entity in the 1553 // scope in which the anonymous union is declared. 1554 Invalid = true; 1555 } else { 1556 // C++ [class.union]p2: 1557 // For the purpose of name lookup, after the anonymous union 1558 // definition, the members of the anonymous union are 1559 // considered to have been defined in the scope in which the 1560 // anonymous union is declared. 1561 Owner->makeDeclVisibleInContext(*F); 1562 S->AddDecl(DeclPtrTy::make(*F)); 1563 IdResolver.AddDecl(*F); 1564 } 1565 } else if (const RecordType *InnerRecordType 1566 = (*F)->getType()->getAs<RecordType>()) { 1567 RecordDecl *InnerRecord = InnerRecordType->getDecl(); 1568 if (InnerRecord->isAnonymousStructOrUnion()) 1569 Invalid = Invalid || 1570 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord); 1571 } 1572 } 1573 1574 return Invalid; 1575} 1576 1577/// ActOnAnonymousStructOrUnion - Handle the declaration of an 1578/// anonymous structure or union. Anonymous unions are a C++ feature 1579/// (C++ [class.union]) and a GNU C extension; anonymous structures 1580/// are a GNU C and GNU C++ extension. 1581Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 1582 RecordDecl *Record) { 1583 DeclContext *Owner = Record->getDeclContext(); 1584 1585 // Diagnose whether this anonymous struct/union is an extension. 1586 if (Record->isUnion() && !getLangOptions().CPlusPlus) 1587 Diag(Record->getLocation(), diag::ext_anonymous_union); 1588 else if (!Record->isUnion()) 1589 Diag(Record->getLocation(), diag::ext_anonymous_struct); 1590 1591 // C and C++ require different kinds of checks for anonymous 1592 // structs/unions. 1593 bool Invalid = false; 1594 if (getLangOptions().CPlusPlus) { 1595 const char* PrevSpec = 0; 1596 unsigned DiagID; 1597 // C++ [class.union]p3: 1598 // Anonymous unions declared in a named namespace or in the 1599 // global namespace shall be declared static. 1600 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 1601 (isa<TranslationUnitDecl>(Owner) || 1602 (isa<NamespaceDecl>(Owner) && 1603 cast<NamespaceDecl>(Owner)->getDeclName()))) { 1604 Diag(Record->getLocation(), diag::err_anonymous_union_not_static); 1605 Invalid = true; 1606 1607 // Recover by adding 'static'. 1608 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), 1609 PrevSpec, DiagID); 1610 } 1611 // C++ [class.union]p3: 1612 // A storage class is not allowed in a declaration of an 1613 // anonymous union in a class scope. 1614 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 1615 isa<RecordDecl>(Owner)) { 1616 Diag(DS.getStorageClassSpecLoc(), 1617 diag::err_anonymous_union_with_storage_spec); 1618 Invalid = true; 1619 1620 // Recover by removing the storage specifier. 1621 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(), 1622 PrevSpec, DiagID); 1623 } 1624 1625 // C++ [class.union]p2: 1626 // The member-specification of an anonymous union shall only 1627 // define non-static data members. [Note: nested types and 1628 // functions cannot be declared within an anonymous union. ] 1629 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 1630 MemEnd = Record->decls_end(); 1631 Mem != MemEnd; ++Mem) { 1632 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 1633 // C++ [class.union]p3: 1634 // An anonymous union shall not have private or protected 1635 // members (clause 11). 1636 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) { 1637 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 1638 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 1639 Invalid = true; 1640 } 1641 } else if ((*Mem)->isImplicit()) { 1642 // Any implicit members are fine. 1643 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 1644 // This is a type that showed up in an 1645 // elaborated-type-specifier inside the anonymous struct or 1646 // union, but which actually declares a type outside of the 1647 // anonymous struct or union. It's okay. 1648 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 1649 if (!MemRecord->isAnonymousStructOrUnion() && 1650 MemRecord->getDeclName()) { 1651 // This is a nested type declaration. 1652 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 1653 << (int)Record->isUnion(); 1654 Invalid = true; 1655 } 1656 } else { 1657 // We have something that isn't a non-static data 1658 // member. Complain about it. 1659 unsigned DK = diag::err_anonymous_record_bad_member; 1660 if (isa<TypeDecl>(*Mem)) 1661 DK = diag::err_anonymous_record_with_type; 1662 else if (isa<FunctionDecl>(*Mem)) 1663 DK = diag::err_anonymous_record_with_function; 1664 else if (isa<VarDecl>(*Mem)) 1665 DK = diag::err_anonymous_record_with_static; 1666 Diag((*Mem)->getLocation(), DK) 1667 << (int)Record->isUnion(); 1668 Invalid = true; 1669 } 1670 } 1671 } 1672 1673 if (!Record->isUnion() && !Owner->isRecord()) { 1674 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 1675 << (int)getLangOptions().CPlusPlus; 1676 Invalid = true; 1677 } 1678 1679 // Mock up a declarator. 1680 Declarator Dc(DS, Declarator::TypeNameContext); 1681 TypeSourceInfo *TInfo = 0; 1682 GetTypeForDeclarator(Dc, S, &TInfo); 1683 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 1684 1685 // Create a declaration for this anonymous struct/union. 1686 NamedDecl *Anon = 0; 1687 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 1688 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(), 1689 /*IdentifierInfo=*/0, 1690 Context.getTypeDeclType(Record), 1691 TInfo, 1692 /*BitWidth=*/0, /*Mutable=*/false); 1693 Anon->setAccess(AS_public); 1694 if (getLangOptions().CPlusPlus) 1695 FieldCollector->Add(cast<FieldDecl>(Anon)); 1696 } else { 1697 VarDecl::StorageClass SC; 1698 switch (DS.getStorageClassSpec()) { 1699 default: assert(0 && "Unknown storage class!"); 1700 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 1701 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 1702 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 1703 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 1704 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 1705 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 1706 case DeclSpec::SCS_mutable: 1707 // mutable can only appear on non-static class members, so it's always 1708 // an error here 1709 Diag(Record->getLocation(), diag::err_mutable_nonmember); 1710 Invalid = true; 1711 SC = VarDecl::None; 1712 break; 1713 } 1714 1715 Anon = VarDecl::Create(Context, Owner, Record->getLocation(), 1716 /*IdentifierInfo=*/0, 1717 Context.getTypeDeclType(Record), 1718 TInfo, 1719 SC); 1720 } 1721 Anon->setImplicit(); 1722 1723 // Add the anonymous struct/union object to the current 1724 // context. We'll be referencing this object when we refer to one of 1725 // its members. 1726 Owner->addDecl(Anon); 1727 1728 // Inject the members of the anonymous struct/union into the owning 1729 // context and into the identifier resolver chain for name lookup 1730 // purposes. 1731 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record)) 1732 Invalid = true; 1733 1734 // Mark this as an anonymous struct/union type. Note that we do not 1735 // do this until after we have already checked and injected the 1736 // members of this anonymous struct/union type, because otherwise 1737 // the members could be injected twice: once by DeclContext when it 1738 // builds its lookup table, and once by 1739 // InjectAnonymousStructOrUnionMembers. 1740 Record->setAnonymousStructOrUnion(true); 1741 1742 if (Invalid) 1743 Anon->setInvalidDecl(); 1744 1745 return DeclPtrTy::make(Anon); 1746} 1747 1748 1749/// GetNameForDeclarator - Determine the full declaration name for the 1750/// given Declarator. 1751DeclarationName Sema::GetNameForDeclarator(Declarator &D) { 1752 return GetNameFromUnqualifiedId(D.getName()); 1753} 1754 1755/// \brief Retrieves the canonicalized name from a parsed unqualified-id. 1756DeclarationName Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 1757 switch (Name.getKind()) { 1758 case UnqualifiedId::IK_Identifier: 1759 return DeclarationName(Name.Identifier); 1760 1761 case UnqualifiedId::IK_OperatorFunctionId: 1762 return Context.DeclarationNames.getCXXOperatorName( 1763 Name.OperatorFunctionId.Operator); 1764 1765 case UnqualifiedId::IK_LiteralOperatorId: 1766 return Context.DeclarationNames.getCXXLiteralOperatorName( 1767 Name.Identifier); 1768 1769 case UnqualifiedId::IK_ConversionFunctionId: { 1770 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId); 1771 if (Ty.isNull()) 1772 return DeclarationName(); 1773 1774 return Context.DeclarationNames.getCXXConversionFunctionName( 1775 Context.getCanonicalType(Ty)); 1776 } 1777 1778 case UnqualifiedId::IK_ConstructorName: { 1779 QualType Ty = GetTypeFromParser(Name.ConstructorName); 1780 if (Ty.isNull()) 1781 return DeclarationName(); 1782 1783 return Context.DeclarationNames.getCXXConstructorName( 1784 Context.getCanonicalType(Ty)); 1785 } 1786 1787 case UnqualifiedId::IK_DestructorName: { 1788 QualType Ty = GetTypeFromParser(Name.DestructorName); 1789 if (Ty.isNull()) 1790 return DeclarationName(); 1791 1792 return Context.DeclarationNames.getCXXDestructorName( 1793 Context.getCanonicalType(Ty)); 1794 } 1795 1796 case UnqualifiedId::IK_TemplateId: { 1797 TemplateName TName 1798 = TemplateName::getFromVoidPointer(Name.TemplateId->Template); 1799 return Context.getNameForTemplate(TName); 1800 } 1801 } 1802 1803 assert(false && "Unknown name kind"); 1804 return DeclarationName(); 1805} 1806 1807/// isNearlyMatchingFunction - Determine whether the C++ functions 1808/// Declaration and Definition are "nearly" matching. This heuristic 1809/// is used to improve diagnostics in the case where an out-of-line 1810/// function definition doesn't match any declaration within 1811/// the class or namespace. 1812static bool isNearlyMatchingFunction(ASTContext &Context, 1813 FunctionDecl *Declaration, 1814 FunctionDecl *Definition) { 1815 if (Declaration->param_size() != Definition->param_size()) 1816 return false; 1817 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 1818 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 1819 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 1820 1821 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(), 1822 DefParamTy.getNonReferenceType())) 1823 return false; 1824 } 1825 1826 return true; 1827} 1828 1829Sema::DeclPtrTy 1830Sema::HandleDeclarator(Scope *S, Declarator &D, 1831 MultiTemplateParamsArg TemplateParamLists, 1832 bool IsFunctionDefinition) { 1833 DeclarationName Name = GetNameForDeclarator(D); 1834 1835 // All of these full declarators require an identifier. If it doesn't have 1836 // one, the ParsedFreeStandingDeclSpec action should be used. 1837 if (!Name) { 1838 if (!D.isInvalidType()) // Reject this if we think it is valid. 1839 Diag(D.getDeclSpec().getSourceRange().getBegin(), 1840 diag::err_declarator_need_ident) 1841 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 1842 return DeclPtrTy(); 1843 } 1844 1845 // The scope passed in may not be a decl scope. Zip up the scope tree until 1846 // we find one that is. 1847 while ((S->getFlags() & Scope::DeclScope) == 0 || 1848 (S->getFlags() & Scope::TemplateParamScope) != 0) 1849 S = S->getParent(); 1850 1851 // If this is an out-of-line definition of a member of a class template 1852 // or class template partial specialization, we may need to rebuild the 1853 // type specifier in the declarator. See RebuildTypeInCurrentInstantiation() 1854 // for more information. 1855 // FIXME: cope with decltype(expr) and typeof(expr) once the rebuilder can 1856 // handle expressions properly. 1857 DeclSpec &DS = const_cast<DeclSpec&>(D.getDeclSpec()); 1858 if (D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid() && 1859 isDependentScopeSpecifier(D.getCXXScopeSpec()) && 1860 (DS.getTypeSpecType() == DeclSpec::TST_typename || 1861 DS.getTypeSpecType() == DeclSpec::TST_typeofType || 1862 DS.getTypeSpecType() == DeclSpec::TST_typeofExpr || 1863 DS.getTypeSpecType() == DeclSpec::TST_decltype)) { 1864 if (DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(), true)) { 1865 // FIXME: Preserve type source info. 1866 QualType T = GetTypeFromParser(DS.getTypeRep()); 1867 EnterDeclaratorContext(S, DC); 1868 T = RebuildTypeInCurrentInstantiation(T, D.getIdentifierLoc(), Name); 1869 ExitDeclaratorContext(S); 1870 if (T.isNull()) 1871 return DeclPtrTy(); 1872 DS.UpdateTypeRep(T.getAsOpaquePtr()); 1873 } 1874 } 1875 1876 DeclContext *DC; 1877 NamedDecl *New; 1878 1879 TypeSourceInfo *TInfo = 0; 1880 QualType R = GetTypeForDeclarator(D, S, &TInfo); 1881 1882 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName, 1883 ForRedeclaration); 1884 1885 // See if this is a redefinition of a variable in the same scope. 1886 if (D.getCXXScopeSpec().isInvalid()) { 1887 DC = CurContext; 1888 D.setInvalidType(); 1889 } else if (!D.getCXXScopeSpec().isSet()) { 1890 bool IsLinkageLookup = false; 1891 1892 // If the declaration we're planning to build will be a function 1893 // or object with linkage, then look for another declaration with 1894 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 1895 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 1896 /* Do nothing*/; 1897 else if (R->isFunctionType()) { 1898 if (CurContext->isFunctionOrMethod() || 1899 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 1900 IsLinkageLookup = true; 1901 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 1902 IsLinkageLookup = true; 1903 else if (CurContext->getLookupContext()->isTranslationUnit() && 1904 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 1905 IsLinkageLookup = true; 1906 1907 if (IsLinkageLookup) 1908 Previous.clear(LookupRedeclarationWithLinkage); 1909 1910 DC = CurContext; 1911 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup); 1912 } else { // Something like "int foo::x;" 1913 DC = computeDeclContext(D.getCXXScopeSpec(), true); 1914 1915 if (!DC) { 1916 // If we could not compute the declaration context, it's because the 1917 // declaration context is dependent but does not refer to a class, 1918 // class template, or class template partial specialization. Complain 1919 // and return early, to avoid the coming semantic disaster. 1920 Diag(D.getIdentifierLoc(), 1921 diag::err_template_qualified_declarator_no_match) 1922 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 1923 << D.getCXXScopeSpec().getRange(); 1924 return DeclPtrTy(); 1925 } 1926 1927 if (!DC->isDependentContext() && 1928 RequireCompleteDeclContext(D.getCXXScopeSpec())) 1929 return DeclPtrTy(); 1930 1931 LookupQualifiedName(Previous, DC); 1932 1933 // Don't consider using declarations as previous declarations for 1934 // out-of-line members. 1935 RemoveUsingDecls(Previous); 1936 1937 // C++ 7.3.1.2p2: 1938 // Members (including explicit specializations of templates) of a named 1939 // namespace can also be defined outside that namespace by explicit 1940 // qualification of the name being defined, provided that the entity being 1941 // defined was already declared in the namespace and the definition appears 1942 // after the point of declaration in a namespace that encloses the 1943 // declarations namespace. 1944 // 1945 // Note that we only check the context at this point. We don't yet 1946 // have enough information to make sure that PrevDecl is actually 1947 // the declaration we want to match. For example, given: 1948 // 1949 // class X { 1950 // void f(); 1951 // void f(float); 1952 // }; 1953 // 1954 // void X::f(int) { } // ill-formed 1955 // 1956 // In this case, PrevDecl will point to the overload set 1957 // containing the two f's declared in X, but neither of them 1958 // matches. 1959 1960 // First check whether we named the global scope. 1961 if (isa<TranslationUnitDecl>(DC)) { 1962 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope) 1963 << Name << D.getCXXScopeSpec().getRange(); 1964 } else { 1965 DeclContext *Cur = CurContext; 1966 while (isa<LinkageSpecDecl>(Cur)) 1967 Cur = Cur->getParent(); 1968 if (!Cur->Encloses(DC)) { 1969 // The qualifying scope doesn't enclose the original declaration. 1970 // Emit diagnostic based on current scope. 1971 SourceLocation L = D.getIdentifierLoc(); 1972 SourceRange R = D.getCXXScopeSpec().getRange(); 1973 if (isa<FunctionDecl>(Cur)) 1974 Diag(L, diag::err_invalid_declarator_in_function) << Name << R; 1975 else 1976 Diag(L, diag::err_invalid_declarator_scope) 1977 << Name << cast<NamedDecl>(DC) << R; 1978 D.setInvalidType(); 1979 } 1980 } 1981 } 1982 1983 if (Previous.isSingleResult() && 1984 Previous.getFoundDecl()->isTemplateParameter()) { 1985 // Maybe we will complain about the shadowed template parameter. 1986 if (!D.isInvalidType()) 1987 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 1988 Previous.getFoundDecl())) 1989 D.setInvalidType(); 1990 1991 // Just pretend that we didn't see the previous declaration. 1992 Previous.clear(); 1993 } 1994 1995 // In C++, the previous declaration we find might be a tag type 1996 // (class or enum). In this case, the new declaration will hide the 1997 // tag type. Note that this does does not apply if we're declaring a 1998 // typedef (C++ [dcl.typedef]p4). 1999 if (Previous.isSingleTagDecl() && 2000 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 2001 Previous.clear(); 2002 2003 bool Redeclaration = false; 2004 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 2005 if (TemplateParamLists.size()) { 2006 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 2007 return DeclPtrTy(); 2008 } 2009 2010 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration); 2011 } else if (R->isFunctionType()) { 2012 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous, 2013 move(TemplateParamLists), 2014 IsFunctionDefinition, Redeclaration); 2015 } else { 2016 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous, 2017 move(TemplateParamLists), 2018 Redeclaration); 2019 } 2020 2021 if (New == 0) 2022 return DeclPtrTy(); 2023 2024 // If this has an identifier and is not an invalid redeclaration or 2025 // function template specialization, add it to the scope stack. 2026 if (Name && !(Redeclaration && New->isInvalidDecl()) && 2027 !(isa<FunctionDecl>(New) && 2028 cast<FunctionDecl>(New)->isFunctionTemplateSpecialization())) 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 3987Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) { 3988 // Clear the last template instantiation error context. 3989 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 3990 3991 if (!D) 3992 return D; 3993 FunctionDecl *FD = 0; 3994 3995 if (FunctionTemplateDecl *FunTmpl 3996 = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>())) 3997 FD = FunTmpl->getTemplatedDecl(); 3998 else 3999 FD = cast<FunctionDecl>(D.getAs<Decl>()); 4000 4001 CurFunctionNeedsScopeChecking = false; 4002 4003 // See if this is a redefinition. 4004 const FunctionDecl *Definition; 4005 if (FD->getBody(Definition)) { 4006 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 4007 Diag(Definition->getLocation(), diag::note_previous_definition); 4008 } 4009 4010 // Builtin functions cannot be defined. 4011 if (unsigned BuiltinID = FD->getBuiltinID()) { 4012 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 4013 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 4014 FD->setInvalidDecl(); 4015 } 4016 } 4017 4018 // The return type of a function definition must be complete 4019 // (C99 6.9.1p3, C++ [dcl.fct]p6). 4020 QualType ResultType = FD->getResultType(); 4021 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 4022 !FD->isInvalidDecl() && 4023 RequireCompleteType(FD->getLocation(), ResultType, 4024 diag::err_func_def_incomplete_result)) 4025 FD->setInvalidDecl(); 4026 4027 // GNU warning -Wmissing-prototypes: 4028 // Warn if a global function is defined without a previous 4029 // prototype declaration. This warning is issued even if the 4030 // definition itself provides a prototype. The aim is to detect 4031 // global functions that fail to be declared in header files. 4032 if (!FD->isInvalidDecl() && FD->isGlobal() && !isa<CXXMethodDecl>(FD) && 4033 !FD->isMain()) { 4034 bool MissingPrototype = true; 4035 for (const FunctionDecl *Prev = FD->getPreviousDeclaration(); 4036 Prev; Prev = Prev->getPreviousDeclaration()) { 4037 // Ignore any declarations that occur in function or method 4038 // scope, because they aren't visible from the header. 4039 if (Prev->getDeclContext()->isFunctionOrMethod()) 4040 continue; 4041 4042 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 4043 break; 4044 } 4045 4046 if (MissingPrototype) 4047 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 4048 } 4049 4050 if (FnBodyScope) 4051 PushDeclContext(FnBodyScope, FD); 4052 4053 // Check the validity of our function parameters 4054 CheckParmsForFunctionDef(FD); 4055 4056 // Introduce our parameters into the function scope 4057 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 4058 ParmVarDecl *Param = FD->getParamDecl(p); 4059 Param->setOwningFunction(FD); 4060 4061 // If this has an identifier, add it to the scope stack. 4062 if (Param->getIdentifier() && FnBodyScope) 4063 PushOnScopeChains(Param, FnBodyScope); 4064 } 4065 4066 // Checking attributes of current function definition 4067 // dllimport attribute. 4068 if (FD->getAttr<DLLImportAttr>() && 4069 (!FD->getAttr<DLLExportAttr>())) { 4070 // dllimport attribute cannot be applied to definition. 4071 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) { 4072 Diag(FD->getLocation(), 4073 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 4074 << "dllimport"; 4075 FD->setInvalidDecl(); 4076 return DeclPtrTy::make(FD); 4077 } else { 4078 // If a symbol previously declared dllimport is later defined, the 4079 // attribute is ignored in subsequent references, and a warning is 4080 // emitted. 4081 Diag(FD->getLocation(), 4082 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 4083 << FD->getNameAsCString() << "dllimport"; 4084 } 4085 } 4086 return DeclPtrTy::make(FD); 4087} 4088 4089Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) { 4090 return ActOnFinishFunctionBody(D, move(BodyArg), false); 4091} 4092 4093Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg, 4094 bool IsInstantiation) { 4095 Decl *dcl = D.getAs<Decl>(); 4096 Stmt *Body = BodyArg.takeAs<Stmt>(); 4097 4098 FunctionDecl *FD = 0; 4099 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 4100 if (FunTmpl) 4101 FD = FunTmpl->getTemplatedDecl(); 4102 else 4103 FD = dyn_cast_or_null<FunctionDecl>(dcl); 4104 4105 if (FD) { 4106 FD->setBody(Body); 4107 if (FD->isMain()) 4108 // C and C++ allow for main to automagically return 0. 4109 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3. 4110 FD->setHasImplicitReturnZero(true); 4111 else 4112 CheckFallThroughForFunctionDef(FD, Body); 4113 4114 if (!FD->isInvalidDecl()) 4115 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 4116 4117 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) { 4118 // C++ [basic.def.odr]p2: 4119 // [...] A virtual member function is used if it is not pure. [...] 4120 if (Method->isVirtual() && !Method->isPure()) 4121 MarkDeclarationReferenced(Method->getLocation(), Method); 4122 4123 if (!Method->isInlined()) 4124 MaybeMarkVirtualImplicitMembersReferenced(Method->getLocation(), 4125 Method); 4126 } 4127 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 4128 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 4129 assert(MD == getCurMethodDecl() && "Method parsing confused"); 4130 MD->setBody(Body); 4131 CheckFallThroughForFunctionDef(MD, Body); 4132 MD->setEndLoc(Body->getLocEnd()); 4133 4134 if (!MD->isInvalidDecl()) 4135 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 4136 } else { 4137 Body->Destroy(Context); 4138 return DeclPtrTy(); 4139 } 4140 if (!IsInstantiation) 4141 PopDeclContext(); 4142 4143 // Verify and clean out per-function state. 4144 4145 assert(&getLabelMap() == &FunctionLabelMap && "Didn't pop block right?"); 4146 4147 // Check goto/label use. 4148 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 4149 I = FunctionLabelMap.begin(), E = FunctionLabelMap.end(); I != E; ++I) { 4150 LabelStmt *L = I->second; 4151 4152 // Verify that we have no forward references left. If so, there was a goto 4153 // or address of a label taken, but no definition of it. Label fwd 4154 // definitions are indicated with a null substmt. 4155 if (L->getSubStmt() != 0) 4156 continue; 4157 4158 // Emit error. 4159 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName(); 4160 4161 // At this point, we have gotos that use the bogus label. Stitch it into 4162 // the function body so that they aren't leaked and that the AST is well 4163 // formed. 4164 if (Body == 0) { 4165 // The whole function wasn't parsed correctly, just delete this. 4166 L->Destroy(Context); 4167 continue; 4168 } 4169 4170 // Otherwise, the body is valid: we want to stitch the label decl into the 4171 // function somewhere so that it is properly owned and so that the goto 4172 // has a valid target. Do this by creating a new compound stmt with the 4173 // label in it. 4174 4175 // Give the label a sub-statement. 4176 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc())); 4177 4178 CompoundStmt *Compound = isa<CXXTryStmt>(Body) ? 4179 cast<CXXTryStmt>(Body)->getTryBlock() : 4180 cast<CompoundStmt>(Body); 4181 std::vector<Stmt*> Elements(Compound->body_begin(), Compound->body_end()); 4182 Elements.push_back(L); 4183 Compound->setStmts(Context, &Elements[0], Elements.size()); 4184 } 4185 FunctionLabelMap.clear(); 4186 4187 if (!Body) return D; 4188 4189 // Verify that that gotos and switch cases don't jump into scopes illegally. 4190 if (CurFunctionNeedsScopeChecking) 4191 DiagnoseInvalidJumps(Body); 4192 4193 // C++ constructors that have function-try-blocks can't have return 4194 // statements in the handlers of that block. (C++ [except.handle]p14) 4195 // Verify this. 4196 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 4197 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 4198 4199 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) 4200 MarkBaseAndMemberDestructorsReferenced(Destructor); 4201 4202 // If any errors have occurred, clear out any temporaries that may have 4203 // been leftover. This ensures that these temporaries won't be picked up for 4204 // deletion in some later function. 4205 if (PP.getDiagnostics().hasErrorOccurred()) 4206 ExprTemporaries.clear(); 4207 4208 assert(ExprTemporaries.empty() && "Leftover temporaries in function"); 4209 return D; 4210} 4211 4212/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 4213/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 4214NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 4215 IdentifierInfo &II, Scope *S) { 4216 // Before we produce a declaration for an implicitly defined 4217 // function, see whether there was a locally-scoped declaration of 4218 // this name as a function or variable. If so, use that 4219 // (non-visible) declaration, and complain about it. 4220 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4221 = LocallyScopedExternalDecls.find(&II); 4222 if (Pos != LocallyScopedExternalDecls.end()) { 4223 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 4224 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 4225 return Pos->second; 4226 } 4227 4228 // Extension in C99. Legal in C90, but warn about it. 4229 if (II.getName().startswith("__builtin_")) 4230 Diag(Loc, diag::warn_builtin_unknown) << &II; 4231 else if (getLangOptions().C99) 4232 Diag(Loc, diag::ext_implicit_function_decl) << &II; 4233 else 4234 Diag(Loc, diag::warn_implicit_function_decl) << &II; 4235 4236 // Set a Declarator for the implicit definition: int foo(); 4237 const char *Dummy; 4238 DeclSpec DS; 4239 unsigned DiagID; 4240 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 4241 Error = Error; // Silence warning. 4242 assert(!Error && "Error setting up implicit decl!"); 4243 Declarator D(DS, Declarator::BlockContext); 4244 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0, 4245 0, 0, false, SourceLocation(), 4246 false, 0,0,0, Loc, Loc, D), 4247 SourceLocation()); 4248 D.SetIdentifier(&II, Loc); 4249 4250 // Insert this function into translation-unit scope. 4251 4252 DeclContext *PrevDC = CurContext; 4253 CurContext = Context.getTranslationUnitDecl(); 4254 4255 FunctionDecl *FD = 4256 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>()); 4257 FD->setImplicit(); 4258 4259 CurContext = PrevDC; 4260 4261 AddKnownFunctionAttributes(FD); 4262 4263 return FD; 4264} 4265 4266/// \brief Adds any function attributes that we know a priori based on 4267/// the declaration of this function. 4268/// 4269/// These attributes can apply both to implicitly-declared builtins 4270/// (like __builtin___printf_chk) or to library-declared functions 4271/// like NSLog or printf. 4272void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 4273 if (FD->isInvalidDecl()) 4274 return; 4275 4276 // If this is a built-in function, map its builtin attributes to 4277 // actual attributes. 4278 if (unsigned BuiltinID = FD->getBuiltinID()) { 4279 // Handle printf-formatting attributes. 4280 unsigned FormatIdx; 4281 bool HasVAListArg; 4282 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 4283 if (!FD->getAttr<FormatAttr>()) 4284 FD->addAttr(::new (Context) FormatAttr("printf", FormatIdx + 1, 4285 HasVAListArg ? 0 : FormatIdx + 2)); 4286 } 4287 4288 // Mark const if we don't care about errno and that is the only 4289 // thing preventing the function from being const. This allows 4290 // IRgen to use LLVM intrinsics for such functions. 4291 if (!getLangOptions().MathErrno && 4292 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 4293 if (!FD->getAttr<ConstAttr>()) 4294 FD->addAttr(::new (Context) ConstAttr()); 4295 } 4296 4297 if (Context.BuiltinInfo.isNoReturn(BuiltinID)) 4298 FD->addAttr(::new (Context) NoReturnAttr()); 4299 } 4300 4301 IdentifierInfo *Name = FD->getIdentifier(); 4302 if (!Name) 4303 return; 4304 if ((!getLangOptions().CPlusPlus && 4305 FD->getDeclContext()->isTranslationUnit()) || 4306 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 4307 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 4308 LinkageSpecDecl::lang_c)) { 4309 // Okay: this could be a libc/libm/Objective-C function we know 4310 // about. 4311 } else 4312 return; 4313 4314 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) { 4315 // FIXME: NSLog and NSLogv should be target specific 4316 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) { 4317 // FIXME: We known better than our headers. 4318 const_cast<FormatAttr *>(Format)->setType("printf"); 4319 } else 4320 FD->addAttr(::new (Context) FormatAttr("printf", 1, 4321 Name->isStr("NSLogv") ? 0 : 2)); 4322 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 4323 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 4324 // target-specific builtins, perhaps? 4325 if (!FD->getAttr<FormatAttr>()) 4326 FD->addAttr(::new (Context) FormatAttr("printf", 2, 4327 Name->isStr("vasprintf") ? 0 : 3)); 4328 } 4329} 4330 4331TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 4332 TypeSourceInfo *TInfo) { 4333 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 4334 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 4335 4336 if (!TInfo) { 4337 assert(D.isInvalidType() && "no declarator info for valid type"); 4338 TInfo = Context.getTrivialTypeSourceInfo(T); 4339 } 4340 4341 // Scope manipulation handled by caller. 4342 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 4343 D.getIdentifierLoc(), 4344 D.getIdentifier(), 4345 TInfo); 4346 4347 if (const TagType *TT = T->getAs<TagType>()) { 4348 TagDecl *TD = TT->getDecl(); 4349 4350 // If the TagDecl that the TypedefDecl points to is an anonymous decl 4351 // keep track of the TypedefDecl. 4352 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl()) 4353 TD->setTypedefForAnonDecl(NewTD); 4354 } 4355 4356 if (D.isInvalidType()) 4357 NewTD->setInvalidDecl(); 4358 return NewTD; 4359} 4360 4361 4362/// \brief Determine whether a tag with a given kind is acceptable 4363/// as a redeclaration of the given tag declaration. 4364/// 4365/// \returns true if the new tag kind is acceptable, false otherwise. 4366bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 4367 TagDecl::TagKind NewTag, 4368 SourceLocation NewTagLoc, 4369 const IdentifierInfo &Name) { 4370 // C++ [dcl.type.elab]p3: 4371 // The class-key or enum keyword present in the 4372 // elaborated-type-specifier shall agree in kind with the 4373 // declaration to which the name in theelaborated-type-specifier 4374 // refers. This rule also applies to the form of 4375 // elaborated-type-specifier that declares a class-name or 4376 // friend class since it can be construed as referring to the 4377 // definition of the class. Thus, in any 4378 // elaborated-type-specifier, the enum keyword shall be used to 4379 // refer to an enumeration (7.2), the union class-keyshall be 4380 // used to refer to a union (clause 9), and either the class or 4381 // struct class-key shall be used to refer to a class (clause 9) 4382 // declared using the class or struct class-key. 4383 TagDecl::TagKind OldTag = Previous->getTagKind(); 4384 if (OldTag == NewTag) 4385 return true; 4386 4387 if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) && 4388 (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) { 4389 // Warn about the struct/class tag mismatch. 4390 bool isTemplate = false; 4391 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 4392 isTemplate = Record->getDescribedClassTemplate(); 4393 4394 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 4395 << (NewTag == TagDecl::TK_class) 4396 << isTemplate << &Name 4397 << CodeModificationHint::CreateReplacement(SourceRange(NewTagLoc), 4398 OldTag == TagDecl::TK_class? "class" : "struct"); 4399 Diag(Previous->getLocation(), diag::note_previous_use); 4400 return true; 4401 } 4402 return false; 4403} 4404 4405/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 4406/// former case, Name will be non-null. In the later case, Name will be null. 4407/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 4408/// reference/declaration/definition of a tag. 4409Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 4410 SourceLocation KWLoc, const CXXScopeSpec &SS, 4411 IdentifierInfo *Name, SourceLocation NameLoc, 4412 AttributeList *Attr, AccessSpecifier AS, 4413 MultiTemplateParamsArg TemplateParameterLists, 4414 bool &OwnedDecl, bool &IsDependent) { 4415 // If this is not a definition, it must have a name. 4416 assert((Name != 0 || TUK == TUK_Definition) && 4417 "Nameless record must be a definition!"); 4418 4419 OwnedDecl = false; 4420 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec); 4421 4422 // FIXME: Check explicit specializations more carefully. 4423 bool isExplicitSpecialization = false; 4424 if (TUK != TUK_Reference) { 4425 if (TemplateParameterList *TemplateParams 4426 = MatchTemplateParametersToScopeSpecifier(KWLoc, SS, 4427 (TemplateParameterList**)TemplateParameterLists.get(), 4428 TemplateParameterLists.size(), 4429 isExplicitSpecialization)) { 4430 if (TemplateParams->size() > 0) { 4431 // This is a declaration or definition of a class template (which may 4432 // be a member of another template). 4433 OwnedDecl = false; 4434 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 4435 SS, Name, NameLoc, Attr, 4436 TemplateParams, 4437 AS); 4438 TemplateParameterLists.release(); 4439 return Result.get(); 4440 } else { 4441 // The "template<>" header is extraneous. 4442 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 4443 << ElaboratedType::getNameForTagKind(Kind) << Name; 4444 isExplicitSpecialization = true; 4445 } 4446 } 4447 4448 TemplateParameterLists.release(); 4449 } 4450 4451 DeclContext *SearchDC = CurContext; 4452 DeclContext *DC = CurContext; 4453 bool isStdBadAlloc = false; 4454 bool Invalid = false; 4455 4456 RedeclarationKind Redecl = (TUK != TUK_Reference ? ForRedeclaration 4457 : NotForRedeclaration); 4458 4459 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 4460 4461 if (Name && SS.isNotEmpty()) { 4462 // We have a nested-name tag ('struct foo::bar'). 4463 4464 // Check for invalid 'foo::'. 4465 if (SS.isInvalid()) { 4466 Name = 0; 4467 goto CreateNewDecl; 4468 } 4469 4470 // If this is a friend or a reference to a class in a dependent 4471 // context, don't try to make a decl for it. 4472 if (TUK == TUK_Friend || TUK == TUK_Reference) { 4473 DC = computeDeclContext(SS, false); 4474 if (!DC) { 4475 IsDependent = true; 4476 return DeclPtrTy(); 4477 } 4478 } 4479 4480 if (RequireCompleteDeclContext(SS)) 4481 return DeclPtrTy::make((Decl *)0); 4482 4483 DC = computeDeclContext(SS, true); 4484 SearchDC = DC; 4485 // Look-up name inside 'foo::'. 4486 LookupQualifiedName(Previous, DC); 4487 4488 if (Previous.isAmbiguous()) 4489 return DeclPtrTy(); 4490 4491 // A tag 'foo::bar' must already exist. 4492 if (Previous.empty()) { 4493 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange(); 4494 Name = 0; 4495 Invalid = true; 4496 goto CreateNewDecl; 4497 } 4498 } else if (Name) { 4499 // If this is a named struct, check to see if there was a previous forward 4500 // declaration or definition. 4501 // FIXME: We're looking into outer scopes here, even when we 4502 // shouldn't be. Doing so can result in ambiguities that we 4503 // shouldn't be diagnosing. 4504 LookupName(Previous, S); 4505 4506 // Note: there used to be some attempt at recovery here. 4507 if (Previous.isAmbiguous()) 4508 return DeclPtrTy(); 4509 4510 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) { 4511 // FIXME: This makes sure that we ignore the contexts associated 4512 // with C structs, unions, and enums when looking for a matching 4513 // tag declaration or definition. See the similar lookup tweak 4514 // in Sema::LookupName; is there a better way to deal with this? 4515 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 4516 SearchDC = SearchDC->getParent(); 4517 } 4518 } 4519 4520 if (Previous.isSingleResult() && 4521 Previous.getFoundDecl()->isTemplateParameter()) { 4522 // Maybe we will complain about the shadowed template parameter. 4523 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 4524 // Just pretend that we didn't see the previous declaration. 4525 Previous.clear(); 4526 } 4527 4528 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace && 4529 DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) { 4530 // This is a declaration of or a reference to "std::bad_alloc". 4531 isStdBadAlloc = true; 4532 4533 if (Previous.empty() && StdBadAlloc) { 4534 // std::bad_alloc has been implicitly declared (but made invisible to 4535 // name lookup). Fill in this implicit declaration as the previous 4536 // declaration, so that the declarations get chained appropriately. 4537 Previous.addDecl(StdBadAlloc); 4538 } 4539 } 4540 4541 if (!Previous.empty()) { 4542 assert(Previous.isSingleResult()); 4543 NamedDecl *PrevDecl = Previous.getFoundDecl(); 4544 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 4545 // If this is a use of a previous tag, or if the tag is already declared 4546 // in the same scope (so that the definition/declaration completes or 4547 // rementions the tag), reuse the decl. 4548 if (TUK == TUK_Reference || TUK == TUK_Friend || 4549 isDeclInScope(PrevDecl, SearchDC, S)) { 4550 // Make sure that this wasn't declared as an enum and now used as a 4551 // struct or something similar. 4552 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) { 4553 bool SafeToContinue 4554 = (PrevTagDecl->getTagKind() != TagDecl::TK_enum && 4555 Kind != TagDecl::TK_enum); 4556 if (SafeToContinue) 4557 Diag(KWLoc, diag::err_use_with_wrong_tag) 4558 << Name 4559 << CodeModificationHint::CreateReplacement(SourceRange(KWLoc), 4560 PrevTagDecl->getKindName()); 4561 else 4562 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 4563 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 4564 4565 if (SafeToContinue) 4566 Kind = PrevTagDecl->getTagKind(); 4567 else { 4568 // Recover by making this an anonymous redefinition. 4569 Name = 0; 4570 Previous.clear(); 4571 Invalid = true; 4572 } 4573 } 4574 4575 if (!Invalid) { 4576 // If this is a use, just return the declaration we found. 4577 4578 // FIXME: In the future, return a variant or some other clue 4579 // for the consumer of this Decl to know it doesn't own it. 4580 // For our current ASTs this shouldn't be a problem, but will 4581 // need to be changed with DeclGroups. 4582 if (TUK == TUK_Reference || TUK == TUK_Friend) 4583 return DeclPtrTy::make(PrevTagDecl); 4584 4585 // Diagnose attempts to redefine a tag. 4586 if (TUK == TUK_Definition) { 4587 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) { 4588 // If we're defining a specialization and the previous definition 4589 // is from an implicit instantiation, don't emit an error 4590 // here; we'll catch this in the general case below. 4591 if (!isExplicitSpecialization || 4592 !isa<CXXRecordDecl>(Def) || 4593 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind() 4594 == TSK_ExplicitSpecialization) { 4595 Diag(NameLoc, diag::err_redefinition) << Name; 4596 Diag(Def->getLocation(), diag::note_previous_definition); 4597 // If this is a redefinition, recover by making this 4598 // struct be anonymous, which will make any later 4599 // references get the previous definition. 4600 Name = 0; 4601 Previous.clear(); 4602 Invalid = true; 4603 } 4604 } else { 4605 // If the type is currently being defined, complain 4606 // about a nested redefinition. 4607 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 4608 if (Tag->isBeingDefined()) { 4609 Diag(NameLoc, diag::err_nested_redefinition) << Name; 4610 Diag(PrevTagDecl->getLocation(), 4611 diag::note_previous_definition); 4612 Name = 0; 4613 Previous.clear(); 4614 Invalid = true; 4615 } 4616 } 4617 4618 // Okay, this is definition of a previously declared or referenced 4619 // tag PrevDecl. We're going to create a new Decl for it. 4620 } 4621 } 4622 // If we get here we have (another) forward declaration or we 4623 // have a definition. Just create a new decl. 4624 4625 } else { 4626 // If we get here, this is a definition of a new tag type in a nested 4627 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 4628 // new decl/type. We set PrevDecl to NULL so that the entities 4629 // have distinct types. 4630 Previous.clear(); 4631 } 4632 // If we get here, we're going to create a new Decl. If PrevDecl 4633 // is non-NULL, it's a definition of the tag declared by 4634 // PrevDecl. If it's NULL, we have a new definition. 4635 } else { 4636 // PrevDecl is a namespace, template, or anything else 4637 // that lives in the IDNS_Tag identifier namespace. 4638 if (isDeclInScope(PrevDecl, SearchDC, S)) { 4639 // The tag name clashes with a namespace name, issue an error and 4640 // recover by making this tag be anonymous. 4641 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 4642 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 4643 Name = 0; 4644 Previous.clear(); 4645 Invalid = true; 4646 } else { 4647 // The existing declaration isn't relevant to us; we're in a 4648 // new scope, so clear out the previous declaration. 4649 Previous.clear(); 4650 } 4651 } 4652 } else if (TUK == TUK_Reference && SS.isEmpty() && Name) { 4653 // C++ [basic.scope.pdecl]p5: 4654 // -- for an elaborated-type-specifier of the form 4655 // 4656 // class-key identifier 4657 // 4658 // if the elaborated-type-specifier is used in the 4659 // decl-specifier-seq or parameter-declaration-clause of a 4660 // function defined in namespace scope, the identifier is 4661 // declared as a class-name in the namespace that contains 4662 // the declaration; otherwise, except as a friend 4663 // declaration, the identifier is declared in the smallest 4664 // non-class, non-function-prototype scope that contains the 4665 // declaration. 4666 // 4667 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 4668 // C structs and unions. 4669 // 4670 // It is an error in C++ to declare (rather than define) an enum 4671 // type, including via an elaborated type specifier. We'll 4672 // diagnose that later; for now, declare the enum in the same 4673 // scope as we would have picked for any other tag type. 4674 // 4675 // GNU C also supports this behavior as part of its incomplete 4676 // enum types extension, while GNU C++ does not. 4677 // 4678 // Find the context where we'll be declaring the tag. 4679 // FIXME: We would like to maintain the current DeclContext as the 4680 // lexical context, 4681 while (SearchDC->isRecord()) 4682 SearchDC = SearchDC->getParent(); 4683 4684 // Find the scope where we'll be declaring the tag. 4685 while (S->isClassScope() || 4686 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) || 4687 ((S->getFlags() & Scope::DeclScope) == 0) || 4688 (S->getEntity() && 4689 ((DeclContext *)S->getEntity())->isTransparentContext())) 4690 S = S->getParent(); 4691 4692 } else if (TUK == TUK_Friend && SS.isEmpty() && Name) { 4693 // C++ [namespace.memdef]p3: 4694 // If a friend declaration in a non-local class first declares a 4695 // class or function, the friend class or function is a member of 4696 // the innermost enclosing namespace. 4697 while (!SearchDC->isFileContext()) 4698 SearchDC = SearchDC->getParent(); 4699 4700 // The entity of a decl scope is a DeclContext; see PushDeclContext. 4701 while (S->getEntity() != SearchDC) 4702 S = S->getParent(); 4703 } 4704 4705CreateNewDecl: 4706 4707 TagDecl *PrevDecl = 0; 4708 if (Previous.isSingleResult()) 4709 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 4710 4711 // If there is an identifier, use the location of the identifier as the 4712 // location of the decl, otherwise use the location of the struct/union 4713 // keyword. 4714 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 4715 4716 // Otherwise, create a new declaration. If there is a previous 4717 // declaration of the same entity, the two will be linked via 4718 // PrevDecl. 4719 TagDecl *New; 4720 4721 if (Kind == TagDecl::TK_enum) { 4722 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 4723 // enum X { A, B, C } D; D should chain to X. 4724 New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc, 4725 cast_or_null<EnumDecl>(PrevDecl)); 4726 // If this is an undefined enum, warn. 4727 if (TUK != TUK_Definition && !Invalid) { 4728 unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum 4729 : diag::ext_forward_ref_enum; 4730 Diag(Loc, DK); 4731 } 4732 } else { 4733 // struct/union/class 4734 4735 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 4736 // struct X { int A; } D; D should chain to X. 4737 if (getLangOptions().CPlusPlus) { 4738 // FIXME: Look for a way to use RecordDecl for simple structs. 4739 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc, 4740 cast_or_null<CXXRecordDecl>(PrevDecl)); 4741 4742 if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit())) 4743 StdBadAlloc = cast<CXXRecordDecl>(New); 4744 } else 4745 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc, 4746 cast_or_null<RecordDecl>(PrevDecl)); 4747 } 4748 4749 if (Kind != TagDecl::TK_enum) { 4750 // Handle #pragma pack: if the #pragma pack stack has non-default 4751 // alignment, make up a packed attribute for this decl. These 4752 // attributes are checked when the ASTContext lays out the 4753 // structure. 4754 // 4755 // It is important for implementing the correct semantics that this 4756 // happen here (in act on tag decl). The #pragma pack stack is 4757 // maintained as a result of parser callbacks which can occur at 4758 // many points during the parsing of a struct declaration (because 4759 // the #pragma tokens are effectively skipped over during the 4760 // parsing of the struct). 4761 if (unsigned Alignment = getPragmaPackAlignment()) 4762 New->addAttr(::new (Context) PragmaPackAttr(Alignment * 8)); 4763 } 4764 4765 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) { 4766 // C++ [dcl.typedef]p3: 4767 // [...] Similarly, in a given scope, a class or enumeration 4768 // shall not be declared with the same name as a typedef-name 4769 // that is declared in that scope and refers to a type other 4770 // than the class or enumeration itself. 4771 LookupResult Lookup(*this, Name, NameLoc, LookupOrdinaryName, 4772 ForRedeclaration); 4773 LookupName(Lookup, S); 4774 TypedefDecl *PrevTypedef = Lookup.getAsSingle<TypedefDecl>(); 4775 NamedDecl *PrevTypedefNamed = PrevTypedef; 4776 if (PrevTypedef && isDeclInScope(PrevTypedefNamed, SearchDC, S) && 4777 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) != 4778 Context.getCanonicalType(Context.getTypeDeclType(New))) { 4779 Diag(Loc, diag::err_tag_definition_of_typedef) 4780 << Context.getTypeDeclType(New) 4781 << PrevTypedef->getUnderlyingType(); 4782 Diag(PrevTypedef->getLocation(), diag::note_previous_definition); 4783 Invalid = true; 4784 } 4785 } 4786 4787 // If this is a specialization of a member class (of a class template), 4788 // check the specialization. 4789 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 4790 Invalid = true; 4791 4792 if (Invalid) 4793 New->setInvalidDecl(); 4794 4795 if (Attr) 4796 ProcessDeclAttributeList(S, New, Attr); 4797 4798 // If we're declaring or defining a tag in function prototype scope 4799 // in C, note that this type can only be used within the function. 4800 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus) 4801 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 4802 4803 // Set the lexical context. If the tag has a C++ scope specifier, the 4804 // lexical context will be different from the semantic context. 4805 New->setLexicalDeclContext(CurContext); 4806 4807 // Mark this as a friend decl if applicable. 4808 if (TUK == TUK_Friend) 4809 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty()); 4810 4811 // Set the access specifier. 4812 if (!Invalid && TUK != TUK_Friend) 4813 SetMemberAccessSpecifier(New, PrevDecl, AS); 4814 4815 if (TUK == TUK_Definition) 4816 New->startDefinition(); 4817 4818 // If this has an identifier, add it to the scope stack. 4819 if (TUK == TUK_Friend) { 4820 // We might be replacing an existing declaration in the lookup tables; 4821 // if so, borrow its access specifier. 4822 if (PrevDecl) 4823 New->setAccess(PrevDecl->getAccess()); 4824 4825 // Friend tag decls are visible in fairly strange ways. 4826 if (!CurContext->isDependentContext()) { 4827 DeclContext *DC = New->getDeclContext()->getLookupContext(); 4828 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false); 4829 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 4830 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 4831 } 4832 } else if (Name) { 4833 S = getNonFieldDeclScope(S); 4834 PushOnScopeChains(New, S); 4835 } else { 4836 CurContext->addDecl(New); 4837 } 4838 4839 // If this is the C FILE type, notify the AST context. 4840 if (IdentifierInfo *II = New->getIdentifier()) 4841 if (!New->isInvalidDecl() && 4842 New->getDeclContext()->getLookupContext()->isTranslationUnit() && 4843 II->isStr("FILE")) 4844 Context.setFILEDecl(New); 4845 4846 OwnedDecl = true; 4847 return DeclPtrTy::make(New); 4848} 4849 4850void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) { 4851 AdjustDeclIfTemplate(TagD); 4852 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 4853 4854 // Enter the tag context. 4855 PushDeclContext(S, Tag); 4856 4857 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) { 4858 FieldCollector->StartClass(); 4859 4860 if (Record->getIdentifier()) { 4861 // C++ [class]p2: 4862 // [...] The class-name is also inserted into the scope of the 4863 // class itself; this is known as the injected-class-name. For 4864 // purposes of access checking, the injected-class-name is treated 4865 // as if it were a public member name. 4866 CXXRecordDecl *InjectedClassName 4867 = CXXRecordDecl::Create(Context, Record->getTagKind(), 4868 CurContext, Record->getLocation(), 4869 Record->getIdentifier(), 4870 Record->getTagKeywordLoc(), 4871 Record); 4872 InjectedClassName->setImplicit(); 4873 InjectedClassName->setAccess(AS_public); 4874 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 4875 InjectedClassName->setDescribedClassTemplate(Template); 4876 PushOnScopeChains(InjectedClassName, S); 4877 assert(InjectedClassName->isInjectedClassName() && 4878 "Broken injected-class-name"); 4879 } 4880 } 4881} 4882 4883void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD, 4884 SourceLocation RBraceLoc) { 4885 AdjustDeclIfTemplate(TagD); 4886 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 4887 Tag->setRBraceLoc(RBraceLoc); 4888 4889 if (isa<CXXRecordDecl>(Tag)) 4890 FieldCollector->FinishClass(); 4891 4892 // Exit this scope of this tag's definition. 4893 PopDeclContext(); 4894 4895 // Notify the consumer that we've defined a tag. 4896 Consumer.HandleTagDeclDefinition(Tag); 4897} 4898 4899// Note that FieldName may be null for anonymous bitfields. 4900bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 4901 QualType FieldTy, const Expr *BitWidth, 4902 bool *ZeroWidth) { 4903 // Default to true; that shouldn't confuse checks for emptiness 4904 if (ZeroWidth) 4905 *ZeroWidth = true; 4906 4907 // C99 6.7.2.1p4 - verify the field type. 4908 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 4909 if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) { 4910 // Handle incomplete types with specific error. 4911 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 4912 return true; 4913 if (FieldName) 4914 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 4915 << FieldName << FieldTy << BitWidth->getSourceRange(); 4916 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 4917 << FieldTy << BitWidth->getSourceRange(); 4918 } 4919 4920 // If the bit-width is type- or value-dependent, don't try to check 4921 // it now. 4922 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 4923 return false; 4924 4925 llvm::APSInt Value; 4926 if (VerifyIntegerConstantExpression(BitWidth, &Value)) 4927 return true; 4928 4929 if (Value != 0 && ZeroWidth) 4930 *ZeroWidth = false; 4931 4932 // Zero-width bitfield is ok for anonymous field. 4933 if (Value == 0 && FieldName) 4934 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 4935 4936 if (Value.isSigned() && Value.isNegative()) { 4937 if (FieldName) 4938 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 4939 << FieldName << Value.toString(10); 4940 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 4941 << Value.toString(10); 4942 } 4943 4944 if (!FieldTy->isDependentType()) { 4945 uint64_t TypeSize = Context.getTypeSize(FieldTy); 4946 if (Value.getZExtValue() > TypeSize) { 4947 if (FieldName) 4948 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 4949 << FieldName << (unsigned)TypeSize; 4950 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 4951 << (unsigned)TypeSize; 4952 } 4953 } 4954 4955 return false; 4956} 4957 4958/// ActOnField - Each field of a struct/union/class is passed into this in order 4959/// to create a FieldDecl object for it. 4960Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD, 4961 SourceLocation DeclStart, 4962 Declarator &D, ExprTy *BitfieldWidth) { 4963 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()), 4964 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 4965 AS_public); 4966 return DeclPtrTy::make(Res); 4967} 4968 4969/// HandleField - Analyze a field of a C struct or a C++ data member. 4970/// 4971FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 4972 SourceLocation DeclStart, 4973 Declarator &D, Expr *BitWidth, 4974 AccessSpecifier AS) { 4975 IdentifierInfo *II = D.getIdentifier(); 4976 SourceLocation Loc = DeclStart; 4977 if (II) Loc = D.getIdentifierLoc(); 4978 4979 TypeSourceInfo *TInfo = 0; 4980 QualType T = GetTypeForDeclarator(D, S, &TInfo); 4981 if (getLangOptions().CPlusPlus) 4982 CheckExtraCXXDefaultArguments(D); 4983 4984 DiagnoseFunctionSpecifiers(D); 4985 4986 if (D.getDeclSpec().isThreadSpecified()) 4987 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 4988 4989 NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName, 4990 ForRedeclaration); 4991 4992 if (PrevDecl && PrevDecl->isTemplateParameter()) { 4993 // Maybe we will complain about the shadowed template parameter. 4994 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 4995 // Just pretend that we didn't see the previous declaration. 4996 PrevDecl = 0; 4997 } 4998 4999 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 5000 PrevDecl = 0; 5001 5002 bool Mutable 5003 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 5004 SourceLocation TSSL = D.getSourceRange().getBegin(); 5005 FieldDecl *NewFD 5006 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL, 5007 AS, PrevDecl, &D); 5008 if (NewFD->isInvalidDecl() && PrevDecl) { 5009 // Don't introduce NewFD into scope; there's already something 5010 // with the same name in the same scope. 5011 } else if (II) { 5012 PushOnScopeChains(NewFD, S); 5013 } else 5014 Record->addDecl(NewFD); 5015 5016 return NewFD; 5017} 5018 5019/// \brief Build a new FieldDecl and check its well-formedness. 5020/// 5021/// This routine builds a new FieldDecl given the fields name, type, 5022/// record, etc. \p PrevDecl should refer to any previous declaration 5023/// with the same name and in the same scope as the field to be 5024/// created. 5025/// 5026/// \returns a new FieldDecl. 5027/// 5028/// \todo The Declarator argument is a hack. It will be removed once 5029FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 5030 TypeSourceInfo *TInfo, 5031 RecordDecl *Record, SourceLocation Loc, 5032 bool Mutable, Expr *BitWidth, 5033 SourceLocation TSSL, 5034 AccessSpecifier AS, NamedDecl *PrevDecl, 5035 Declarator *D) { 5036 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5037 bool InvalidDecl = false; 5038 if (D) InvalidDecl = D->isInvalidType(); 5039 5040 // If we receive a broken type, recover by assuming 'int' and 5041 // marking this declaration as invalid. 5042 if (T.isNull()) { 5043 InvalidDecl = true; 5044 T = Context.IntTy; 5045 } 5046 5047 QualType EltTy = Context.getBaseElementType(T); 5048 if (!EltTy->isDependentType() && 5049 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) 5050 InvalidDecl = true; 5051 5052 // C99 6.7.2.1p8: A member of a structure or union may have any type other 5053 // than a variably modified type. 5054 if (!InvalidDecl && T->isVariablyModifiedType()) { 5055 bool SizeIsNegative; 5056 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context, 5057 SizeIsNegative); 5058 if (!FixedTy.isNull()) { 5059 Diag(Loc, diag::warn_illegal_constant_array_size); 5060 T = FixedTy; 5061 } else { 5062 if (SizeIsNegative) 5063 Diag(Loc, diag::err_typecheck_negative_array_size); 5064 else 5065 Diag(Loc, diag::err_typecheck_field_variable_size); 5066 InvalidDecl = true; 5067 } 5068 } 5069 5070 // Fields can not have abstract class types 5071 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 5072 diag::err_abstract_type_in_decl, 5073 AbstractFieldType)) 5074 InvalidDecl = true; 5075 5076 bool ZeroWidth = false; 5077 // If this is declared as a bit-field, check the bit-field. 5078 if (!InvalidDecl && BitWidth && 5079 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) { 5080 InvalidDecl = true; 5081 DeleteExpr(BitWidth); 5082 BitWidth = 0; 5083 ZeroWidth = false; 5084 } 5085 5086 FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo, 5087 BitWidth, Mutable); 5088 if (InvalidDecl) 5089 NewFD->setInvalidDecl(); 5090 5091 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 5092 Diag(Loc, diag::err_duplicate_member) << II; 5093 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 5094 NewFD->setInvalidDecl(); 5095 } 5096 5097 if (getLangOptions().CPlusPlus) { 5098 CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record); 5099 5100 if (!T->isPODType()) 5101 CXXRecord->setPOD(false); 5102 if (!ZeroWidth) 5103 CXXRecord->setEmpty(false); 5104 5105 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 5106 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 5107 5108 if (!RDecl->hasTrivialConstructor()) 5109 CXXRecord->setHasTrivialConstructor(false); 5110 if (!RDecl->hasTrivialCopyConstructor()) 5111 CXXRecord->setHasTrivialCopyConstructor(false); 5112 if (!RDecl->hasTrivialCopyAssignment()) 5113 CXXRecord->setHasTrivialCopyAssignment(false); 5114 if (!RDecl->hasTrivialDestructor()) 5115 CXXRecord->setHasTrivialDestructor(false); 5116 5117 // C++ 9.5p1: An object of a class with a non-trivial 5118 // constructor, a non-trivial copy constructor, a non-trivial 5119 // destructor, or a non-trivial copy assignment operator 5120 // cannot be a member of a union, nor can an array of such 5121 // objects. 5122 // TODO: C++0x alters this restriction significantly. 5123 if (Record->isUnion()) { 5124 // We check for copy constructors before constructors 5125 // because otherwise we'll never get complaints about 5126 // copy constructors. 5127 5128 const CXXSpecialMember invalid = (CXXSpecialMember) -1; 5129 5130 CXXSpecialMember member; 5131 if (!RDecl->hasTrivialCopyConstructor()) 5132 member = CXXCopyConstructor; 5133 else if (!RDecl->hasTrivialConstructor()) 5134 member = CXXDefaultConstructor; 5135 else if (!RDecl->hasTrivialCopyAssignment()) 5136 member = CXXCopyAssignment; 5137 else if (!RDecl->hasTrivialDestructor()) 5138 member = CXXDestructor; 5139 else 5140 member = invalid; 5141 5142 if (member != invalid) { 5143 Diag(Loc, diag::err_illegal_union_member) << Name << member; 5144 DiagnoseNontrivial(RT, member); 5145 NewFD->setInvalidDecl(); 5146 } 5147 } 5148 } 5149 } 5150 5151 // FIXME: We need to pass in the attributes given an AST 5152 // representation, not a parser representation. 5153 if (D) 5154 // FIXME: What to pass instead of TUScope? 5155 ProcessDeclAttributes(TUScope, NewFD, *D); 5156 5157 if (T.isObjCGCWeak()) 5158 Diag(Loc, diag::warn_attribute_weak_on_field); 5159 5160 NewFD->setAccess(AS); 5161 5162 // C++ [dcl.init.aggr]p1: 5163 // An aggregate is an array or a class (clause 9) with [...] no 5164 // private or protected non-static data members (clause 11). 5165 // A POD must be an aggregate. 5166 if (getLangOptions().CPlusPlus && 5167 (AS == AS_private || AS == AS_protected)) { 5168 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 5169 CXXRecord->setAggregate(false); 5170 CXXRecord->setPOD(false); 5171 } 5172 5173 return NewFD; 5174} 5175 5176/// DiagnoseNontrivial - Given that a class has a non-trivial 5177/// special member, figure out why. 5178void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) { 5179 QualType QT(T, 0U); 5180 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl()); 5181 5182 // Check whether the member was user-declared. 5183 switch (member) { 5184 case CXXDefaultConstructor: 5185 if (RD->hasUserDeclaredConstructor()) { 5186 typedef CXXRecordDecl::ctor_iterator ctor_iter; 5187 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){ 5188 const FunctionDecl *body = 0; 5189 ci->getBody(body); 5190 if (!body || 5191 !cast<CXXConstructorDecl>(body)->isImplicitlyDefined(Context)) { 5192 SourceLocation CtorLoc = ci->getLocation(); 5193 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 5194 return; 5195 } 5196 } 5197 5198 assert(0 && "found no user-declared constructors"); 5199 return; 5200 } 5201 break; 5202 5203 case CXXCopyConstructor: 5204 if (RD->hasUserDeclaredCopyConstructor()) { 5205 SourceLocation CtorLoc = 5206 RD->getCopyConstructor(Context, 0)->getLocation(); 5207 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 5208 return; 5209 } 5210 break; 5211 5212 case CXXCopyAssignment: 5213 if (RD->hasUserDeclaredCopyAssignment()) { 5214 // FIXME: this should use the location of the copy 5215 // assignment, not the type. 5216 SourceLocation TyLoc = RD->getSourceRange().getBegin(); 5217 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member; 5218 return; 5219 } 5220 break; 5221 5222 case CXXDestructor: 5223 if (RD->hasUserDeclaredDestructor()) { 5224 SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation(); 5225 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member; 5226 return; 5227 } 5228 break; 5229 } 5230 5231 typedef CXXRecordDecl::base_class_iterator base_iter; 5232 5233 // Virtual bases and members inhibit trivial copying/construction, 5234 // but not trivial destruction. 5235 if (member != CXXDestructor) { 5236 // Check for virtual bases. vbases includes indirect virtual bases, 5237 // so we just iterate through the direct bases. 5238 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) 5239 if (bi->isVirtual()) { 5240 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 5241 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1; 5242 return; 5243 } 5244 5245 // Check for virtual methods. 5246 typedef CXXRecordDecl::method_iterator meth_iter; 5247 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me; 5248 ++mi) { 5249 if (mi->isVirtual()) { 5250 SourceLocation MLoc = mi->getSourceRange().getBegin(); 5251 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0; 5252 return; 5253 } 5254 } 5255 } 5256 5257 bool (CXXRecordDecl::*hasTrivial)() const; 5258 switch (member) { 5259 case CXXDefaultConstructor: 5260 hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break; 5261 case CXXCopyConstructor: 5262 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break; 5263 case CXXCopyAssignment: 5264 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break; 5265 case CXXDestructor: 5266 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break; 5267 default: 5268 assert(0 && "unexpected special member"); return; 5269 } 5270 5271 // Check for nontrivial bases (and recurse). 5272 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) { 5273 const RecordType *BaseRT = bi->getType()->getAs<RecordType>(); 5274 assert(BaseRT && "Don't know how to handle dependent bases"); 5275 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl()); 5276 if (!(BaseRecTy->*hasTrivial)()) { 5277 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 5278 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member; 5279 DiagnoseNontrivial(BaseRT, member); 5280 return; 5281 } 5282 } 5283 5284 // Check for nontrivial members (and recurse). 5285 typedef RecordDecl::field_iterator field_iter; 5286 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe; 5287 ++fi) { 5288 QualType EltTy = Context.getBaseElementType((*fi)->getType()); 5289 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) { 5290 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl()); 5291 5292 if (!(EltRD->*hasTrivial)()) { 5293 SourceLocation FLoc = (*fi)->getLocation(); 5294 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member; 5295 DiagnoseNontrivial(EltRT, member); 5296 return; 5297 } 5298 } 5299 } 5300 5301 assert(0 && "found no explanation for non-trivial member"); 5302} 5303 5304/// TranslateIvarVisibility - Translate visibility from a token ID to an 5305/// AST enum value. 5306static ObjCIvarDecl::AccessControl 5307TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 5308 switch (ivarVisibility) { 5309 default: assert(0 && "Unknown visitibility kind"); 5310 case tok::objc_private: return ObjCIvarDecl::Private; 5311 case tok::objc_public: return ObjCIvarDecl::Public; 5312 case tok::objc_protected: return ObjCIvarDecl::Protected; 5313 case tok::objc_package: return ObjCIvarDecl::Package; 5314 } 5315} 5316 5317/// ActOnIvar - Each ivar field of an objective-c class is passed into this 5318/// in order to create an IvarDecl object for it. 5319Sema::DeclPtrTy Sema::ActOnIvar(Scope *S, 5320 SourceLocation DeclStart, 5321 DeclPtrTy IntfDecl, 5322 Declarator &D, ExprTy *BitfieldWidth, 5323 tok::ObjCKeywordKind Visibility) { 5324 5325 IdentifierInfo *II = D.getIdentifier(); 5326 Expr *BitWidth = (Expr*)BitfieldWidth; 5327 SourceLocation Loc = DeclStart; 5328 if (II) Loc = D.getIdentifierLoc(); 5329 5330 // FIXME: Unnamed fields can be handled in various different ways, for 5331 // example, unnamed unions inject all members into the struct namespace! 5332 5333 TypeSourceInfo *TInfo = 0; 5334 QualType T = GetTypeForDeclarator(D, S, &TInfo); 5335 5336 if (BitWidth) { 5337 // 6.7.2.1p3, 6.7.2.1p4 5338 if (VerifyBitField(Loc, II, T, BitWidth)) { 5339 D.setInvalidType(); 5340 DeleteExpr(BitWidth); 5341 BitWidth = 0; 5342 } 5343 } else { 5344 // Not a bitfield. 5345 5346 // validate II. 5347 5348 } 5349 5350 // C99 6.7.2.1p8: A member of a structure or union may have any type other 5351 // than a variably modified type. 5352 if (T->isVariablyModifiedType()) { 5353 Diag(Loc, diag::err_typecheck_ivar_variable_size); 5354 D.setInvalidType(); 5355 } 5356 5357 // Get the visibility (access control) for this ivar. 5358 ObjCIvarDecl::AccessControl ac = 5359 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 5360 : ObjCIvarDecl::None; 5361 // Must set ivar's DeclContext to its enclosing interface. 5362 Decl *EnclosingDecl = IntfDecl.getAs<Decl>(); 5363 DeclContext *EnclosingContext; 5364 if (ObjCImplementationDecl *IMPDecl = 5365 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 5366 // Case of ivar declared in an implementation. Context is that of its class. 5367 ObjCInterfaceDecl* IDecl = IMPDecl->getClassInterface(); 5368 assert(IDecl && "No class- ActOnIvar"); 5369 EnclosingContext = cast_or_null<DeclContext>(IDecl); 5370 } else 5371 EnclosingContext = dyn_cast<DeclContext>(EnclosingDecl); 5372 assert(EnclosingContext && "null DeclContext for ivar - ActOnIvar"); 5373 5374 // Construct the decl. 5375 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, 5376 EnclosingContext, Loc, II, T, 5377 TInfo, ac, (Expr *)BitfieldWidth); 5378 5379 if (II) { 5380 NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName, 5381 ForRedeclaration); 5382 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 5383 && !isa<TagDecl>(PrevDecl)) { 5384 Diag(Loc, diag::err_duplicate_member) << II; 5385 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 5386 NewID->setInvalidDecl(); 5387 } 5388 } 5389 5390 // Process attributes attached to the ivar. 5391 ProcessDeclAttributes(S, NewID, D); 5392 5393 if (D.isInvalidType()) 5394 NewID->setInvalidDecl(); 5395 5396 if (II) { 5397 // FIXME: When interfaces are DeclContexts, we'll need to add 5398 // these to the interface. 5399 S->AddDecl(DeclPtrTy::make(NewID)); 5400 IdResolver.AddDecl(NewID); 5401 } 5402 5403 return DeclPtrTy::make(NewID); 5404} 5405 5406void Sema::ActOnFields(Scope* S, 5407 SourceLocation RecLoc, DeclPtrTy RecDecl, 5408 DeclPtrTy *Fields, unsigned NumFields, 5409 SourceLocation LBrac, SourceLocation RBrac, 5410 AttributeList *Attr) { 5411 Decl *EnclosingDecl = RecDecl.getAs<Decl>(); 5412 assert(EnclosingDecl && "missing record or interface decl"); 5413 5414 // If the decl this is being inserted into is invalid, then it may be a 5415 // redeclaration or some other bogus case. Don't try to add fields to it. 5416 if (EnclosingDecl->isInvalidDecl()) { 5417 // FIXME: Deallocate fields? 5418 return; 5419 } 5420 5421 5422 // Verify that all the fields are okay. 5423 unsigned NumNamedMembers = 0; 5424 llvm::SmallVector<FieldDecl*, 32> RecFields; 5425 5426 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 5427 for (unsigned i = 0; i != NumFields; ++i) { 5428 FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>()); 5429 5430 // Get the type for the field. 5431 Type *FDTy = FD->getType().getTypePtr(); 5432 5433 if (!FD->isAnonymousStructOrUnion()) { 5434 // Remember all fields written by the user. 5435 RecFields.push_back(FD); 5436 } 5437 5438 // If the field is already invalid for some reason, don't emit more 5439 // diagnostics about it. 5440 if (FD->isInvalidDecl()) { 5441 EnclosingDecl->setInvalidDecl(); 5442 continue; 5443 } 5444 5445 // C99 6.7.2.1p2: 5446 // A structure or union shall not contain a member with 5447 // incomplete or function type (hence, a structure shall not 5448 // contain an instance of itself, but may contain a pointer to 5449 // an instance of itself), except that the last member of a 5450 // structure with more than one named member may have incomplete 5451 // array type; such a structure (and any union containing, 5452 // possibly recursively, a member that is such a structure) 5453 // shall not be a member of a structure or an element of an 5454 // array. 5455 if (FDTy->isFunctionType()) { 5456 // Field declared as a function. 5457 Diag(FD->getLocation(), diag::err_field_declared_as_function) 5458 << FD->getDeclName(); 5459 FD->setInvalidDecl(); 5460 EnclosingDecl->setInvalidDecl(); 5461 continue; 5462 } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 && 5463 Record && Record->isStruct()) { 5464 // Flexible array member. 5465 if (NumNamedMembers < 1) { 5466 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 5467 << FD->getDeclName(); 5468 FD->setInvalidDecl(); 5469 EnclosingDecl->setInvalidDecl(); 5470 continue; 5471 } 5472 // Okay, we have a legal flexible array member at the end of the struct. 5473 if (Record) 5474 Record->setHasFlexibleArrayMember(true); 5475 } else if (!FDTy->isDependentType() && 5476 RequireCompleteType(FD->getLocation(), FD->getType(), 5477 diag::err_field_incomplete)) { 5478 // Incomplete type 5479 FD->setInvalidDecl(); 5480 EnclosingDecl->setInvalidDecl(); 5481 continue; 5482 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 5483 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 5484 // If this is a member of a union, then entire union becomes "flexible". 5485 if (Record && Record->isUnion()) { 5486 Record->setHasFlexibleArrayMember(true); 5487 } else { 5488 // If this is a struct/class and this is not the last element, reject 5489 // it. Note that GCC supports variable sized arrays in the middle of 5490 // structures. 5491 if (i != NumFields-1) 5492 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 5493 << FD->getDeclName() << FD->getType(); 5494 else { 5495 // We support flexible arrays at the end of structs in 5496 // other structs as an extension. 5497 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 5498 << FD->getDeclName(); 5499 if (Record) 5500 Record->setHasFlexibleArrayMember(true); 5501 } 5502 } 5503 } 5504 if (Record && FDTTy->getDecl()->hasObjectMember()) 5505 Record->setHasObjectMember(true); 5506 } else if (FDTy->isObjCInterfaceType()) { 5507 /// A field cannot be an Objective-c object 5508 Diag(FD->getLocation(), diag::err_statically_allocated_object); 5509 FD->setInvalidDecl(); 5510 EnclosingDecl->setInvalidDecl(); 5511 continue; 5512 } else if (getLangOptions().ObjC1 && 5513 getLangOptions().getGCMode() != LangOptions::NonGC && 5514 Record && 5515 (FD->getType()->isObjCObjectPointerType() || 5516 FD->getType().isObjCGCStrong())) 5517 Record->setHasObjectMember(true); 5518 // Keep track of the number of named members. 5519 if (FD->getIdentifier()) 5520 ++NumNamedMembers; 5521 } 5522 5523 // Okay, we successfully defined 'Record'. 5524 if (Record) { 5525 Record->completeDefinition(Context); 5526 } else { 5527 ObjCIvarDecl **ClsFields = 5528 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 5529 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 5530 ID->setIVarList(ClsFields, RecFields.size(), Context); 5531 ID->setLocEnd(RBrac); 5532 // Add ivar's to class's DeclContext. 5533 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 5534 ClsFields[i]->setLexicalDeclContext(ID); 5535 ID->addDecl(ClsFields[i]); 5536 } 5537 // Must enforce the rule that ivars in the base classes may not be 5538 // duplicates. 5539 if (ID->getSuperClass()) { 5540 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(), 5541 IVE = ID->ivar_end(); IVI != IVE; ++IVI) { 5542 ObjCIvarDecl* Ivar = (*IVI); 5543 5544 if (IdentifierInfo *II = Ivar->getIdentifier()) { 5545 ObjCIvarDecl* prevIvar = 5546 ID->getSuperClass()->lookupInstanceVariable(II); 5547 if (prevIvar) { 5548 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II; 5549 Diag(prevIvar->getLocation(), diag::note_previous_declaration); 5550 } 5551 } 5552 } 5553 } 5554 } else if (ObjCImplementationDecl *IMPDecl = 5555 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 5556 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 5557 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 5558 // Ivar declared in @implementation never belongs to the implementation. 5559 // Only it is in implementation's lexical context. 5560 ClsFields[I]->setLexicalDeclContext(IMPDecl); 5561 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 5562 } 5563 } 5564 5565 if (Attr) 5566 ProcessDeclAttributeList(S, Record, Attr); 5567} 5568 5569EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 5570 EnumConstantDecl *LastEnumConst, 5571 SourceLocation IdLoc, 5572 IdentifierInfo *Id, 5573 ExprArg val) { 5574 Expr *Val = (Expr *)val.get(); 5575 5576 llvm::APSInt EnumVal(32); 5577 QualType EltTy; 5578 if (Val) { 5579 if (Val->isTypeDependent()) 5580 EltTy = Context.DependentTy; 5581 else { 5582 // Make sure to promote the operand type to int. 5583 UsualUnaryConversions(Val); 5584 if (Val != val.get()) { 5585 val.release(); 5586 val = Val; 5587 } 5588 5589 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 5590 SourceLocation ExpLoc; 5591 if (!Val->isValueDependent() && 5592 VerifyIntegerConstantExpression(Val, &EnumVal)) { 5593 Val = 0; 5594 } else { 5595 EltTy = Val->getType(); 5596 } 5597 } 5598 } 5599 5600 if (!Val) { 5601 if (LastEnumConst) { 5602 // Assign the last value + 1. 5603 EnumVal = LastEnumConst->getInitVal(); 5604 ++EnumVal; 5605 5606 // Check for overflow on increment. 5607 if (EnumVal < LastEnumConst->getInitVal()) 5608 Diag(IdLoc, diag::warn_enum_value_overflow); 5609 5610 EltTy = LastEnumConst->getType(); 5611 } else { 5612 // First value, set to zero. 5613 EltTy = Context.IntTy; 5614 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy))); 5615 } 5616 } 5617 5618 assert(!EltTy.isNull() && "Enum constant with NULL type"); 5619 5620 val.release(); 5621 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 5622 Val, EnumVal); 5623} 5624 5625 5626Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl, 5627 DeclPtrTy lastEnumConst, 5628 SourceLocation IdLoc, 5629 IdentifierInfo *Id, 5630 SourceLocation EqualLoc, ExprTy *val) { 5631 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>()); 5632 EnumConstantDecl *LastEnumConst = 5633 cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>()); 5634 Expr *Val = static_cast<Expr*>(val); 5635 5636 // The scope passed in may not be a decl scope. Zip up the scope tree until 5637 // we find one that is. 5638 S = getNonFieldDeclScope(S); 5639 5640 // Verify that there isn't already something declared with this name in this 5641 // scope. 5642 NamedDecl *PrevDecl = LookupSingleName(S, Id, LookupOrdinaryName); 5643 if (PrevDecl && PrevDecl->isTemplateParameter()) { 5644 // Maybe we will complain about the shadowed template parameter. 5645 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 5646 // Just pretend that we didn't see the previous declaration. 5647 PrevDecl = 0; 5648 } 5649 5650 if (PrevDecl) { 5651 // When in C++, we may get a TagDecl with the same name; in this case the 5652 // enum constant will 'hide' the tag. 5653 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 5654 "Received TagDecl when not in C++!"); 5655 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 5656 if (isa<EnumConstantDecl>(PrevDecl)) 5657 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 5658 else 5659 Diag(IdLoc, diag::err_redefinition) << Id; 5660 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5661 if (Val) Val->Destroy(Context); 5662 return DeclPtrTy(); 5663 } 5664 } 5665 5666 EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst, 5667 IdLoc, Id, Owned(Val)); 5668 5669 // Register this decl in the current scope stack. 5670 if (New) 5671 PushOnScopeChains(New, S); 5672 5673 return DeclPtrTy::make(New); 5674} 5675 5676void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 5677 SourceLocation RBraceLoc, DeclPtrTy EnumDeclX, 5678 DeclPtrTy *Elements, unsigned NumElements, 5679 Scope *S, AttributeList *Attr) { 5680 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>()); 5681 QualType EnumType = Context.getTypeDeclType(Enum); 5682 5683 if (Attr) 5684 ProcessDeclAttributeList(S, Enum, Attr); 5685 5686 // TODO: If the result value doesn't fit in an int, it must be a long or long 5687 // long value. ISO C does not support this, but GCC does as an extension, 5688 // emit a warning. 5689 unsigned IntWidth = Context.Target.getIntWidth(); 5690 unsigned CharWidth = Context.Target.getCharWidth(); 5691 unsigned ShortWidth = Context.Target.getShortWidth(); 5692 5693 // Verify that all the values are okay, compute the size of the values, and 5694 // reverse the list. 5695 unsigned NumNegativeBits = 0; 5696 unsigned NumPositiveBits = 0; 5697 5698 // Keep track of whether all elements have type int. 5699 bool AllElementsInt = true; 5700 5701 for (unsigned i = 0; i != NumElements; ++i) { 5702 EnumConstantDecl *ECD = 5703 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>()); 5704 if (!ECD) continue; // Already issued a diagnostic. 5705 5706 // If the enum value doesn't fit in an int, emit an extension warning. 5707 const llvm::APSInt &InitVal = ECD->getInitVal(); 5708 assert(InitVal.getBitWidth() >= IntWidth && 5709 "Should have promoted value to int"); 5710 if (InitVal.getBitWidth() > IntWidth) { 5711 llvm::APSInt V(InitVal); 5712 V.trunc(IntWidth); 5713 V.extend(InitVal.getBitWidth()); 5714 if (V != InitVal) 5715 Diag(ECD->getLocation(), diag::ext_enum_value_not_int) 5716 << InitVal.toString(10); 5717 } 5718 5719 // Keep track of the size of positive and negative values. 5720 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 5721 NumPositiveBits = std::max(NumPositiveBits, 5722 (unsigned)InitVal.getActiveBits()); 5723 else 5724 NumNegativeBits = std::max(NumNegativeBits, 5725 (unsigned)InitVal.getMinSignedBits()); 5726 5727 // Keep track of whether every enum element has type int (very commmon). 5728 if (AllElementsInt) 5729 AllElementsInt = ECD->getType() == Context.IntTy; 5730 } 5731 5732 // Figure out the type that should be used for this enum. 5733 // FIXME: Support -fshort-enums. 5734 QualType BestType; 5735 unsigned BestWidth; 5736 5737 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 5738 5739 if (NumNegativeBits) { 5740 // If there is a negative value, figure out the smallest integer type (of 5741 // int/long/longlong) that fits. 5742 // If it's packed, check also if it fits a char or a short. 5743 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 5744 BestType = Context.SignedCharTy; 5745 BestWidth = CharWidth; 5746 } else if (Packed && NumNegativeBits <= ShortWidth && 5747 NumPositiveBits < ShortWidth) { 5748 BestType = Context.ShortTy; 5749 BestWidth = ShortWidth; 5750 } 5751 else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 5752 BestType = Context.IntTy; 5753 BestWidth = IntWidth; 5754 } else { 5755 BestWidth = Context.Target.getLongWidth(); 5756 5757 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) 5758 BestType = Context.LongTy; 5759 else { 5760 BestWidth = Context.Target.getLongLongWidth(); 5761 5762 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 5763 Diag(Enum->getLocation(), diag::warn_enum_too_large); 5764 BestType = Context.LongLongTy; 5765 } 5766 } 5767 } else { 5768 // If there is no negative value, figure out which of uint, ulong, ulonglong 5769 // fits. 5770 // If it's packed, check also if it fits a char or a short. 5771 if (Packed && NumPositiveBits <= CharWidth) { 5772 BestType = Context.UnsignedCharTy; 5773 BestWidth = CharWidth; 5774 } else if (Packed && NumPositiveBits <= ShortWidth) { 5775 BestType = Context.UnsignedShortTy; 5776 BestWidth = ShortWidth; 5777 } 5778 else if (NumPositiveBits <= IntWidth) { 5779 BestType = Context.UnsignedIntTy; 5780 BestWidth = IntWidth; 5781 } else if (NumPositiveBits <= 5782 (BestWidth = Context.Target.getLongWidth())) { 5783 BestType = Context.UnsignedLongTy; 5784 } else { 5785 BestWidth = Context.Target.getLongLongWidth(); 5786 assert(NumPositiveBits <= BestWidth && 5787 "How could an initializer get larger than ULL?"); 5788 BestType = Context.UnsignedLongLongTy; 5789 } 5790 } 5791 5792 // Loop over all of the enumerator constants, changing their types to match 5793 // the type of the enum if needed. 5794 for (unsigned i = 0; i != NumElements; ++i) { 5795 EnumConstantDecl *ECD = 5796 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>()); 5797 if (!ECD) continue; // Already issued a diagnostic. 5798 5799 // Standard C says the enumerators have int type, but we allow, as an 5800 // extension, the enumerators to be larger than int size. If each 5801 // enumerator value fits in an int, type it as an int, otherwise type it the 5802 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 5803 // that X has type 'int', not 'unsigned'. 5804 if (ECD->getType() == Context.IntTy) { 5805 // Make sure the init value is signed. 5806 llvm::APSInt IV = ECD->getInitVal(); 5807 IV.setIsSigned(true); 5808 ECD->setInitVal(IV); 5809 5810 if (getLangOptions().CPlusPlus) 5811 // C++ [dcl.enum]p4: Following the closing brace of an 5812 // enum-specifier, each enumerator has the type of its 5813 // enumeration. 5814 ECD->setType(EnumType); 5815 continue; // Already int type. 5816 } 5817 5818 // Determine whether the value fits into an int. 5819 llvm::APSInt InitVal = ECD->getInitVal(); 5820 bool FitsInInt; 5821 if (InitVal.isUnsigned() || !InitVal.isNegative()) 5822 FitsInInt = InitVal.getActiveBits() < IntWidth; 5823 else 5824 FitsInInt = InitVal.getMinSignedBits() <= IntWidth; 5825 5826 // If it fits into an integer type, force it. Otherwise force it to match 5827 // the enum decl type. 5828 QualType NewTy; 5829 unsigned NewWidth; 5830 bool NewSign; 5831 if (FitsInInt) { 5832 NewTy = Context.IntTy; 5833 NewWidth = IntWidth; 5834 NewSign = true; 5835 } else if (ECD->getType() == BestType) { 5836 // Already the right type! 5837 if (getLangOptions().CPlusPlus) 5838 // C++ [dcl.enum]p4: Following the closing brace of an 5839 // enum-specifier, each enumerator has the type of its 5840 // enumeration. 5841 ECD->setType(EnumType); 5842 continue; 5843 } else { 5844 NewTy = BestType; 5845 NewWidth = BestWidth; 5846 NewSign = BestType->isSignedIntegerType(); 5847 } 5848 5849 // Adjust the APSInt value. 5850 InitVal.extOrTrunc(NewWidth); 5851 InitVal.setIsSigned(NewSign); 5852 ECD->setInitVal(InitVal); 5853 5854 // Adjust the Expr initializer and type. 5855 if (ECD->getInitExpr()) 5856 ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy, 5857 CastExpr::CK_IntegralCast, 5858 ECD->getInitExpr(), 5859 /*isLvalue=*/false)); 5860 if (getLangOptions().CPlusPlus) 5861 // C++ [dcl.enum]p4: Following the closing brace of an 5862 // enum-specifier, each enumerator has the type of its 5863 // enumeration. 5864 ECD->setType(EnumType); 5865 else 5866 ECD->setType(NewTy); 5867 } 5868 5869 Enum->completeDefinition(Context, BestType); 5870} 5871 5872Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc, 5873 ExprArg expr) { 5874 StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>()); 5875 5876 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 5877 Loc, AsmString); 5878 CurContext->addDecl(New); 5879 return DeclPtrTy::make(New); 5880} 5881 5882void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 5883 SourceLocation PragmaLoc, 5884 SourceLocation NameLoc) { 5885 Decl *PrevDecl = LookupSingleName(TUScope, Name, LookupOrdinaryName); 5886 5887 if (PrevDecl) { 5888 PrevDecl->addAttr(::new (Context) WeakAttr()); 5889 } else { 5890 (void)WeakUndeclaredIdentifiers.insert( 5891 std::pair<IdentifierInfo*,WeakInfo> 5892 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 5893 } 5894} 5895 5896void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 5897 IdentifierInfo* AliasName, 5898 SourceLocation PragmaLoc, 5899 SourceLocation NameLoc, 5900 SourceLocation AliasNameLoc) { 5901 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, LookupOrdinaryName); 5902 WeakInfo W = WeakInfo(Name, NameLoc); 5903 5904 if (PrevDecl) { 5905 if (!PrevDecl->hasAttr<AliasAttr>()) 5906 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 5907 DeclApplyPragmaWeak(TUScope, ND, W); 5908 } else { 5909 (void)WeakUndeclaredIdentifiers.insert( 5910 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 5911 } 5912} 5913