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