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