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