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