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