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