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