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