SemaDecl.cpp revision aa9c3503867bc52e1f61c4da676116db1b1cdf01
1e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer// 3e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer// The LLVM Compiler Infrastructure 4e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer// 5fc001bbfc360ab828e5a4b0cbe4bb7db87361b85Chris Lattner// This file is distributed under the University of Illinois Open Source 6fc001bbfc360ab828e5a4b0cbe4bb7db87361b85Chris Lattner// License. See LICENSE.TXT for details. 7e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer// 8e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer//===----------------------------------------------------------------------===// 9e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer// 10e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer// This file implements semantic analysis for declarations. 11e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer// 1200b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen//===----------------------------------------------------------------------===// 13e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 14e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include "clang/Sema/SemaInternal.h" 15e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include "clang/Sema/Initialization.h" 16e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include "clang/Sema/Lookup.h" 17e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include "clang/Sema/CXXFieldCollector.h" 18e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include "clang/Sema/Scope.h" 19e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include "clang/Sema/ScopeInfo.h" 20e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include "TypeLocBuilder.h" 218b477ed579794ba6d76915d56b3f448a7dd20120Owen Anderson#include "clang/AST/ASTConsumer.h" 22e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include "clang/AST/ASTContext.h" 23e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include "clang/AST/CXXInheritance.h" 2456427031f60a34f8388a0facf14bea0558b8320eReid Spencer#include "clang/AST/DeclCXX.h" 25e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include "clang/AST/DeclObjC.h" 26e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include "clang/AST/DeclTemplate.h" 27afebb449283ada1b44f423e698b30672606fdc54Jeff Cohen#include "clang/AST/EvaluatedExprVisitor.h" 28afebb449283ada1b44f423e698b30672606fdc54Jeff Cohen#include "clang/AST/ExprCXX.h" 29e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include "clang/AST/StmtCXX.h" 30da06288aeb28393b937e17dcd180658c3737a6e5Chris Lattner#include "clang/AST/CharUnits.h" 31e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include "clang/Sema/DeclSpec.h" 32e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include "clang/Sema/ParsedTemplate.h" 33e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include "clang/Parse/ParseDiagnostic.h" 346a98754ebbc211958297b0d20a77e8c3261c3708Chris Lattner#include "clang/Basic/PartialDiagnostic.h" 35e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include "clang/Sema/DelayedDiagnostic.h" 36e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include "clang/Basic/SourceManager.h" 37e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include "clang/Basic/TargetInfo.h" 386a98754ebbc211958297b0d20a77e8c3261c3708Chris Lattner// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's) 391d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson#include "clang/Lex/Preprocessor.h" 401d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson#include "clang/Lex/HeaderSearch.h" 411d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson#include "clang/Lex/ModuleLoader.h" 426a98754ebbc211958297b0d20a77e8c3261c3708Chris Lattner#include "llvm/ADT/Triple.h" 4300b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen#include <algorithm> 44e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include <cstring> 45e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer#include <functional> 461d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Andersonusing namespace clang; 4700b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohenusing namespace sema; 48e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 491d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen AndersonSema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 5000b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen if (OwnedType) { 51e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer Decl *Group[2] = { OwnedType, Ptr }; 52e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 53e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer } 54e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 5500b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 56e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer} 577cbd8a3e92221437048b484d5ef9c0a22d0f8c58Gabor Greif 5800b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen/// \brief If the identifier refers to a type name within this scope, 59e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer/// return the declaration of that type. 601d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson/// 6100b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen/// This routine performs ordinary name lookup of the identifier II 6200b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen/// within the given scope, with optional C++ scope specifier SS, to 63e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer/// determine whether the name refers to a type. If so, returns an 64e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer/// opaque pointer (actually a QualType) corresponding to that 65e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer/// type. Otherwise, returns NULL. 666a98754ebbc211958297b0d20a77e8c3261c3708Chris Lattner/// 67e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer/// If name lookup results in an ambiguity, this routine will complain 68e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer/// and then return NULL. 696a98754ebbc211958297b0d20a77e8c3261c3708Chris LattnerParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 701d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson Scope *S, CXXScopeSpec *SS, 711d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson bool isClassName, bool HasTrailingDot, 721d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson ParsedType ObjectTypePtr, 736a98754ebbc211958297b0d20a77e8c3261c3708Chris Lattner bool WantNontrivialTypeSourceInfo, 7400b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen IdentifierInfo **CorrectedII) { 75e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // Determine where we will perform name lookup. 761d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson DeclContext *LookupCtx = 0; 7700b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen if (ObjectTypePtr) { 78e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer QualType ObjectType = ObjectTypePtr.get(); 791d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson if (ObjectType->isRecordType()) 801d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson LookupCtx = computeDeclContext(ObjectType); 8100b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen } else if (SS && SS->isNotEmpty()) { 82e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer LookupCtx = computeDeclContext(*SS, false); 83e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 84e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (!LookupCtx) { 8500b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen if (isDependentScopeSpecifier(*SS)) { 86e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // C++ [temp.res]p3: 871d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson // A qualified-id that refers to a type and in which the 88e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // nested-name-specifier depends on a template-parameter (14.6.2) 891d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson // shall be prefixed by the keyword typename to indicate that the 9000b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen // qualified-id denotes a type, forming an 91e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // elaborated-type-specifier (7.1.5.3). 92333c40096561218bc3597cf153c0a3895274414cOwen Anderson // 93051a950000e21935165db56695e35bade668193bGabor Greif // We therefore do not perform any name lookup if the result would 9400b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen // refer to a member of an unknown specialization. 95e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (!isClassName) 961d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson return ParsedType(); 9700b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen 98e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // We know from the grammar that this name refers to a type, 997cbd8a3e92221437048b484d5ef9c0a22d0f8c58Gabor Greif // so build a dependent node to describe the type. 100051a950000e21935165db56695e35bade668193bGabor Greif if (WantNontrivialTypeSourceInfo) 10100b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 102e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 1037cbd8a3e92221437048b484d5ef9c0a22d0f8c58Gabor Greif NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 104051a950000e21935165db56695e35bade668193bGabor Greif QualType T = 10500b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 106e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer II, NameLoc); 10700b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen 1087cbd8a3e92221437048b484d5ef9c0a22d0f8c58Gabor Greif return ParsedType::make(T); 10900b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen } 110e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 1111d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson return ParsedType(); 11200b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen } 113e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 114e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (!LookupCtx->isDependentContext() && 115e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer RequireCompleteDeclContext(*SS, LookupCtx)) 116e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer return ParsedType(); 117e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer } 118e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 119e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // FIXME: LookupNestedNameSpecifierName isn't the right kind of 120e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // lookup for class-names. 121e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 122e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer LookupOrdinaryName; 123e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer LookupResult Result(*this, &II, NameLoc, Kind); 124e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (LookupCtx) { 125e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // Perform "qualified" name lookup into the declaration context we 126e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // computed, which is either the type of the base of a member access 127e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // expression or the declaration context associated with a prior 128e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // nested-name-specifier. 129e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer LookupQualifiedName(Result, LookupCtx); 130e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 131e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (ObjectTypePtr && Result.empty()) { 13200b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen // C++ [basic.lookup.classref]p3: 133e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // If the unqualified-id is ~type-name, the type-name is looked up 134e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // in the context of the entire postfix-expression. If the type T of 13500b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen // the object expression is of a class type C, the type-name is also 136e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // looked up in the scope of class C. At least one of the lookups shall 137e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // find a name that refers to (possibly cv-qualified) T. 138e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer LookupName(Result, S); 13900b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen } 140e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer } else { 141e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // Perform unqualified name lookup. 142e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer LookupName(Result, S); 143e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer } 14400b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen 145e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer NamedDecl *IIDecl = 0; 146e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer switch (Result.getResultKind()) { 147e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer case LookupResult::NotFound: 14800b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen case LookupResult::NotFoundInCurrentInstantiation: 149e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (CorrectedII) { 150e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), 151e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer Kind, S, SS, 0, false, 152e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer Sema::CTC_Type); 153e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 154e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer TemplateTy Template; 155e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer bool MemberOfUnknownSpecialization; 15600b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen UnqualifiedId TemplateName; 157e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer TemplateName.setIdentifier(NewII, NameLoc); 15800b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 159e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer CXXScopeSpec NewSS, *NewSSPtr = SS; 160e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (SS && NNS) { 161e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 162e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer NewSSPtr = &NewSS; 16300b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen } 16400b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen if (Correction && (NNS || NewII != &II) && 165e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // Ignore a correction to a template type as the to-be-corrected 166e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // identifier is not a template (typo correction for template names 167e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // is handled elsewhere). 168e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer !(getLangOptions().CPlusPlus && NewSSPtr && 169e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 17000b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen false, Template, MemberOfUnknownSpecialization))) { 171e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 172e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer isClassName, HasTrailingDot, ObjectTypePtr, 173e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer WantNontrivialTypeSourceInfo); 174e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (Ty) { 17500b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen std::string CorrectedStr(Correction.getAsString(getLangOptions())); 176e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer std::string CorrectedQuotedStr( 177e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer Correction.getQuoted(getLangOptions())); 178e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer Diag(NameLoc, diag::err_unknown_typename_suggest) 179e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer << Result.getLookupName() << CorrectedQuotedStr 180e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer << FixItHint::CreateReplacement(SourceRange(NameLoc), 181e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer CorrectedStr); 182e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (NamedDecl *FirstDecl = Correction.getCorrectionDecl()) 18300b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen Diag(FirstDecl->getLocation(), diag::note_previous_decl) 184e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer << CorrectedQuotedStr; 185e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 186e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (SS && NNS) 18700b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 18800b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen *CorrectedII = NewII; 189e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer return Ty; 190e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer } 191e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer } 192e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer } 19300b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen // If typo correction failed or was not performed, fall through 194e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer case LookupResult::FoundOverloaded: 195e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer case LookupResult::FoundUnresolvedValue: 196e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer Result.suppressDiagnostics(); 197e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer return ParsedType(); 19800b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen 199e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer case LookupResult::Ambiguous: 200e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // Recover from type-hiding ambiguities by hiding the type. We'll 201e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // do the lookup again when looking for an object, and we can 202e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // diagnose the error then. If we don't do this, then the error 203e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // about hiding the type will be immediately followed by an error 204e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // that only makes sense if the identifier was treated like a type. 205e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 20600b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen Result.suppressDiagnostics(); 207e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer return ParsedType(); 208e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer } 209e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 210e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // Look to see if we have a type anywhere in the list of results. 211e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 212e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer Res != ResEnd; ++Res) { 213709877243661b2b450402d4911de892af5c74f43Chris Lattner if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 214e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (!IIDecl || 21500b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen (*Res)->getLocation().getRawEncoding() < 216e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer IIDecl->getLocation().getRawEncoding()) 217e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer IIDecl = *Res; 218e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer } 219e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer } 220e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 221e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (!IIDecl) { 222e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // None of the entities we found is a type, so there is no way 223e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // to even assume that the result is a type. In this case, don't 224e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // complain about the ambiguity. The parser will either try to 225e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // perform this lookup again (e.g., as an object name), which 226e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // will produce the ambiguity, or will complain that it expected 22700b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen // a type name. 228e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer Result.suppressDiagnostics(); 229e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer return ParsedType(); 23034bd70de3c344034b82dc9a964a6b6893efa3e82Reid Spencer } 23100b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen 232e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // We found a type within the ambiguous lookup; diagnose the 233e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // ambiguity and then return that type. This might be the right 23400b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen // answer, or it might not be, but it suppresses any attempt to 23534bd70de3c344034b82dc9a964a6b6893efa3e82Reid Spencer // perform the name lookup again. 236e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer break; 237e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 238da06288aeb28393b937e17dcd180658c3737a6e5Chris Lattner case LookupResult::Found: 239da06288aeb28393b937e17dcd180658c3737a6e5Chris Lattner IIDecl = Result.getFoundDecl(); 2408b477ed579794ba6d76915d56b3f448a7dd20120Owen Anderson break; 241da06288aeb28393b937e17dcd180658c3737a6e5Chris Lattner } 242e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 24331895e73591d3c9ceae731a1274c8f56194b9616Owen Anderson assert(IIDecl && "Didn't find decl"); 24400b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen 245e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer QualType T; 246e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 24700b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen DiagnoseUseOfDecl(IIDecl, NameLoc); 248e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 2494b1511b027ce0b648b3379f2891816c25b46f515Reid Kleckner if (T.isNull()) 25000b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen T = Context.getTypeDeclType(TD); 251e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 252e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (SS && SS->isNotEmpty()) { 25300b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen if (WantNontrivialTypeSourceInfo) { 254e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // Construct a type with type-source information. 255e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer TypeLocBuilder Builder; 256e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer Builder.pushTypeSpec(T).setNameLoc(NameLoc); 257e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 25800b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen T = getElaboratedType(ETK_None, *SS, T); 259e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 260e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer ElabTL.setKeywordLoc(SourceLocation()); 261e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 262e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 263e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer } else { 264e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer T = getElaboratedType(ETK_None, *SS, T); 26500b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen } 266e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer } 267e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 268e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer (void)DiagnoseUseOfDecl(IDecl, NameLoc); 269e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (!HasTrailingDot) 270e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer T = Context.getObjCInterfaceType(IDecl); 271e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer } 27200b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen 273e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (T.isNull()) { 274e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // If it's not plausibly a type, suppress diagnostics. 275e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer Result.suppressDiagnostics(); 276e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer return ParsedType(); 277e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer } 278e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer return ParsedType::make(T); 27900b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen} 280e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 28100b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen/// isTagName() - This method is called *for error recovery purposes only* 282e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer/// to determine if the specified name is a valid tag name ("struct foo"). If 283e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer/// so, this returns the TST for the tag corresponding to it (TST_enum, 284e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C 285e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer/// where the user forgot to specify the tag. 286e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid SpencerDeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 287e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer // Do a tag name lookup in this scope. 2886fb0d735f0ffdf4cd1b0a1fa04bd436586097448Reid Spencer LookupResult R(*this, &II, SourceLocation(), LookupTagName); 28900b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen LookupName(R, S, false); 290e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer R.suppressDiagnostics(); 291e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (R.getResultKind() == LookupResult::Found) 292e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 293e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer switch (TD->getTagKind()) { 294e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer default: return DeclSpec::TST_unspecified; 2956fb0d735f0ffdf4cd1b0a1fa04bd436586097448Reid Spencer case TTK_Struct: return DeclSpec::TST_struct; 29600b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen case TTK_Union: return DeclSpec::TST_union; 297e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer case TTK_Class: return DeclSpec::TST_class; 298e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer case TTK_Enum: return DeclSpec::TST_enum; 299e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer } 300e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer } 301e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 3026fb0d735f0ffdf4cd1b0a1fa04bd436586097448Reid Spencer return DeclSpec::TST_unspecified; 30300b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen} 304e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer 305e8cdc8b3a372015728bfbe494e4a8949fb66f6a6Reid Spencer/// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 306/// if a CXXScopeSpec's type is equal to the type of one of the base classes 307/// then downgrade the missing typename error to a warning. 308/// This is needed for MSVC compatibility; Example: 309/// @code 310/// template<class T> class A { 311/// public: 312/// typedef int TYPE; 313/// }; 314/// template<class T> class B : public A<T> { 315/// public: 316/// A<T>::TYPE a; // no typename required because A<T> is a base class. 317/// }; 318/// @endcode 319bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 320 if (CurContext->isRecord()) { 321 const Type *Ty = SS->getScopeRep()->getAsType(); 322 323 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 324 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 325 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) 326 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType())) 327 return true; 328 return S->isFunctionPrototypeScope(); 329 } 330 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 331} 332 333bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II, 334 SourceLocation IILoc, 335 Scope *S, 336 CXXScopeSpec *SS, 337 ParsedType &SuggestedType) { 338 // We don't have anything to suggest (yet). 339 SuggestedType = ParsedType(); 340 341 // There may have been a typo in the name of the type. Look up typo 342 // results, in case we have something that we can suggest. 343 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc), 344 LookupOrdinaryName, S, SS, NULL, 345 false, CTC_Type)) { 346 std::string CorrectedStr(Corrected.getAsString(getLangOptions())); 347 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions())); 348 349 if (Corrected.isKeyword()) { 350 // We corrected to a keyword. 351 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it. 352 Diag(IILoc, diag::err_unknown_typename_suggest) 353 << &II << CorrectedQuotedStr; 354 return true; 355 } else { 356 NamedDecl *Result = Corrected.getCorrectionDecl(); 357 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) && 358 !Result->isInvalidDecl()) { 359 // We found a similarly-named type or interface; suggest that. 360 if (!SS || !SS->isSet()) 361 Diag(IILoc, diag::err_unknown_typename_suggest) 362 << &II << CorrectedQuotedStr 363 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 364 else if (DeclContext *DC = computeDeclContext(*SS, false)) 365 Diag(IILoc, diag::err_unknown_nested_typename_suggest) 366 << &II << DC << CorrectedQuotedStr << SS->getRange() 367 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 368 else 369 llvm_unreachable("could not have corrected a typo here"); 370 371 Diag(Result->getLocation(), diag::note_previous_decl) 372 << CorrectedQuotedStr; 373 374 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS, 375 false, false, ParsedType(), 376 /*NonTrivialTypeSourceInfo=*/true); 377 return true; 378 } 379 } 380 } 381 382 if (getLangOptions().CPlusPlus) { 383 // See if II is a class template that the user forgot to pass arguments to. 384 UnqualifiedId Name; 385 Name.setIdentifier(&II, IILoc); 386 CXXScopeSpec EmptySS; 387 TemplateTy TemplateResult; 388 bool MemberOfUnknownSpecialization; 389 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 390 Name, ParsedType(), true, TemplateResult, 391 MemberOfUnknownSpecialization) == TNK_Type_template) { 392 TemplateName TplName = TemplateResult.getAsVal<TemplateName>(); 393 Diag(IILoc, diag::err_template_missing_args) << TplName; 394 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 395 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 396 << TplDecl->getTemplateParameters()->getSourceRange(); 397 } 398 return true; 399 } 400 } 401 402 // FIXME: Should we move the logic that tries to recover from a missing tag 403 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 404 405 if (!SS || (!SS->isSet() && !SS->isInvalid())) 406 Diag(IILoc, diag::err_unknown_typename) << &II; 407 else if (DeclContext *DC = computeDeclContext(*SS, false)) 408 Diag(IILoc, diag::err_typename_nested_not_found) 409 << &II << DC << SS->getRange(); 410 else if (isDependentScopeSpecifier(*SS)) { 411 unsigned DiagID = diag::err_typename_missing; 412 if (getLangOptions().MicrosoftMode && isMicrosoftMissingTypename(SS, S)) 413 DiagID = diag::warn_typename_missing; 414 415 Diag(SS->getRange().getBegin(), DiagID) 416 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName() 417 << SourceRange(SS->getRange().getBegin(), IILoc) 418 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 419 SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc) 420 .get(); 421 } else { 422 assert(SS && SS->isInvalid() && 423 "Invalid scope specifier has already been diagnosed"); 424 } 425 426 return true; 427} 428 429/// \brief Determine whether the given result set contains either a type name 430/// or 431static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 432 bool CheckTemplate = R.getSema().getLangOptions().CPlusPlus && 433 NextToken.is(tok::less); 434 435 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 436 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 437 return true; 438 439 if (CheckTemplate && isa<TemplateDecl>(*I)) 440 return true; 441 } 442 443 return false; 444} 445 446Sema::NameClassification Sema::ClassifyName(Scope *S, 447 CXXScopeSpec &SS, 448 IdentifierInfo *&Name, 449 SourceLocation NameLoc, 450 const Token &NextToken) { 451 DeclarationNameInfo NameInfo(Name, NameLoc); 452 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 453 454 if (NextToken.is(tok::coloncolon)) { 455 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 456 QualType(), false, SS, 0, false); 457 458 } 459 460 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 461 LookupParsedName(Result, S, &SS, !CurMethod); 462 463 // Perform lookup for Objective-C instance variables (including automatically 464 // synthesized instance variables), if we're in an Objective-C method. 465 // FIXME: This lookup really, really needs to be folded in to the normal 466 // unqualified lookup mechanism. 467 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 468 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 469 if (E.get() || E.isInvalid()) 470 return E; 471 } 472 473 bool SecondTry = false; 474 bool IsFilteredTemplateName = false; 475 476Corrected: 477 switch (Result.getResultKind()) { 478 case LookupResult::NotFound: 479 // If an unqualified-id is followed by a '(', then we have a function 480 // call. 481 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 482 // In C++, this is an ADL-only call. 483 // FIXME: Reference? 484 if (getLangOptions().CPlusPlus) 485 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 486 487 // C90 6.3.2.2: 488 // If the expression that precedes the parenthesized argument list in a 489 // function call consists solely of an identifier, and if no 490 // declaration is visible for this identifier, the identifier is 491 // implicitly declared exactly as if, in the innermost block containing 492 // the function call, the declaration 493 // 494 // extern int identifier (); 495 // 496 // appeared. 497 // 498 // We also allow this in C99 as an extension. 499 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 500 Result.addDecl(D); 501 Result.resolveKind(); 502 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 503 } 504 } 505 506 // In C, we first see whether there is a tag type by the same name, in 507 // which case it's likely that the user just forget to write "enum", 508 // "struct", or "union". 509 if (!getLangOptions().CPlusPlus && !SecondTry) { 510 Result.clear(LookupTagName); 511 LookupParsedName(Result, S, &SS); 512 if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) { 513 const char *TagName = 0; 514 const char *FixItTagName = 0; 515 switch (Tag->getTagKind()) { 516 case TTK_Class: 517 TagName = "class"; 518 FixItTagName = "class "; 519 break; 520 521 case TTK_Enum: 522 TagName = "enum"; 523 FixItTagName = "enum "; 524 break; 525 526 case TTK_Struct: 527 TagName = "struct"; 528 FixItTagName = "struct "; 529 break; 530 531 case TTK_Union: 532 TagName = "union"; 533 FixItTagName = "union "; 534 break; 535 } 536 537 Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 538 << Name << TagName << getLangOptions().CPlusPlus 539 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 540 break; 541 } 542 543 Result.clear(LookupOrdinaryName); 544 } 545 546 // Perform typo correction to determine if there is another name that is 547 // close to this name. 548 if (!SecondTry) { 549 SecondTry = true; 550 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 551 Result.getLookupKind(), S, 552 &SS)) { 553 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 554 unsigned QualifiedDiag = diag::err_no_member_suggest; 555 std::string CorrectedStr(Corrected.getAsString(getLangOptions())); 556 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions())); 557 558 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 559 NamedDecl *UnderlyingFirstDecl 560 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 561 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) && 562 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 563 UnqualifiedDiag = diag::err_no_template_suggest; 564 QualifiedDiag = diag::err_no_member_template_suggest; 565 } else if (UnderlyingFirstDecl && 566 (isa<TypeDecl>(UnderlyingFirstDecl) || 567 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 568 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 569 UnqualifiedDiag = diag::err_unknown_typename_suggest; 570 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 571 } 572 573 if (SS.isEmpty()) 574 Diag(NameLoc, UnqualifiedDiag) 575 << Name << CorrectedQuotedStr 576 << FixItHint::CreateReplacement(NameLoc, CorrectedStr); 577 else 578 Diag(NameLoc, QualifiedDiag) 579 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 580 << SS.getRange() 581 << FixItHint::CreateReplacement(NameLoc, CorrectedStr); 582 583 // Update the name, so that the caller has the new name. 584 Name = Corrected.getCorrectionAsIdentifierInfo(); 585 586 // Also update the LookupResult... 587 // FIXME: This should probably go away at some point 588 Result.clear(); 589 Result.setLookupName(Corrected.getCorrection()); 590 if (FirstDecl) Result.addDecl(FirstDecl); 591 592 // Typo correction corrected to a keyword. 593 if (Corrected.isKeyword()) 594 return Corrected.getCorrectionAsIdentifierInfo(); 595 596 if (FirstDecl) 597 Diag(FirstDecl->getLocation(), diag::note_previous_decl) 598 << CorrectedQuotedStr; 599 600 // If we found an Objective-C instance variable, let 601 // LookupInObjCMethod build the appropriate expression to 602 // reference the ivar. 603 // FIXME: This is a gross hack. 604 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 605 Result.clear(); 606 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 607 return move(E); 608 } 609 610 goto Corrected; 611 } 612 } 613 614 // We failed to correct; just fall through and let the parser deal with it. 615 Result.suppressDiagnostics(); 616 return NameClassification::Unknown(); 617 618 case LookupResult::NotFoundInCurrentInstantiation: 619 // We performed name lookup into the current instantiation, and there were 620 // dependent bases, so we treat this result the same way as any other 621 // dependent nested-name-specifier. 622 623 // C++ [temp.res]p2: 624 // A name used in a template declaration or definition and that is 625 // dependent on a template-parameter is assumed not to name a type 626 // unless the applicable name lookup finds a type name or the name is 627 // qualified by the keyword typename. 628 // 629 // FIXME: If the next token is '<', we might want to ask the parser to 630 // perform some heroics to see if we actually have a 631 // template-argument-list, which would indicate a missing 'template' 632 // keyword here. 633 return BuildDependentDeclRefExpr(SS, NameInfo, /*TemplateArgs=*/0); 634 635 case LookupResult::Found: 636 case LookupResult::FoundOverloaded: 637 case LookupResult::FoundUnresolvedValue: 638 break; 639 640 case LookupResult::Ambiguous: 641 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) && 642 hasAnyAcceptableTemplateNames(Result)) { 643 // C++ [temp.local]p3: 644 // A lookup that finds an injected-class-name (10.2) can result in an 645 // ambiguity in certain cases (for example, if it is found in more than 646 // one base class). If all of the injected-class-names that are found 647 // refer to specializations of the same class template, and if the name 648 // is followed by a template-argument-list, the reference refers to the 649 // class template itself and not a specialization thereof, and is not 650 // ambiguous. 651 // 652 // This filtering can make an ambiguous result into an unambiguous one, 653 // so try again after filtering out template names. 654 FilterAcceptableTemplateNames(Result); 655 if (!Result.isAmbiguous()) { 656 IsFilteredTemplateName = true; 657 break; 658 } 659 } 660 661 // Diagnose the ambiguity and return an error. 662 return NameClassification::Error(); 663 } 664 665 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) && 666 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 667 // C++ [temp.names]p3: 668 // After name lookup (3.4) finds that a name is a template-name or that 669 // an operator-function-id or a literal- operator-id refers to a set of 670 // overloaded functions any member of which is a function template if 671 // this is followed by a <, the < is always taken as the delimiter of a 672 // template-argument-list and never as the less-than operator. 673 if (!IsFilteredTemplateName) 674 FilterAcceptableTemplateNames(Result); 675 676 if (!Result.empty()) { 677 bool IsFunctionTemplate; 678 TemplateName Template; 679 if (Result.end() - Result.begin() > 1) { 680 IsFunctionTemplate = true; 681 Template = Context.getOverloadedTemplateName(Result.begin(), 682 Result.end()); 683 } else { 684 TemplateDecl *TD 685 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 686 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 687 688 if (SS.isSet() && !SS.isInvalid()) 689 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 690 /*TemplateKeyword=*/false, 691 TD); 692 else 693 Template = TemplateName(TD); 694 } 695 696 if (IsFunctionTemplate) { 697 // Function templates always go through overload resolution, at which 698 // point we'll perform the various checks (e.g., accessibility) we need 699 // to based on which function we selected. 700 Result.suppressDiagnostics(); 701 702 return NameClassification::FunctionTemplate(Template); 703 } 704 705 return NameClassification::TypeTemplate(Template); 706 } 707 } 708 709 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 710 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 711 DiagnoseUseOfDecl(Type, NameLoc); 712 QualType T = Context.getTypeDeclType(Type); 713 return ParsedType::make(T); 714 } 715 716 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 717 if (!Class) { 718 // FIXME: It's unfortunate that we don't have a Type node for handling this. 719 if (ObjCCompatibleAliasDecl *Alias 720 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 721 Class = Alias->getClassInterface(); 722 } 723 724 if (Class) { 725 DiagnoseUseOfDecl(Class, NameLoc); 726 727 if (NextToken.is(tok::period)) { 728 // Interface. <something> is parsed as a property reference expression. 729 // Just return "unknown" as a fall-through for now. 730 Result.suppressDiagnostics(); 731 return NameClassification::Unknown(); 732 } 733 734 QualType T = Context.getObjCInterfaceType(Class); 735 return ParsedType::make(T); 736 } 737 738 if (!Result.empty() && (*Result.begin())->isCXXClassMember()) 739 return BuildPossibleImplicitMemberExpr(SS, Result, 0); 740 741 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 742 return BuildDeclarationNameExpr(SS, Result, ADL); 743} 744 745// Determines the context to return to after temporarily entering a 746// context. This depends in an unnecessarily complicated way on the 747// exact ordering of callbacks from the parser. 748DeclContext *Sema::getContainingDC(DeclContext *DC) { 749 750 // Functions defined inline within classes aren't parsed until we've 751 // finished parsing the top-level class, so the top-level class is 752 // the context we'll need to return to. 753 if (isa<FunctionDecl>(DC)) { 754 DC = DC->getLexicalParent(); 755 756 // A function not defined within a class will always return to its 757 // lexical context. 758 if (!isa<CXXRecordDecl>(DC)) 759 return DC; 760 761 // A C++ inline method/friend is parsed *after* the topmost class 762 // it was declared in is fully parsed ("complete"); the topmost 763 // class is the context we need to return to. 764 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 765 DC = RD; 766 767 // Return the declaration context of the topmost class the inline method is 768 // declared in. 769 return DC; 770 } 771 772 return DC->getLexicalParent(); 773} 774 775void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 776 assert(getContainingDC(DC) == CurContext && 777 "The next DeclContext should be lexically contained in the current one."); 778 CurContext = DC; 779 S->setEntity(DC); 780} 781 782void Sema::PopDeclContext() { 783 assert(CurContext && "DeclContext imbalance!"); 784 785 CurContext = getContainingDC(CurContext); 786 assert(CurContext && "Popped translation unit!"); 787} 788 789/// EnterDeclaratorContext - Used when we must lookup names in the context 790/// of a declarator's nested name specifier. 791/// 792void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 793 // C++0x [basic.lookup.unqual]p13: 794 // A name used in the definition of a static data member of class 795 // X (after the qualified-id of the static member) is looked up as 796 // if the name was used in a member function of X. 797 // C++0x [basic.lookup.unqual]p14: 798 // If a variable member of a namespace is defined outside of the 799 // scope of its namespace then any name used in the definition of 800 // the variable member (after the declarator-id) is looked up as 801 // if the definition of the variable member occurred in its 802 // namespace. 803 // Both of these imply that we should push a scope whose context 804 // is the semantic context of the declaration. We can't use 805 // PushDeclContext here because that context is not necessarily 806 // lexically contained in the current context. Fortunately, 807 // the containing scope should have the appropriate information. 808 809 assert(!S->getEntity() && "scope already has entity"); 810 811#ifndef NDEBUG 812 Scope *Ancestor = S->getParent(); 813 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 814 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 815#endif 816 817 CurContext = DC; 818 S->setEntity(DC); 819} 820 821void Sema::ExitDeclaratorContext(Scope *S) { 822 assert(S->getEntity() == CurContext && "Context imbalance!"); 823 824 // Switch back to the lexical context. The safety of this is 825 // enforced by an assert in EnterDeclaratorContext. 826 Scope *Ancestor = S->getParent(); 827 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 828 CurContext = (DeclContext*) Ancestor->getEntity(); 829 830 // We don't need to do anything with the scope, which is going to 831 // disappear. 832} 833 834 835void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 836 FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 837 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) { 838 // We assume that the caller has already called 839 // ActOnReenterTemplateScope 840 FD = TFD->getTemplatedDecl(); 841 } 842 if (!FD) 843 return; 844 845 PushDeclContext(S, FD); 846 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 847 ParmVarDecl *Param = FD->getParamDecl(P); 848 // If the parameter has an identifier, then add it to the scope 849 if (Param->getIdentifier()) { 850 S->AddDecl(Param); 851 IdResolver.AddDecl(Param); 852 } 853 } 854} 855 856 857/// \brief Determine whether we allow overloading of the function 858/// PrevDecl with another declaration. 859/// 860/// This routine determines whether overloading is possible, not 861/// whether some new function is actually an overload. It will return 862/// true in C++ (where we can always provide overloads) or, as an 863/// extension, in C when the previous function is already an 864/// overloaded function declaration or has the "overloadable" 865/// attribute. 866static bool AllowOverloadingOfFunction(LookupResult &Previous, 867 ASTContext &Context) { 868 if (Context.getLangOptions().CPlusPlus) 869 return true; 870 871 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 872 return true; 873 874 return (Previous.getResultKind() == LookupResult::Found 875 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 876} 877 878/// Add this decl to the scope shadowed decl chains. 879void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 880 // Move up the scope chain until we find the nearest enclosing 881 // non-transparent context. The declaration will be introduced into this 882 // scope. 883 while (S->getEntity() && 884 ((DeclContext *)S->getEntity())->isTransparentContext()) 885 S = S->getParent(); 886 887 // Add scoped declarations into their context, so that they can be 888 // found later. Declarations without a context won't be inserted 889 // into any context. 890 if (AddToContext) 891 CurContext->addDecl(D); 892 893 // Out-of-line definitions shouldn't be pushed into scope in C++. 894 // Out-of-line variable and function definitions shouldn't even in C. 895 if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) && 896 D->isOutOfLine() && 897 !D->getDeclContext()->getRedeclContext()->Equals( 898 D->getLexicalDeclContext()->getRedeclContext())) 899 return; 900 901 // Template instantiations should also not be pushed into scope. 902 if (isa<FunctionDecl>(D) && 903 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 904 return; 905 906 // If this replaces anything in the current scope, 907 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 908 IEnd = IdResolver.end(); 909 for (; I != IEnd; ++I) { 910 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 911 S->RemoveDecl(*I); 912 IdResolver.RemoveDecl(*I); 913 914 // Should only need to replace one decl. 915 break; 916 } 917 } 918 919 S->AddDecl(D); 920 921 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 922 // Implicitly-generated labels may end up getting generated in an order that 923 // isn't strictly lexical, which breaks name lookup. Be careful to insert 924 // the label at the appropriate place in the identifier chain. 925 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 926 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 927 if (IDC == CurContext) { 928 if (!S->isDeclScope(*I)) 929 continue; 930 } else if (IDC->Encloses(CurContext)) 931 break; 932 } 933 934 IdResolver.InsertDeclAfter(I, D); 935 } else { 936 IdResolver.AddDecl(D); 937 } 938} 939 940void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 941 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 942 TUScope->AddDecl(D); 943} 944 945bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S, 946 bool ExplicitInstantiationOrSpecialization) { 947 return IdResolver.isDeclInScope(D, Ctx, Context, S, 948 ExplicitInstantiationOrSpecialization); 949} 950 951Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 952 DeclContext *TargetDC = DC->getPrimaryContext(); 953 do { 954 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity()) 955 if (ScopeDC->getPrimaryContext() == TargetDC) 956 return S; 957 } while ((S = S->getParent())); 958 959 return 0; 960} 961 962static bool isOutOfScopePreviousDeclaration(NamedDecl *, 963 DeclContext*, 964 ASTContext&); 965 966/// Filters out lookup results that don't fall within the given scope 967/// as determined by isDeclInScope. 968void Sema::FilterLookupForScope(LookupResult &R, 969 DeclContext *Ctx, Scope *S, 970 bool ConsiderLinkage, 971 bool ExplicitInstantiationOrSpecialization) { 972 LookupResult::Filter F = R.makeFilter(); 973 while (F.hasNext()) { 974 NamedDecl *D = F.next(); 975 976 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization)) 977 continue; 978 979 if (ConsiderLinkage && 980 isOutOfScopePreviousDeclaration(D, Ctx, Context)) 981 continue; 982 983 F.erase(); 984 } 985 986 F.done(); 987} 988 989static bool isUsingDecl(NamedDecl *D) { 990 return isa<UsingShadowDecl>(D) || 991 isa<UnresolvedUsingTypenameDecl>(D) || 992 isa<UnresolvedUsingValueDecl>(D); 993} 994 995/// Removes using shadow declarations from the lookup results. 996static void RemoveUsingDecls(LookupResult &R) { 997 LookupResult::Filter F = R.makeFilter(); 998 while (F.hasNext()) 999 if (isUsingDecl(F.next())) 1000 F.erase(); 1001 1002 F.done(); 1003} 1004 1005/// \brief Check for this common pattern: 1006/// @code 1007/// class S { 1008/// S(const S&); // DO NOT IMPLEMENT 1009/// void operator=(const S&); // DO NOT IMPLEMENT 1010/// }; 1011/// @endcode 1012static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1013 // FIXME: Should check for private access too but access is set after we get 1014 // the decl here. 1015 if (D->doesThisDeclarationHaveABody()) 1016 return false; 1017 1018 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1019 return CD->isCopyConstructor(); 1020 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1021 return Method->isCopyAssignmentOperator(); 1022 return false; 1023} 1024 1025bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1026 assert(D); 1027 1028 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1029 return false; 1030 1031 // Ignore class templates. 1032 if (D->getDeclContext()->isDependentContext() || 1033 D->getLexicalDeclContext()->isDependentContext()) 1034 return false; 1035 1036 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1037 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1038 return false; 1039 1040 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1041 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1042 return false; 1043 } else { 1044 // 'static inline' functions are used in headers; don't warn. 1045 if (FD->getStorageClass() == SC_Static && 1046 FD->isInlineSpecified()) 1047 return false; 1048 } 1049 1050 if (FD->doesThisDeclarationHaveABody() && 1051 Context.DeclMustBeEmitted(FD)) 1052 return false; 1053 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1054 if (!VD->isFileVarDecl() || 1055 VD->getType().isConstant(Context) || 1056 Context.DeclMustBeEmitted(VD)) 1057 return false; 1058 1059 if (VD->isStaticDataMember() && 1060 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1061 return false; 1062 1063 } else { 1064 return false; 1065 } 1066 1067 // Only warn for unused decls internal to the translation unit. 1068 if (D->getLinkage() == ExternalLinkage) 1069 return false; 1070 1071 return true; 1072} 1073 1074void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1075 if (!D) 1076 return; 1077 1078 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1079 const FunctionDecl *First = FD->getFirstDeclaration(); 1080 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1081 return; // First should already be in the vector. 1082 } 1083 1084 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1085 const VarDecl *First = VD->getFirstDeclaration(); 1086 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1087 return; // First should already be in the vector. 1088 } 1089 1090 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1091 UnusedFileScopedDecls.push_back(D); 1092 } 1093 1094static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1095 if (D->isInvalidDecl()) 1096 return false; 1097 1098 if (D->isUsed() || D->hasAttr<UnusedAttr>()) 1099 return false; 1100 1101 if (isa<LabelDecl>(D)) 1102 return true; 1103 1104 // White-list anything that isn't a local variable. 1105 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1106 !D->getDeclContext()->isFunctionOrMethod()) 1107 return false; 1108 1109 // Types of valid local variables should be complete, so this should succeed. 1110 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 1111 1112 // White-list anything with an __attribute__((unused)) type. 1113 QualType Ty = VD->getType(); 1114 1115 // Only look at the outermost level of typedef. 1116 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) { 1117 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1118 return false; 1119 } 1120 1121 // If we failed to complete the type for some reason, or if the type is 1122 // dependent, don't diagnose the variable. 1123 if (Ty->isIncompleteType() || Ty->isDependentType()) 1124 return false; 1125 1126 if (const TagType *TT = Ty->getAs<TagType>()) { 1127 const TagDecl *Tag = TT->getDecl(); 1128 if (Tag->hasAttr<UnusedAttr>()) 1129 return false; 1130 1131 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1132 // FIXME: Checking for the presence of a user-declared constructor 1133 // isn't completely accurate; we'd prefer to check that the initializer 1134 // has no side effects. 1135 if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor()) 1136 return false; 1137 } 1138 } 1139 1140 // TODO: __attribute__((unused)) templates? 1141 } 1142 1143 return true; 1144} 1145 1146static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1147 FixItHint &Hint) { 1148 if (isa<LabelDecl>(D)) { 1149 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1150 tok::colon, Ctx.getSourceManager(), Ctx.getLangOptions(), true); 1151 if (AfterColon.isInvalid()) 1152 return; 1153 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1154 getCharRange(D->getLocStart(), AfterColon)); 1155 } 1156 return; 1157} 1158 1159/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1160/// unless they are marked attr(unused). 1161void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1162 FixItHint Hint; 1163 if (!ShouldDiagnoseUnusedDecl(D)) 1164 return; 1165 1166 GenerateFixForUnusedDecl(D, Context, Hint); 1167 1168 unsigned DiagID; 1169 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1170 DiagID = diag::warn_unused_exception_param; 1171 else if (isa<LabelDecl>(D)) 1172 DiagID = diag::warn_unused_label; 1173 else 1174 DiagID = diag::warn_unused_variable; 1175 1176 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1177} 1178 1179static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1180 // Verify that we have no forward references left. If so, there was a goto 1181 // or address of a label taken, but no definition of it. Label fwd 1182 // definitions are indicated with a null substmt. 1183 if (L->getStmt() == 0) 1184 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1185} 1186 1187void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1188 if (S->decl_empty()) return; 1189 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1190 "Scope shouldn't contain decls!"); 1191 1192 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 1193 I != E; ++I) { 1194 Decl *TmpD = (*I); 1195 assert(TmpD && "This decl didn't get pushed??"); 1196 1197 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1198 NamedDecl *D = cast<NamedDecl>(TmpD); 1199 1200 if (!D->getDeclName()) continue; 1201 1202 // Diagnose unused variables in this scope. 1203 if (!S->hasErrorOccurred()) 1204 DiagnoseUnusedDecl(D); 1205 1206 // If this was a forward reference to a label, verify it was defined. 1207 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1208 CheckPoppedLabel(LD, *this); 1209 1210 // Remove this name from our lexical scope. 1211 IdResolver.RemoveDecl(D); 1212 } 1213} 1214 1215/// \brief Look for an Objective-C class in the translation unit. 1216/// 1217/// \param Id The name of the Objective-C class we're looking for. If 1218/// typo-correction fixes this name, the Id will be updated 1219/// to the fixed name. 1220/// 1221/// \param IdLoc The location of the name in the translation unit. 1222/// 1223/// \param TypoCorrection If true, this routine will attempt typo correction 1224/// if there is no class with the given name. 1225/// 1226/// \returns The declaration of the named Objective-C class, or NULL if the 1227/// class could not be found. 1228ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1229 SourceLocation IdLoc, 1230 bool DoTypoCorrection) { 1231 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1232 // creation from this context. 1233 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1234 1235 if (!IDecl && DoTypoCorrection) { 1236 // Perform typo correction at the given location, but only if we 1237 // find an Objective-C class name. 1238 TypoCorrection C; 1239 if ((C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1240 TUScope, NULL, NULL, false, CTC_NoKeywords)) && 1241 (IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>())) { 1242 Diag(IdLoc, diag::err_undef_interface_suggest) 1243 << Id << IDecl->getDeclName() 1244 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString()); 1245 Diag(IDecl->getLocation(), diag::note_previous_decl) 1246 << IDecl->getDeclName(); 1247 1248 Id = IDecl->getIdentifier(); 1249 } 1250 } 1251 1252 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1253} 1254 1255/// getNonFieldDeclScope - Retrieves the innermost scope, starting 1256/// from S, where a non-field would be declared. This routine copes 1257/// with the difference between C and C++ scoping rules in structs and 1258/// unions. For example, the following code is well-formed in C but 1259/// ill-formed in C++: 1260/// @code 1261/// struct S6 { 1262/// enum { BAR } e; 1263/// }; 1264/// 1265/// void test_S6() { 1266/// struct S6 a; 1267/// a.e = BAR; 1268/// } 1269/// @endcode 1270/// For the declaration of BAR, this routine will return a different 1271/// scope. The scope S will be the scope of the unnamed enumeration 1272/// within S6. In C++, this routine will return the scope associated 1273/// with S6, because the enumeration's scope is a transparent 1274/// context but structures can contain non-field names. In C, this 1275/// routine will return the translation unit scope, since the 1276/// enumeration's scope is a transparent context and structures cannot 1277/// contain non-field names. 1278Scope *Sema::getNonFieldDeclScope(Scope *S) { 1279 while (((S->getFlags() & Scope::DeclScope) == 0) || 1280 (S->getEntity() && 1281 ((DeclContext *)S->getEntity())->isTransparentContext()) || 1282 (S->isClassScope() && !getLangOptions().CPlusPlus)) 1283 S = S->getParent(); 1284 return S; 1285} 1286 1287/// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1288/// file scope. lazily create a decl for it. ForRedeclaration is true 1289/// if we're creating this built-in in anticipation of redeclaring the 1290/// built-in. 1291NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1292 Scope *S, bool ForRedeclaration, 1293 SourceLocation Loc) { 1294 Builtin::ID BID = (Builtin::ID)bid; 1295 1296 ASTContext::GetBuiltinTypeError Error; 1297 QualType R = Context.GetBuiltinType(BID, Error); 1298 switch (Error) { 1299 case ASTContext::GE_None: 1300 // Okay 1301 break; 1302 1303 case ASTContext::GE_Missing_stdio: 1304 if (ForRedeclaration) 1305 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1306 << Context.BuiltinInfo.GetName(BID); 1307 return 0; 1308 1309 case ASTContext::GE_Missing_setjmp: 1310 if (ForRedeclaration) 1311 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1312 << Context.BuiltinInfo.GetName(BID); 1313 return 0; 1314 1315 case ASTContext::GE_Missing_ucontext: 1316 if (ForRedeclaration) 1317 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 1318 << Context.BuiltinInfo.GetName(BID); 1319 return 0; 1320 } 1321 1322 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1323 Diag(Loc, diag::ext_implicit_lib_function_decl) 1324 << Context.BuiltinInfo.GetName(BID) 1325 << R; 1326 if (Context.BuiltinInfo.getHeaderName(BID) && 1327 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1328 != DiagnosticsEngine::Ignored) 1329 Diag(Loc, diag::note_please_include_header) 1330 << Context.BuiltinInfo.getHeaderName(BID) 1331 << Context.BuiltinInfo.GetName(BID); 1332 } 1333 1334 FunctionDecl *New = FunctionDecl::Create(Context, 1335 Context.getTranslationUnitDecl(), 1336 Loc, Loc, II, R, /*TInfo=*/0, 1337 SC_Extern, 1338 SC_None, false, 1339 /*hasPrototype=*/true); 1340 New->setImplicit(); 1341 1342 // Create Decl objects for each parameter, adding them to the 1343 // FunctionDecl. 1344 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1345 SmallVector<ParmVarDecl*, 16> Params; 1346 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) { 1347 ParmVarDecl *parm = 1348 ParmVarDecl::Create(Context, New, SourceLocation(), 1349 SourceLocation(), 0, 1350 FT->getArgType(i), /*TInfo=*/0, 1351 SC_None, SC_None, 0); 1352 parm->setScopeInfo(0, i); 1353 Params.push_back(parm); 1354 } 1355 New->setParams(Params); 1356 } 1357 1358 AddKnownFunctionAttributes(New); 1359 1360 // TUScope is the translation-unit scope to insert this function into. 1361 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1362 // relate Scopes to DeclContexts, and probably eliminate CurContext 1363 // entirely, but we're not there yet. 1364 DeclContext *SavedContext = CurContext; 1365 CurContext = Context.getTranslationUnitDecl(); 1366 PushOnScopeChains(New, TUScope); 1367 CurContext = SavedContext; 1368 return New; 1369} 1370 1371/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1372/// same name and scope as a previous declaration 'Old'. Figure out 1373/// how to resolve this situation, merging decls or emitting 1374/// diagnostics as appropriate. If there was an error, set New to be invalid. 1375/// 1376void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1377 // If the new decl is known invalid already, don't bother doing any 1378 // merging checks. 1379 if (New->isInvalidDecl()) return; 1380 1381 // Allow multiple definitions for ObjC built-in typedefs. 1382 // FIXME: Verify the underlying types are equivalent! 1383 if (getLangOptions().ObjC1) { 1384 const IdentifierInfo *TypeID = New->getIdentifier(); 1385 switch (TypeID->getLength()) { 1386 default: break; 1387 case 2: 1388 if (!TypeID->isStr("id")) 1389 break; 1390 Context.setObjCIdRedefinitionType(New->getUnderlyingType()); 1391 // Install the built-in type for 'id', ignoring the current definition. 1392 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1393 return; 1394 case 5: 1395 if (!TypeID->isStr("Class")) 1396 break; 1397 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1398 // Install the built-in type for 'Class', ignoring the current definition. 1399 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1400 return; 1401 case 3: 1402 if (!TypeID->isStr("SEL")) 1403 break; 1404 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1405 // Install the built-in type for 'SEL', ignoring the current definition. 1406 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1407 return; 1408 } 1409 // Fall through - the typedef name was not a builtin type. 1410 } 1411 1412 // Verify the old decl was also a type. 1413 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1414 if (!Old) { 1415 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1416 << New->getDeclName(); 1417 1418 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1419 if (OldD->getLocation().isValid()) 1420 Diag(OldD->getLocation(), diag::note_previous_definition); 1421 1422 return New->setInvalidDecl(); 1423 } 1424 1425 // If the old declaration is invalid, just give up here. 1426 if (Old->isInvalidDecl()) 1427 return New->setInvalidDecl(); 1428 1429 // Determine the "old" type we'll use for checking and diagnostics. 1430 QualType OldType; 1431 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1432 OldType = OldTypedef->getUnderlyingType(); 1433 else 1434 OldType = Context.getTypeDeclType(Old); 1435 1436 // If the typedef types are not identical, reject them in all languages and 1437 // with any extensions enabled. 1438 1439 if (OldType != New->getUnderlyingType() && 1440 Context.getCanonicalType(OldType) != 1441 Context.getCanonicalType(New->getUnderlyingType())) { 1442 int Kind = 0; 1443 if (isa<TypeAliasDecl>(Old)) 1444 Kind = 1; 1445 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1446 << Kind << New->getUnderlyingType() << OldType; 1447 if (Old->getLocation().isValid()) 1448 Diag(Old->getLocation(), diag::note_previous_definition); 1449 return New->setInvalidDecl(); 1450 } 1451 1452 // The types match. Link up the redeclaration chain if the old 1453 // declaration was a typedef. 1454 // FIXME: this is a potential source of weirdness if the type 1455 // spellings don't match exactly. 1456 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) 1457 New->setPreviousDeclaration(Typedef); 1458 1459 // __module_private__ is propagated to later declarations. 1460 if (Old->isModulePrivate()) 1461 New->setModulePrivate(); 1462 else if (New->isModulePrivate()) 1463 diagnoseModulePrivateRedeclaration(New, Old); 1464 1465 if (getLangOptions().MicrosoftExt) 1466 return; 1467 1468 if (getLangOptions().CPlusPlus) { 1469 // C++ [dcl.typedef]p2: 1470 // In a given non-class scope, a typedef specifier can be used to 1471 // redefine the name of any type declared in that scope to refer 1472 // to the type to which it already refers. 1473 if (!isa<CXXRecordDecl>(CurContext)) 1474 return; 1475 1476 // C++0x [dcl.typedef]p4: 1477 // In a given class scope, a typedef specifier can be used to redefine 1478 // any class-name declared in that scope that is not also a typedef-name 1479 // to refer to the type to which it already refers. 1480 // 1481 // This wording came in via DR424, which was a correction to the 1482 // wording in DR56, which accidentally banned code like: 1483 // 1484 // struct S { 1485 // typedef struct A { } A; 1486 // }; 1487 // 1488 // in the C++03 standard. We implement the C++0x semantics, which 1489 // allow the above but disallow 1490 // 1491 // struct S { 1492 // typedef int I; 1493 // typedef int I; 1494 // }; 1495 // 1496 // since that was the intent of DR56. 1497 if (!isa<TypedefNameDecl>(Old)) 1498 return; 1499 1500 Diag(New->getLocation(), diag::err_redefinition) 1501 << New->getDeclName(); 1502 Diag(Old->getLocation(), diag::note_previous_definition); 1503 return New->setInvalidDecl(); 1504 } 1505 1506 // If we have a redefinition of a typedef in C, emit a warning. This warning 1507 // is normally mapped to an error, but can be controlled with 1508 // -Wtypedef-redefinition. If either the original or the redefinition is 1509 // in a system header, don't emit this for compatibility with GCC. 1510 if (getDiagnostics().getSuppressSystemWarnings() && 1511 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1512 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1513 return; 1514 1515 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1516 << New->getDeclName(); 1517 Diag(Old->getLocation(), diag::note_previous_definition); 1518 return; 1519} 1520 1521/// DeclhasAttr - returns true if decl Declaration already has the target 1522/// attribute. 1523static bool 1524DeclHasAttr(const Decl *D, const Attr *A) { 1525 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1526 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1527 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 1528 if ((*i)->getKind() == A->getKind()) { 1529 if (Ann) { 1530 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation()) 1531 return true; 1532 continue; 1533 } 1534 // FIXME: Don't hardcode this check 1535 if (OA && isa<OwnershipAttr>(*i)) 1536 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 1537 return true; 1538 } 1539 1540 return false; 1541} 1542 1543/// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 1544static void mergeDeclAttributes(Decl *newDecl, const Decl *oldDecl, 1545 ASTContext &C, bool mergeDeprecation = true) { 1546 if (!oldDecl->hasAttrs()) 1547 return; 1548 1549 bool foundAny = newDecl->hasAttrs(); 1550 1551 // Ensure that any moving of objects within the allocated map is done before 1552 // we process them. 1553 if (!foundAny) newDecl->setAttrs(AttrVec()); 1554 1555 for (specific_attr_iterator<InheritableAttr> 1556 i = oldDecl->specific_attr_begin<InheritableAttr>(), 1557 e = oldDecl->specific_attr_end<InheritableAttr>(); i != e; ++i) { 1558 // Ignore deprecated/unavailable/availability attributes if requested. 1559 if (!mergeDeprecation && 1560 (isa<DeprecatedAttr>(*i) || 1561 isa<UnavailableAttr>(*i) || 1562 isa<AvailabilityAttr>(*i))) 1563 continue; 1564 1565 if (!DeclHasAttr(newDecl, *i)) { 1566 InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(C)); 1567 newAttr->setInherited(true); 1568 newDecl->addAttr(newAttr); 1569 foundAny = true; 1570 } 1571 } 1572 1573 if (!foundAny) newDecl->dropAttrs(); 1574} 1575 1576/// mergeParamDeclAttributes - Copy attributes from the old parameter 1577/// to the new one. 1578static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 1579 const ParmVarDecl *oldDecl, 1580 ASTContext &C) { 1581 if (!oldDecl->hasAttrs()) 1582 return; 1583 1584 bool foundAny = newDecl->hasAttrs(); 1585 1586 // Ensure that any moving of objects within the allocated map is 1587 // done before we process them. 1588 if (!foundAny) newDecl->setAttrs(AttrVec()); 1589 1590 for (specific_attr_iterator<InheritableParamAttr> 1591 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 1592 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 1593 if (!DeclHasAttr(newDecl, *i)) { 1594 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C)); 1595 newAttr->setInherited(true); 1596 newDecl->addAttr(newAttr); 1597 foundAny = true; 1598 } 1599 } 1600 1601 if (!foundAny) newDecl->dropAttrs(); 1602} 1603 1604namespace { 1605 1606/// Used in MergeFunctionDecl to keep track of function parameters in 1607/// C. 1608struct GNUCompatibleParamWarning { 1609 ParmVarDecl *OldParm; 1610 ParmVarDecl *NewParm; 1611 QualType PromotedType; 1612}; 1613 1614} 1615 1616/// getSpecialMember - get the special member enum for a method. 1617Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 1618 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 1619 if (Ctor->isDefaultConstructor()) 1620 return Sema::CXXDefaultConstructor; 1621 1622 if (Ctor->isCopyConstructor()) 1623 return Sema::CXXCopyConstructor; 1624 1625 if (Ctor->isMoveConstructor()) 1626 return Sema::CXXMoveConstructor; 1627 } else if (isa<CXXDestructorDecl>(MD)) { 1628 return Sema::CXXDestructor; 1629 } else if (MD->isCopyAssignmentOperator()) { 1630 return Sema::CXXCopyAssignment; 1631 } else if (MD->isMoveAssignmentOperator()) { 1632 return Sema::CXXMoveAssignment; 1633 } 1634 1635 return Sema::CXXInvalid; 1636} 1637 1638/// canRedefineFunction - checks if a function can be redefined. Currently, 1639/// only extern inline functions can be redefined, and even then only in 1640/// GNU89 mode. 1641static bool canRedefineFunction(const FunctionDecl *FD, 1642 const LangOptions& LangOpts) { 1643 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 1644 !LangOpts.CPlusPlus && 1645 FD->isInlineSpecified() && 1646 FD->getStorageClass() == SC_Extern); 1647} 1648 1649/// MergeFunctionDecl - We just parsed a function 'New' from 1650/// declarator D which has the same name and scope as a previous 1651/// declaration 'Old'. Figure out how to resolve this situation, 1652/// merging decls or emitting diagnostics as appropriate. 1653/// 1654/// In C++, New and Old must be declarations that are not 1655/// overloaded. Use IsOverload to determine whether New and Old are 1656/// overloaded, and to select the Old declaration that New should be 1657/// merged with. 1658/// 1659/// Returns true if there was an error, false otherwise. 1660bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) { 1661 // Verify the old decl was also a function. 1662 FunctionDecl *Old = 0; 1663 if (FunctionTemplateDecl *OldFunctionTemplate 1664 = dyn_cast<FunctionTemplateDecl>(OldD)) 1665 Old = OldFunctionTemplate->getTemplatedDecl(); 1666 else 1667 Old = dyn_cast<FunctionDecl>(OldD); 1668 if (!Old) { 1669 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 1670 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 1671 Diag(Shadow->getTargetDecl()->getLocation(), 1672 diag::note_using_decl_target); 1673 Diag(Shadow->getUsingDecl()->getLocation(), 1674 diag::note_using_decl) << 0; 1675 return true; 1676 } 1677 1678 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1679 << New->getDeclName(); 1680 Diag(OldD->getLocation(), diag::note_previous_definition); 1681 return true; 1682 } 1683 1684 // Determine whether the previous declaration was a definition, 1685 // implicit declaration, or a declaration. 1686 diag::kind PrevDiag; 1687 if (Old->isThisDeclarationADefinition()) 1688 PrevDiag = diag::note_previous_definition; 1689 else if (Old->isImplicit()) 1690 PrevDiag = diag::note_previous_implicit_declaration; 1691 else 1692 PrevDiag = diag::note_previous_declaration; 1693 1694 QualType OldQType = Context.getCanonicalType(Old->getType()); 1695 QualType NewQType = Context.getCanonicalType(New->getType()); 1696 1697 // Don't complain about this if we're in GNU89 mode and the old function 1698 // is an extern inline function. 1699 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 1700 New->getStorageClass() == SC_Static && 1701 Old->getStorageClass() != SC_Static && 1702 !canRedefineFunction(Old, getLangOptions())) { 1703 if (getLangOptions().MicrosoftExt) { 1704 Diag(New->getLocation(), diag::warn_static_non_static) << New; 1705 Diag(Old->getLocation(), PrevDiag); 1706 } else { 1707 Diag(New->getLocation(), diag::err_static_non_static) << New; 1708 Diag(Old->getLocation(), PrevDiag); 1709 return true; 1710 } 1711 } 1712 1713 // If a function is first declared with a calling convention, but is 1714 // later declared or defined without one, the second decl assumes the 1715 // calling convention of the first. 1716 // 1717 // For the new decl, we have to look at the NON-canonical type to tell the 1718 // difference between a function that really doesn't have a calling 1719 // convention and one that is declared cdecl. That's because in 1720 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away 1721 // because it is the default calling convention. 1722 // 1723 // Note also that we DO NOT return at this point, because we still have 1724 // other tests to run. 1725 const FunctionType *OldType = cast<FunctionType>(OldQType); 1726 const FunctionType *NewType = New->getType()->getAs<FunctionType>(); 1727 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 1728 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 1729 bool RequiresAdjustment = false; 1730 if (OldTypeInfo.getCC() != CC_Default && 1731 NewTypeInfo.getCC() == CC_Default) { 1732 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 1733 RequiresAdjustment = true; 1734 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(), 1735 NewTypeInfo.getCC())) { 1736 // Calling conventions really aren't compatible, so complain. 1737 Diag(New->getLocation(), diag::err_cconv_change) 1738 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 1739 << (OldTypeInfo.getCC() == CC_Default) 1740 << (OldTypeInfo.getCC() == CC_Default ? "" : 1741 FunctionType::getNameForCallConv(OldTypeInfo.getCC())); 1742 Diag(Old->getLocation(), diag::note_previous_declaration); 1743 return true; 1744 } 1745 1746 // FIXME: diagnose the other way around? 1747 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 1748 NewTypeInfo = NewTypeInfo.withNoReturn(true); 1749 RequiresAdjustment = true; 1750 } 1751 1752 // Merge regparm attribute. 1753 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 1754 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 1755 if (NewTypeInfo.getHasRegParm()) { 1756 Diag(New->getLocation(), diag::err_regparm_mismatch) 1757 << NewType->getRegParmType() 1758 << OldType->getRegParmType(); 1759 Diag(Old->getLocation(), diag::note_previous_declaration); 1760 return true; 1761 } 1762 1763 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 1764 RequiresAdjustment = true; 1765 } 1766 1767 // Merge ns_returns_retained attribute. 1768 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 1769 if (NewTypeInfo.getProducesResult()) { 1770 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 1771 Diag(Old->getLocation(), diag::note_previous_declaration); 1772 return true; 1773 } 1774 1775 NewTypeInfo = NewTypeInfo.withProducesResult(true); 1776 RequiresAdjustment = true; 1777 } 1778 1779 if (RequiresAdjustment) { 1780 NewType = Context.adjustFunctionType(NewType, NewTypeInfo); 1781 New->setType(QualType(NewType, 0)); 1782 NewQType = Context.getCanonicalType(New->getType()); 1783 } 1784 1785 if (getLangOptions().CPlusPlus) { 1786 // (C++98 13.1p2): 1787 // Certain function declarations cannot be overloaded: 1788 // -- Function declarations that differ only in the return type 1789 // cannot be overloaded. 1790 QualType OldReturnType = OldType->getResultType(); 1791 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType(); 1792 QualType ResQT; 1793 if (OldReturnType != NewReturnType) { 1794 if (NewReturnType->isObjCObjectPointerType() 1795 && OldReturnType->isObjCObjectPointerType()) 1796 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 1797 if (ResQT.isNull()) { 1798 if (New->isCXXClassMember() && New->isOutOfLine()) 1799 Diag(New->getLocation(), 1800 diag::err_member_def_does_not_match_ret_type) << New; 1801 else 1802 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 1803 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1804 return true; 1805 } 1806 else 1807 NewQType = ResQT; 1808 } 1809 1810 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 1811 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 1812 if (OldMethod && NewMethod) { 1813 // Preserve triviality. 1814 NewMethod->setTrivial(OldMethod->isTrivial()); 1815 1816 // MSVC allows explicit template specialization at class scope: 1817 // 2 CXMethodDecls referring to the same function will be injected. 1818 // We don't want a redeclartion error. 1819 bool IsClassScopeExplicitSpecialization = 1820 OldMethod->isFunctionTemplateSpecialization() && 1821 NewMethod->isFunctionTemplateSpecialization(); 1822 bool isFriend = NewMethod->getFriendObjectKind(); 1823 1824 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 1825 !IsClassScopeExplicitSpecialization) { 1826 // -- Member function declarations with the same name and the 1827 // same parameter types cannot be overloaded if any of them 1828 // is a static member function declaration. 1829 if (OldMethod->isStatic() || NewMethod->isStatic()) { 1830 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 1831 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1832 return true; 1833 } 1834 1835 // C++ [class.mem]p1: 1836 // [...] A member shall not be declared twice in the 1837 // member-specification, except that a nested class or member 1838 // class template can be declared and then later defined. 1839 unsigned NewDiag; 1840 if (isa<CXXConstructorDecl>(OldMethod)) 1841 NewDiag = diag::err_constructor_redeclared; 1842 else if (isa<CXXDestructorDecl>(NewMethod)) 1843 NewDiag = diag::err_destructor_redeclared; 1844 else if (isa<CXXConversionDecl>(NewMethod)) 1845 NewDiag = diag::err_conv_function_redeclared; 1846 else 1847 NewDiag = diag::err_member_redeclared; 1848 1849 Diag(New->getLocation(), NewDiag); 1850 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1851 1852 // Complain if this is an explicit declaration of a special 1853 // member that was initially declared implicitly. 1854 // 1855 // As an exception, it's okay to befriend such methods in order 1856 // to permit the implicit constructor/destructor/operator calls. 1857 } else if (OldMethod->isImplicit()) { 1858 if (isFriend) { 1859 NewMethod->setImplicit(); 1860 } else { 1861 Diag(NewMethod->getLocation(), 1862 diag::err_definition_of_implicitly_declared_member) 1863 << New << getSpecialMember(OldMethod); 1864 return true; 1865 } 1866 } else if (OldMethod->isExplicitlyDefaulted()) { 1867 Diag(NewMethod->getLocation(), 1868 diag::err_definition_of_explicitly_defaulted_member) 1869 << getSpecialMember(OldMethod); 1870 return true; 1871 } 1872 } 1873 1874 // (C++98 8.3.5p3): 1875 // All declarations for a function shall agree exactly in both the 1876 // return type and the parameter-type-list. 1877 // We also want to respect all the extended bits except noreturn. 1878 1879 // noreturn should now match unless the old type info didn't have it. 1880 QualType OldQTypeForComparison = OldQType; 1881 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 1882 assert(OldQType == QualType(OldType, 0)); 1883 const FunctionType *OldTypeForComparison 1884 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 1885 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 1886 assert(OldQTypeForComparison.isCanonical()); 1887 } 1888 1889 if (OldQTypeForComparison == NewQType) 1890 return MergeCompatibleFunctionDecls(New, Old); 1891 1892 // Fall through for conflicting redeclarations and redefinitions. 1893 } 1894 1895 // C: Function types need to be compatible, not identical. This handles 1896 // duplicate function decls like "void f(int); void f(enum X);" properly. 1897 if (!getLangOptions().CPlusPlus && 1898 Context.typesAreCompatible(OldQType, NewQType)) { 1899 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 1900 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 1901 const FunctionProtoType *OldProto = 0; 1902 if (isa<FunctionNoProtoType>(NewFuncType) && 1903 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 1904 // The old declaration provided a function prototype, but the 1905 // new declaration does not. Merge in the prototype. 1906 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 1907 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 1908 OldProto->arg_type_end()); 1909 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 1910 ParamTypes.data(), ParamTypes.size(), 1911 OldProto->getExtProtoInfo()); 1912 New->setType(NewQType); 1913 New->setHasInheritedPrototype(); 1914 1915 // Synthesize a parameter for each argument type. 1916 SmallVector<ParmVarDecl*, 16> Params; 1917 for (FunctionProtoType::arg_type_iterator 1918 ParamType = OldProto->arg_type_begin(), 1919 ParamEnd = OldProto->arg_type_end(); 1920 ParamType != ParamEnd; ++ParamType) { 1921 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 1922 SourceLocation(), 1923 SourceLocation(), 0, 1924 *ParamType, /*TInfo=*/0, 1925 SC_None, SC_None, 1926 0); 1927 Param->setScopeInfo(0, Params.size()); 1928 Param->setImplicit(); 1929 Params.push_back(Param); 1930 } 1931 1932 New->setParams(Params); 1933 } 1934 1935 return MergeCompatibleFunctionDecls(New, Old); 1936 } 1937 1938 // GNU C permits a K&R definition to follow a prototype declaration 1939 // if the declared types of the parameters in the K&R definition 1940 // match the types in the prototype declaration, even when the 1941 // promoted types of the parameters from the K&R definition differ 1942 // from the types in the prototype. GCC then keeps the types from 1943 // the prototype. 1944 // 1945 // If a variadic prototype is followed by a non-variadic K&R definition, 1946 // the K&R definition becomes variadic. This is sort of an edge case, but 1947 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 1948 // C99 6.9.1p8. 1949 if (!getLangOptions().CPlusPlus && 1950 Old->hasPrototype() && !New->hasPrototype() && 1951 New->getType()->getAs<FunctionProtoType>() && 1952 Old->getNumParams() == New->getNumParams()) { 1953 SmallVector<QualType, 16> ArgTypes; 1954 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 1955 const FunctionProtoType *OldProto 1956 = Old->getType()->getAs<FunctionProtoType>(); 1957 const FunctionProtoType *NewProto 1958 = New->getType()->getAs<FunctionProtoType>(); 1959 1960 // Determine whether this is the GNU C extension. 1961 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 1962 NewProto->getResultType()); 1963 bool LooseCompatible = !MergedReturn.isNull(); 1964 for (unsigned Idx = 0, End = Old->getNumParams(); 1965 LooseCompatible && Idx != End; ++Idx) { 1966 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 1967 ParmVarDecl *NewParm = New->getParamDecl(Idx); 1968 if (Context.typesAreCompatible(OldParm->getType(), 1969 NewProto->getArgType(Idx))) { 1970 ArgTypes.push_back(NewParm->getType()); 1971 } else if (Context.typesAreCompatible(OldParm->getType(), 1972 NewParm->getType(), 1973 /*CompareUnqualified=*/true)) { 1974 GNUCompatibleParamWarning Warn 1975 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 1976 Warnings.push_back(Warn); 1977 ArgTypes.push_back(NewParm->getType()); 1978 } else 1979 LooseCompatible = false; 1980 } 1981 1982 if (LooseCompatible) { 1983 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 1984 Diag(Warnings[Warn].NewParm->getLocation(), 1985 diag::ext_param_promoted_not_compatible_with_prototype) 1986 << Warnings[Warn].PromotedType 1987 << Warnings[Warn].OldParm->getType(); 1988 if (Warnings[Warn].OldParm->getLocation().isValid()) 1989 Diag(Warnings[Warn].OldParm->getLocation(), 1990 diag::note_previous_declaration); 1991 } 1992 1993 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0], 1994 ArgTypes.size(), 1995 OldProto->getExtProtoInfo())); 1996 return MergeCompatibleFunctionDecls(New, Old); 1997 } 1998 1999 // Fall through to diagnose conflicting types. 2000 } 2001 2002 // A function that has already been declared has been redeclared or defined 2003 // with a different type- show appropriate diagnostic 2004 if (unsigned BuiltinID = Old->getBuiltinID()) { 2005 // The user has declared a builtin function with an incompatible 2006 // signature. 2007 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2008 // The function the user is redeclaring is a library-defined 2009 // function like 'malloc' or 'printf'. Warn about the 2010 // redeclaration, then pretend that we don't know about this 2011 // library built-in. 2012 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2013 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 2014 << Old << Old->getType(); 2015 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2016 Old->setInvalidDecl(); 2017 return false; 2018 } 2019 2020 PrevDiag = diag::note_previous_builtin_declaration; 2021 } 2022 2023 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2024 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2025 return true; 2026} 2027 2028/// \brief Completes the merge of two function declarations that are 2029/// known to be compatible. 2030/// 2031/// This routine handles the merging of attributes and other 2032/// properties of function declarations form the old declaration to 2033/// the new declaration, once we know that New is in fact a 2034/// redeclaration of Old. 2035/// 2036/// \returns false 2037bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) { 2038 // Merge the attributes 2039 mergeDeclAttributes(New, Old, Context); 2040 2041 // Merge the storage class. 2042 if (Old->getStorageClass() != SC_Extern && 2043 Old->getStorageClass() != SC_None) 2044 New->setStorageClass(Old->getStorageClass()); 2045 2046 // Merge "pure" flag. 2047 if (Old->isPure()) 2048 New->setPure(); 2049 2050 // __module_private__ is propagated to later declarations. 2051 if (Old->isModulePrivate()) 2052 New->setModulePrivate(); 2053 else if (New->isModulePrivate()) 2054 diagnoseModulePrivateRedeclaration(New, Old); 2055 2056 // Merge attributes from the parameters. These can mismatch with K&R 2057 // declarations. 2058 if (New->getNumParams() == Old->getNumParams()) 2059 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2060 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2061 Context); 2062 2063 if (getLangOptions().CPlusPlus) 2064 return MergeCXXFunctionDecl(New, Old); 2065 2066 return false; 2067} 2068 2069 2070void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2071 const ObjCMethodDecl *oldMethod) { 2072 // We don't want to merge unavailable and deprecated attributes 2073 // except from interface to implementation. 2074 bool mergeDeprecation = isa<ObjCImplDecl>(newMethod->getDeclContext()); 2075 2076 // Merge the attributes. 2077 mergeDeclAttributes(newMethod, oldMethod, Context, mergeDeprecation); 2078 2079 // Merge attributes from the parameters. 2080 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(); 2081 for (ObjCMethodDecl::param_iterator 2082 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2083 ni != ne; ++ni, ++oi) 2084 mergeParamDeclAttributes(*ni, *oi, Context); 2085 2086 CheckObjCMethodOverride(newMethod, oldMethod, true); 2087} 2088 2089/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2090/// scope as a previous declaration 'Old'. Figure out how to merge their types, 2091/// emitting diagnostics as appropriate. 2092/// 2093/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2094/// to here in AddInitializerToDecl and AddCXXDirectInitializerToDecl. We can't 2095/// check them before the initializer is attached. 2096/// 2097void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) { 2098 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2099 return; 2100 2101 QualType MergedT; 2102 if (getLangOptions().CPlusPlus) { 2103 AutoType *AT = New->getType()->getContainedAutoType(); 2104 if (AT && !AT->isDeduced()) { 2105 // We don't know what the new type is until the initializer is attached. 2106 return; 2107 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2108 // These could still be something that needs exception specs checked. 2109 return MergeVarDeclExceptionSpecs(New, Old); 2110 } 2111 // C++ [basic.link]p10: 2112 // [...] the types specified by all declarations referring to a given 2113 // object or function shall be identical, except that declarations for an 2114 // array object can specify array types that differ by the presence or 2115 // absence of a major array bound (8.3.4). 2116 else if (Old->getType()->isIncompleteArrayType() && 2117 New->getType()->isArrayType()) { 2118 CanQual<ArrayType> OldArray 2119 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 2120 CanQual<ArrayType> NewArray 2121 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 2122 if (OldArray->getElementType() == NewArray->getElementType()) 2123 MergedT = New->getType(); 2124 } else if (Old->getType()->isArrayType() && 2125 New->getType()->isIncompleteArrayType()) { 2126 CanQual<ArrayType> OldArray 2127 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 2128 CanQual<ArrayType> NewArray 2129 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 2130 if (OldArray->getElementType() == NewArray->getElementType()) 2131 MergedT = Old->getType(); 2132 } else if (New->getType()->isObjCObjectPointerType() 2133 && Old->getType()->isObjCObjectPointerType()) { 2134 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2135 Old->getType()); 2136 } 2137 } else { 2138 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2139 } 2140 if (MergedT.isNull()) { 2141 Diag(New->getLocation(), diag::err_redefinition_different_type) 2142 << New->getDeclName(); 2143 Diag(Old->getLocation(), diag::note_previous_definition); 2144 return New->setInvalidDecl(); 2145 } 2146 New->setType(MergedT); 2147} 2148 2149/// MergeVarDecl - We just parsed a variable 'New' which has the same name 2150/// and scope as a previous declaration 'Old'. Figure out how to resolve this 2151/// situation, merging decls or emitting diagnostics as appropriate. 2152/// 2153/// Tentative definition rules (C99 6.9.2p2) are checked by 2154/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2155/// definitions here, since the initializer hasn't been attached. 2156/// 2157void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2158 // If the new decl is already invalid, don't do any other checking. 2159 if (New->isInvalidDecl()) 2160 return; 2161 2162 // Verify the old decl was also a variable. 2163 VarDecl *Old = 0; 2164 if (!Previous.isSingleResult() || 2165 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 2166 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2167 << New->getDeclName(); 2168 Diag(Previous.getRepresentativeDecl()->getLocation(), 2169 diag::note_previous_definition); 2170 return New->setInvalidDecl(); 2171 } 2172 2173 // C++ [class.mem]p1: 2174 // A member shall not be declared twice in the member-specification [...] 2175 // 2176 // Here, we need only consider static data members. 2177 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 2178 Diag(New->getLocation(), diag::err_duplicate_member) 2179 << New->getIdentifier(); 2180 Diag(Old->getLocation(), diag::note_previous_declaration); 2181 New->setInvalidDecl(); 2182 } 2183 2184 mergeDeclAttributes(New, Old, Context); 2185 // Warn if an already-declared variable is made a weak_import in a subsequent 2186 // declaration 2187 if (New->getAttr<WeakImportAttr>() && 2188 Old->getStorageClass() == SC_None && 2189 !Old->getAttr<WeakImportAttr>()) { 2190 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 2191 Diag(Old->getLocation(), diag::note_previous_definition); 2192 // Remove weak_import attribute on new declaration. 2193 New->dropAttr<WeakImportAttr>(); 2194 } 2195 2196 // Merge the types. 2197 MergeVarDeclTypes(New, Old); 2198 if (New->isInvalidDecl()) 2199 return; 2200 2201 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 2202 if (New->getStorageClass() == SC_Static && 2203 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) { 2204 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 2205 Diag(Old->getLocation(), diag::note_previous_definition); 2206 return New->setInvalidDecl(); 2207 } 2208 // C99 6.2.2p4: 2209 // For an identifier declared with the storage-class specifier 2210 // extern in a scope in which a prior declaration of that 2211 // identifier is visible,23) if the prior declaration specifies 2212 // internal or external linkage, the linkage of the identifier at 2213 // the later declaration is the same as the linkage specified at 2214 // the prior declaration. If no prior declaration is visible, or 2215 // if the prior declaration specifies no linkage, then the 2216 // identifier has external linkage. 2217 if (New->hasExternalStorage() && Old->hasLinkage()) 2218 /* Okay */; 2219 else if (New->getStorageClass() != SC_Static && 2220 Old->getStorageClass() == SC_Static) { 2221 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 2222 Diag(Old->getLocation(), diag::note_previous_definition); 2223 return New->setInvalidDecl(); 2224 } 2225 2226 // Check if extern is followed by non-extern and vice-versa. 2227 if (New->hasExternalStorage() && 2228 !Old->hasLinkage() && Old->isLocalVarDecl()) { 2229 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 2230 Diag(Old->getLocation(), diag::note_previous_definition); 2231 return New->setInvalidDecl(); 2232 } 2233 if (Old->hasExternalStorage() && 2234 !New->hasLinkage() && New->isLocalVarDecl()) { 2235 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 2236 Diag(Old->getLocation(), diag::note_previous_definition); 2237 return New->setInvalidDecl(); 2238 } 2239 2240 // __module_private__ is propagated to later declarations. 2241 if (Old->isModulePrivate()) 2242 New->setModulePrivate(); 2243 else if (New->isModulePrivate()) 2244 diagnoseModulePrivateRedeclaration(New, Old); 2245 2246 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 2247 2248 // FIXME: The test for external storage here seems wrong? We still 2249 // need to check for mismatches. 2250 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 2251 // Don't complain about out-of-line definitions of static members. 2252 !(Old->getLexicalDeclContext()->isRecord() && 2253 !New->getLexicalDeclContext()->isRecord())) { 2254 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 2255 Diag(Old->getLocation(), diag::note_previous_definition); 2256 return New->setInvalidDecl(); 2257 } 2258 2259 if (New->isThreadSpecified() && !Old->isThreadSpecified()) { 2260 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 2261 Diag(Old->getLocation(), diag::note_previous_definition); 2262 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) { 2263 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 2264 Diag(Old->getLocation(), diag::note_previous_definition); 2265 } 2266 2267 // C++ doesn't have tentative definitions, so go right ahead and check here. 2268 const VarDecl *Def; 2269 if (getLangOptions().CPlusPlus && 2270 New->isThisDeclarationADefinition() == VarDecl::Definition && 2271 (Def = Old->getDefinition())) { 2272 Diag(New->getLocation(), diag::err_redefinition) 2273 << New->getDeclName(); 2274 Diag(Def->getLocation(), diag::note_previous_definition); 2275 New->setInvalidDecl(); 2276 return; 2277 } 2278 // c99 6.2.2 P4. 2279 // For an identifier declared with the storage-class specifier extern in a 2280 // scope in which a prior declaration of that identifier is visible, if 2281 // the prior declaration specifies internal or external linkage, the linkage 2282 // of the identifier at the later declaration is the same as the linkage 2283 // specified at the prior declaration. 2284 // FIXME. revisit this code. 2285 if (New->hasExternalStorage() && 2286 Old->getLinkage() == InternalLinkage && 2287 New->getDeclContext() == Old->getDeclContext()) 2288 New->setStorageClass(Old->getStorageClass()); 2289 2290 // Keep a chain of previous declarations. 2291 New->setPreviousDeclaration(Old); 2292 2293 // Inherit access appropriately. 2294 New->setAccess(Old->getAccess()); 2295} 2296 2297/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2298/// no declarator (e.g. "struct foo;") is parsed. 2299Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2300 DeclSpec &DS) { 2301 return ParsedFreeStandingDeclSpec(S, AS, DS, 2302 MultiTemplateParamsArg(*this, 0, 0)); 2303} 2304 2305/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2306/// no declarator (e.g. "struct foo;") is parsed. It also accopts template 2307/// parameters to cope with template friend declarations. 2308Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2309 DeclSpec &DS, 2310 MultiTemplateParamsArg TemplateParams) { 2311 Decl *TagD = 0; 2312 TagDecl *Tag = 0; 2313 if (DS.getTypeSpecType() == DeclSpec::TST_class || 2314 DS.getTypeSpecType() == DeclSpec::TST_struct || 2315 DS.getTypeSpecType() == DeclSpec::TST_union || 2316 DS.getTypeSpecType() == DeclSpec::TST_enum) { 2317 TagD = DS.getRepAsDecl(); 2318 2319 if (!TagD) // We probably had an error 2320 return 0; 2321 2322 // Note that the above type specs guarantee that the 2323 // type rep is a Decl, whereas in many of the others 2324 // it's a Type. 2325 if (isa<TagDecl>(TagD)) 2326 Tag = cast<TagDecl>(TagD); 2327 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 2328 Tag = CTD->getTemplatedDecl(); 2329 } 2330 2331 if (Tag) 2332 Tag->setFreeStanding(); 2333 2334 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 2335 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 2336 // or incomplete types shall not be restrict-qualified." 2337 if (TypeQuals & DeclSpec::TQ_restrict) 2338 Diag(DS.getRestrictSpecLoc(), 2339 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 2340 << DS.getSourceRange(); 2341 } 2342 2343 if (DS.isConstexprSpecified()) { 2344 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 2345 // and definitions of functions and variables. 2346 if (Tag) 2347 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 2348 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 2349 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 2350 DS.getTypeSpecType() == DeclSpec::TST_union ? 2 : 3); 2351 else 2352 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 2353 // Don't emit warnings after this error. 2354 return TagD; 2355 } 2356 2357 if (DS.isFriendSpecified()) { 2358 // If we're dealing with a decl but not a TagDecl, assume that 2359 // whatever routines created it handled the friendship aspect. 2360 if (TagD && !Tag) 2361 return 0; 2362 return ActOnFriendTypeDecl(S, DS, TemplateParams); 2363 } 2364 2365 // Track whether we warned about the fact that there aren't any 2366 // declarators. 2367 bool emittedWarning = false; 2368 2369 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 2370 ProcessDeclAttributeList(S, Record, DS.getAttributes().getList()); 2371 2372 if (!Record->getDeclName() && Record->isCompleteDefinition() && 2373 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 2374 if (getLangOptions().CPlusPlus || 2375 Record->getDeclContext()->isRecord()) 2376 return BuildAnonymousStructOrUnion(S, DS, AS, Record); 2377 2378 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators) 2379 << DS.getSourceRange(); 2380 emittedWarning = true; 2381 } 2382 } 2383 2384 // Check for Microsoft C extension: anonymous struct. 2385 if (getLangOptions().MicrosoftExt && !getLangOptions().CPlusPlus && 2386 CurContext->isRecord() && 2387 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 2388 // Handle 2 kinds of anonymous struct: 2389 // struct STRUCT; 2390 // and 2391 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 2392 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 2393 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 2394 (DS.getTypeSpecType() == DeclSpec::TST_typename && 2395 DS.getRepAsType().get()->isStructureType())) { 2396 Diag(DS.getSourceRange().getBegin(), diag::ext_ms_anonymous_struct) 2397 << DS.getSourceRange(); 2398 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 2399 } 2400 } 2401 2402 if (getLangOptions().CPlusPlus && 2403 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 2404 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 2405 if (Enum->enumerator_begin() == Enum->enumerator_end() && 2406 !Enum->getIdentifier() && !Enum->isInvalidDecl()) { 2407 Diag(Enum->getLocation(), diag::ext_no_declarators) 2408 << DS.getSourceRange(); 2409 emittedWarning = true; 2410 } 2411 2412 // Skip all the checks below if we have a type error. 2413 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD; 2414 2415 if (!DS.isMissingDeclaratorOk()) { 2416 // Warn about typedefs of enums without names, since this is an 2417 // extension in both Microsoft and GNU. 2418 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef && 2419 Tag && isa<EnumDecl>(Tag)) { 2420 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name) 2421 << DS.getSourceRange(); 2422 return Tag; 2423 } 2424 2425 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators) 2426 << DS.getSourceRange(); 2427 emittedWarning = true; 2428 } 2429 2430 // We're going to complain about a bunch of spurious specifiers; 2431 // only do this if we're declaring a tag, because otherwise we 2432 // should be getting diag::ext_no_declarators. 2433 if (emittedWarning || (TagD && TagD->isInvalidDecl())) 2434 return TagD; 2435 2436 // Note that a linkage-specification sets a storage class, but 2437 // 'extern "C" struct foo;' is actually valid and not theoretically 2438 // useless. 2439 if (DeclSpec::SCS scs = DS.getStorageClassSpec()) 2440 if (!DS.isExternInLinkageSpec()) 2441 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier) 2442 << DeclSpec::getSpecifierName(scs); 2443 2444 if (DS.isThreadSpecified()) 2445 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread"; 2446 if (DS.getTypeQualifiers()) { 2447 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2448 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const"; 2449 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 2450 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile"; 2451 // Restrict is covered above. 2452 } 2453 if (DS.isInlineSpecified()) 2454 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline"; 2455 if (DS.isVirtualSpecified()) 2456 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual"; 2457 if (DS.isExplicitSpecified()) 2458 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit"; 2459 2460 if (DS.isModulePrivateSpecified() && 2461 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 2462 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 2463 << Tag->getTagKind() 2464 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 2465 2466 // FIXME: Warn on useless attributes 2467 2468 return TagD; 2469} 2470 2471/// ActOnVlaStmt - This rouine if finds a vla expression in a decl spec. 2472/// builds a statement for it and returns it so it is evaluated. 2473StmtResult Sema::ActOnVlaStmt(const DeclSpec &DS) { 2474 StmtResult R; 2475 if (DS.getTypeSpecType() == DeclSpec::TST_typeofExpr) { 2476 Expr *Exp = DS.getRepAsExpr(); 2477 QualType Ty = Exp->getType(); 2478 if (Ty->isPointerType()) { 2479 do 2480 Ty = Ty->getAs<PointerType>()->getPointeeType(); 2481 while (Ty->isPointerType()); 2482 } 2483 if (Ty->isVariableArrayType()) { 2484 R = ActOnExprStmt(MakeFullExpr(Exp)); 2485 } 2486 } 2487 return R; 2488} 2489 2490/// We are trying to inject an anonymous member into the given scope; 2491/// check if there's an existing declaration that can't be overloaded. 2492/// 2493/// \return true if this is a forbidden redeclaration 2494static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 2495 Scope *S, 2496 DeclContext *Owner, 2497 DeclarationName Name, 2498 SourceLocation NameLoc, 2499 unsigned diagnostic) { 2500 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 2501 Sema::ForRedeclaration); 2502 if (!SemaRef.LookupName(R, S)) return false; 2503 2504 if (R.getAsSingle<TagDecl>()) 2505 return false; 2506 2507 // Pick a representative declaration. 2508 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 2509 assert(PrevDecl && "Expected a non-null Decl"); 2510 2511 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 2512 return false; 2513 2514 SemaRef.Diag(NameLoc, diagnostic) << Name; 2515 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 2516 2517 return true; 2518} 2519 2520/// InjectAnonymousStructOrUnionMembers - Inject the members of the 2521/// anonymous struct or union AnonRecord into the owning context Owner 2522/// and scope S. This routine will be invoked just after we realize 2523/// that an unnamed union or struct is actually an anonymous union or 2524/// struct, e.g., 2525/// 2526/// @code 2527/// union { 2528/// int i; 2529/// float f; 2530/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 2531/// // f into the surrounding scope.x 2532/// @endcode 2533/// 2534/// This routine is recursive, injecting the names of nested anonymous 2535/// structs/unions into the owning context and scope as well. 2536static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 2537 DeclContext *Owner, 2538 RecordDecl *AnonRecord, 2539 AccessSpecifier AS, 2540 SmallVector<NamedDecl*, 2> &Chaining, 2541 bool MSAnonStruct) { 2542 unsigned diagKind 2543 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 2544 : diag::err_anonymous_struct_member_redecl; 2545 2546 bool Invalid = false; 2547 2548 // Look every FieldDecl and IndirectFieldDecl with a name. 2549 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 2550 DEnd = AnonRecord->decls_end(); 2551 D != DEnd; ++D) { 2552 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 2553 cast<NamedDecl>(*D)->getDeclName()) { 2554 ValueDecl *VD = cast<ValueDecl>(*D); 2555 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 2556 VD->getLocation(), diagKind)) { 2557 // C++ [class.union]p2: 2558 // The names of the members of an anonymous union shall be 2559 // distinct from the names of any other entity in the 2560 // scope in which the anonymous union is declared. 2561 Invalid = true; 2562 } else { 2563 // C++ [class.union]p2: 2564 // For the purpose of name lookup, after the anonymous union 2565 // definition, the members of the anonymous union are 2566 // considered to have been defined in the scope in which the 2567 // anonymous union is declared. 2568 unsigned OldChainingSize = Chaining.size(); 2569 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 2570 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 2571 PE = IF->chain_end(); PI != PE; ++PI) 2572 Chaining.push_back(*PI); 2573 else 2574 Chaining.push_back(VD); 2575 2576 assert(Chaining.size() >= 2); 2577 NamedDecl **NamedChain = 2578 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 2579 for (unsigned i = 0; i < Chaining.size(); i++) 2580 NamedChain[i] = Chaining[i]; 2581 2582 IndirectFieldDecl* IndirectField = 2583 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 2584 VD->getIdentifier(), VD->getType(), 2585 NamedChain, Chaining.size()); 2586 2587 IndirectField->setAccess(AS); 2588 IndirectField->setImplicit(); 2589 SemaRef.PushOnScopeChains(IndirectField, S); 2590 2591 // That includes picking up the appropriate access specifier. 2592 if (AS != AS_none) IndirectField->setAccess(AS); 2593 2594 Chaining.resize(OldChainingSize); 2595 } 2596 } 2597 } 2598 2599 return Invalid; 2600} 2601 2602/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 2603/// a VarDecl::StorageClass. Any error reporting is up to the caller: 2604/// illegal input values are mapped to SC_None. 2605static StorageClass 2606StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 2607 switch (StorageClassSpec) { 2608 case DeclSpec::SCS_unspecified: return SC_None; 2609 case DeclSpec::SCS_extern: return SC_Extern; 2610 case DeclSpec::SCS_static: return SC_Static; 2611 case DeclSpec::SCS_auto: return SC_Auto; 2612 case DeclSpec::SCS_register: return SC_Register; 2613 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 2614 // Illegal SCSs map to None: error reporting is up to the caller. 2615 case DeclSpec::SCS_mutable: // Fall through. 2616 case DeclSpec::SCS_typedef: return SC_None; 2617 } 2618 llvm_unreachable("unknown storage class specifier"); 2619} 2620 2621/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to 2622/// a StorageClass. Any error reporting is up to the caller: 2623/// illegal input values are mapped to SC_None. 2624static StorageClass 2625StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 2626 switch (StorageClassSpec) { 2627 case DeclSpec::SCS_unspecified: return SC_None; 2628 case DeclSpec::SCS_extern: return SC_Extern; 2629 case DeclSpec::SCS_static: return SC_Static; 2630 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 2631 // Illegal SCSs map to None: error reporting is up to the caller. 2632 case DeclSpec::SCS_auto: // Fall through. 2633 case DeclSpec::SCS_mutable: // Fall through. 2634 case DeclSpec::SCS_register: // Fall through. 2635 case DeclSpec::SCS_typedef: return SC_None; 2636 } 2637 llvm_unreachable("unknown storage class specifier"); 2638} 2639 2640/// BuildAnonymousStructOrUnion - Handle the declaration of an 2641/// anonymous structure or union. Anonymous unions are a C++ feature 2642/// (C++ [class.union]) and a GNU C extension; anonymous structures 2643/// are a GNU C and GNU C++ extension. 2644Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 2645 AccessSpecifier AS, 2646 RecordDecl *Record) { 2647 DeclContext *Owner = Record->getDeclContext(); 2648 2649 // Diagnose whether this anonymous struct/union is an extension. 2650 if (Record->isUnion() && !getLangOptions().CPlusPlus) 2651 Diag(Record->getLocation(), diag::ext_anonymous_union); 2652 else if (!Record->isUnion()) 2653 Diag(Record->getLocation(), diag::ext_anonymous_struct); 2654 2655 // C and C++ require different kinds of checks for anonymous 2656 // structs/unions. 2657 bool Invalid = false; 2658 if (getLangOptions().CPlusPlus) { 2659 const char* PrevSpec = 0; 2660 unsigned DiagID; 2661 if (Record->isUnion()) { 2662 // C++ [class.union]p6: 2663 // Anonymous unions declared in a named namespace or in the 2664 // global namespace shall be declared static. 2665 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 2666 (isa<TranslationUnitDecl>(Owner) || 2667 (isa<NamespaceDecl>(Owner) && 2668 cast<NamespaceDecl>(Owner)->getDeclName()))) { 2669 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 2670 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 2671 2672 // Recover by adding 'static'. 2673 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 2674 PrevSpec, DiagID); 2675 } 2676 // C++ [class.union]p6: 2677 // A storage class is not allowed in a declaration of an 2678 // anonymous union in a class scope. 2679 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 2680 isa<RecordDecl>(Owner)) { 2681 Diag(DS.getStorageClassSpecLoc(), 2682 diag::err_anonymous_union_with_storage_spec) 2683 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 2684 2685 // Recover by removing the storage specifier. 2686 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 2687 SourceLocation(), 2688 PrevSpec, DiagID); 2689 } 2690 } 2691 2692 // Ignore const/volatile/restrict qualifiers. 2693 if (DS.getTypeQualifiers()) { 2694 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2695 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 2696 << Record->isUnion() << 0 2697 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 2698 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 2699 Diag(DS.getVolatileSpecLoc(), 2700 diag::ext_anonymous_struct_union_qualified) 2701 << Record->isUnion() << 1 2702 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 2703 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 2704 Diag(DS.getRestrictSpecLoc(), 2705 diag::ext_anonymous_struct_union_qualified) 2706 << Record->isUnion() << 2 2707 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 2708 2709 DS.ClearTypeQualifiers(); 2710 } 2711 2712 // C++ [class.union]p2: 2713 // The member-specification of an anonymous union shall only 2714 // define non-static data members. [Note: nested types and 2715 // functions cannot be declared within an anonymous union. ] 2716 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 2717 MemEnd = Record->decls_end(); 2718 Mem != MemEnd; ++Mem) { 2719 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 2720 // C++ [class.union]p3: 2721 // An anonymous union shall not have private or protected 2722 // members (clause 11). 2723 assert(FD->getAccess() != AS_none); 2724 if (FD->getAccess() != AS_public) { 2725 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 2726 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 2727 Invalid = true; 2728 } 2729 2730 // C++ [class.union]p1 2731 // An object of a class with a non-trivial constructor, a non-trivial 2732 // copy constructor, a non-trivial destructor, or a non-trivial copy 2733 // assignment operator cannot be a member of a union, nor can an 2734 // array of such objects. 2735 if (CheckNontrivialField(FD)) 2736 Invalid = true; 2737 } else if ((*Mem)->isImplicit()) { 2738 // Any implicit members are fine. 2739 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 2740 // This is a type that showed up in an 2741 // elaborated-type-specifier inside the anonymous struct or 2742 // union, but which actually declares a type outside of the 2743 // anonymous struct or union. It's okay. 2744 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 2745 if (!MemRecord->isAnonymousStructOrUnion() && 2746 MemRecord->getDeclName()) { 2747 // Visual C++ allows type definition in anonymous struct or union. 2748 if (getLangOptions().MicrosoftExt) 2749 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 2750 << (int)Record->isUnion(); 2751 else { 2752 // This is a nested type declaration. 2753 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 2754 << (int)Record->isUnion(); 2755 Invalid = true; 2756 } 2757 } 2758 } else if (isa<AccessSpecDecl>(*Mem)) { 2759 // Any access specifier is fine. 2760 } else { 2761 // We have something that isn't a non-static data 2762 // member. Complain about it. 2763 unsigned DK = diag::err_anonymous_record_bad_member; 2764 if (isa<TypeDecl>(*Mem)) 2765 DK = diag::err_anonymous_record_with_type; 2766 else if (isa<FunctionDecl>(*Mem)) 2767 DK = diag::err_anonymous_record_with_function; 2768 else if (isa<VarDecl>(*Mem)) 2769 DK = diag::err_anonymous_record_with_static; 2770 2771 // Visual C++ allows type definition in anonymous struct or union. 2772 if (getLangOptions().MicrosoftExt && 2773 DK == diag::err_anonymous_record_with_type) 2774 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 2775 << (int)Record->isUnion(); 2776 else { 2777 Diag((*Mem)->getLocation(), DK) 2778 << (int)Record->isUnion(); 2779 Invalid = true; 2780 } 2781 } 2782 } 2783 } 2784 2785 if (!Record->isUnion() && !Owner->isRecord()) { 2786 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 2787 << (int)getLangOptions().CPlusPlus; 2788 Invalid = true; 2789 } 2790 2791 // Mock up a declarator. 2792 Declarator Dc(DS, Declarator::MemberContext); 2793 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 2794 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 2795 2796 // Create a declaration for this anonymous struct/union. 2797 NamedDecl *Anon = 0; 2798 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 2799 Anon = FieldDecl::Create(Context, OwningClass, 2800 DS.getSourceRange().getBegin(), 2801 Record->getLocation(), 2802 /*IdentifierInfo=*/0, 2803 Context.getTypeDeclType(Record), 2804 TInfo, 2805 /*BitWidth=*/0, /*Mutable=*/false, 2806 /*HasInit=*/false); 2807 Anon->setAccess(AS); 2808 if (getLangOptions().CPlusPlus) 2809 FieldCollector->Add(cast<FieldDecl>(Anon)); 2810 } else { 2811 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 2812 assert(SCSpec != DeclSpec::SCS_typedef && 2813 "Parser allowed 'typedef' as storage class VarDecl."); 2814 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 2815 if (SCSpec == DeclSpec::SCS_mutable) { 2816 // mutable can only appear on non-static class members, so it's always 2817 // an error here 2818 Diag(Record->getLocation(), diag::err_mutable_nonmember); 2819 Invalid = true; 2820 SC = SC_None; 2821 } 2822 SCSpec = DS.getStorageClassSpecAsWritten(); 2823 VarDecl::StorageClass SCAsWritten 2824 = StorageClassSpecToVarDeclStorageClass(SCSpec); 2825 2826 Anon = VarDecl::Create(Context, Owner, 2827 DS.getSourceRange().getBegin(), 2828 Record->getLocation(), /*IdentifierInfo=*/0, 2829 Context.getTypeDeclType(Record), 2830 TInfo, SC, SCAsWritten); 2831 2832 // Default-initialize the implicit variable. This initialization will be 2833 // trivial in almost all cases, except if a union member has an in-class 2834 // initializer: 2835 // union { int n = 0; }; 2836 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 2837 } 2838 Anon->setImplicit(); 2839 2840 // Add the anonymous struct/union object to the current 2841 // context. We'll be referencing this object when we refer to one of 2842 // its members. 2843 Owner->addDecl(Anon); 2844 2845 // Inject the members of the anonymous struct/union into the owning 2846 // context and into the identifier resolver chain for name lookup 2847 // purposes. 2848 SmallVector<NamedDecl*, 2> Chain; 2849 Chain.push_back(Anon); 2850 2851 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 2852 Chain, false)) 2853 Invalid = true; 2854 2855 // Mark this as an anonymous struct/union type. Note that we do not 2856 // do this until after we have already checked and injected the 2857 // members of this anonymous struct/union type, because otherwise 2858 // the members could be injected twice: once by DeclContext when it 2859 // builds its lookup table, and once by 2860 // InjectAnonymousStructOrUnionMembers. 2861 Record->setAnonymousStructOrUnion(true); 2862 2863 if (Invalid) 2864 Anon->setInvalidDecl(); 2865 2866 return Anon; 2867} 2868 2869/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 2870/// Microsoft C anonymous structure. 2871/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 2872/// Example: 2873/// 2874/// struct A { int a; }; 2875/// struct B { struct A; int b; }; 2876/// 2877/// void foo() { 2878/// B var; 2879/// var.a = 3; 2880/// } 2881/// 2882Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 2883 RecordDecl *Record) { 2884 2885 // If there is no Record, get the record via the typedef. 2886 if (!Record) 2887 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 2888 2889 // Mock up a declarator. 2890 Declarator Dc(DS, Declarator::TypeNameContext); 2891 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 2892 assert(TInfo && "couldn't build declarator info for anonymous struct"); 2893 2894 // Create a declaration for this anonymous struct. 2895 NamedDecl* Anon = FieldDecl::Create(Context, 2896 cast<RecordDecl>(CurContext), 2897 DS.getSourceRange().getBegin(), 2898 DS.getSourceRange().getBegin(), 2899 /*IdentifierInfo=*/0, 2900 Context.getTypeDeclType(Record), 2901 TInfo, 2902 /*BitWidth=*/0, /*Mutable=*/false, 2903 /*HasInit=*/false); 2904 Anon->setImplicit(); 2905 2906 // Add the anonymous struct object to the current context. 2907 CurContext->addDecl(Anon); 2908 2909 // Inject the members of the anonymous struct into the current 2910 // context and into the identifier resolver chain for name lookup 2911 // purposes. 2912 SmallVector<NamedDecl*, 2> Chain; 2913 Chain.push_back(Anon); 2914 2915 if (InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 2916 Record->getDefinition(), 2917 AS_none, Chain, true)) 2918 Anon->setInvalidDecl(); 2919 2920 return Anon; 2921} 2922 2923/// GetNameForDeclarator - Determine the full declaration name for the 2924/// given Declarator. 2925DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 2926 return GetNameFromUnqualifiedId(D.getName()); 2927} 2928 2929/// \brief Retrieves the declaration name from a parsed unqualified-id. 2930DeclarationNameInfo 2931Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 2932 DeclarationNameInfo NameInfo; 2933 NameInfo.setLoc(Name.StartLocation); 2934 2935 switch (Name.getKind()) { 2936 2937 case UnqualifiedId::IK_ImplicitSelfParam: 2938 case UnqualifiedId::IK_Identifier: 2939 NameInfo.setName(Name.Identifier); 2940 NameInfo.setLoc(Name.StartLocation); 2941 return NameInfo; 2942 2943 case UnqualifiedId::IK_OperatorFunctionId: 2944 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 2945 Name.OperatorFunctionId.Operator)); 2946 NameInfo.setLoc(Name.StartLocation); 2947 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 2948 = Name.OperatorFunctionId.SymbolLocations[0]; 2949 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 2950 = Name.EndLocation.getRawEncoding(); 2951 return NameInfo; 2952 2953 case UnqualifiedId::IK_LiteralOperatorId: 2954 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 2955 Name.Identifier)); 2956 NameInfo.setLoc(Name.StartLocation); 2957 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 2958 return NameInfo; 2959 2960 case UnqualifiedId::IK_ConversionFunctionId: { 2961 TypeSourceInfo *TInfo; 2962 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 2963 if (Ty.isNull()) 2964 return DeclarationNameInfo(); 2965 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 2966 Context.getCanonicalType(Ty))); 2967 NameInfo.setLoc(Name.StartLocation); 2968 NameInfo.setNamedTypeInfo(TInfo); 2969 return NameInfo; 2970 } 2971 2972 case UnqualifiedId::IK_ConstructorName: { 2973 TypeSourceInfo *TInfo; 2974 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 2975 if (Ty.isNull()) 2976 return DeclarationNameInfo(); 2977 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 2978 Context.getCanonicalType(Ty))); 2979 NameInfo.setLoc(Name.StartLocation); 2980 NameInfo.setNamedTypeInfo(TInfo); 2981 return NameInfo; 2982 } 2983 2984 case UnqualifiedId::IK_ConstructorTemplateId: { 2985 // In well-formed code, we can only have a constructor 2986 // template-id that refers to the current context, so go there 2987 // to find the actual type being constructed. 2988 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 2989 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 2990 return DeclarationNameInfo(); 2991 2992 // Determine the type of the class being constructed. 2993 QualType CurClassType = Context.getTypeDeclType(CurClass); 2994 2995 // FIXME: Check two things: that the template-id names the same type as 2996 // CurClassType, and that the template-id does not occur when the name 2997 // was qualified. 2998 2999 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3000 Context.getCanonicalType(CurClassType))); 3001 NameInfo.setLoc(Name.StartLocation); 3002 // FIXME: should we retrieve TypeSourceInfo? 3003 NameInfo.setNamedTypeInfo(0); 3004 return NameInfo; 3005 } 3006 3007 case UnqualifiedId::IK_DestructorName: { 3008 TypeSourceInfo *TInfo; 3009 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3010 if (Ty.isNull()) 3011 return DeclarationNameInfo(); 3012 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3013 Context.getCanonicalType(Ty))); 3014 NameInfo.setLoc(Name.StartLocation); 3015 NameInfo.setNamedTypeInfo(TInfo); 3016 return NameInfo; 3017 } 3018 3019 case UnqualifiedId::IK_TemplateId: { 3020 TemplateName TName = Name.TemplateId->Template.get(); 3021 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3022 return Context.getNameForTemplate(TName, TNameLoc); 3023 } 3024 3025 } // switch (Name.getKind()) 3026 3027 llvm_unreachable("Unknown name kind"); 3028} 3029 3030static QualType getCoreType(QualType Ty) { 3031 do { 3032 if (Ty->isPointerType() || Ty->isReferenceType()) 3033 Ty = Ty->getPointeeType(); 3034 else if (Ty->isArrayType()) 3035 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3036 else 3037 return Ty.withoutLocalFastQualifiers(); 3038 } while (true); 3039} 3040 3041/// hasSimilarParameters - Determine whether the C++ functions Declaration 3042/// and Definition have "nearly" matching parameters. This heuristic is 3043/// used to improve diagnostics in the case where an out-of-line function 3044/// definition doesn't match any declaration within the class or namespace. 3045/// Also sets Params to the list of indices to the parameters that differ 3046/// between the declaration and the definition. If hasSimilarParameters 3047/// returns true and Params is empty, then all of the parameters match. 3048static bool hasSimilarParameters(ASTContext &Context, 3049 FunctionDecl *Declaration, 3050 FunctionDecl *Definition, 3051 llvm::SmallVectorImpl<unsigned> &Params) { 3052 Params.clear(); 3053 if (Declaration->param_size() != Definition->param_size()) 3054 return false; 3055 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 3056 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 3057 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 3058 3059 // The parameter types are identical 3060 if (Context.hasSameType(DefParamTy, DeclParamTy)) 3061 continue; 3062 3063 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 3064 QualType DefParamBaseTy = getCoreType(DefParamTy); 3065 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 3066 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 3067 3068 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 3069 (DeclTyName && DeclTyName == DefTyName)) 3070 Params.push_back(Idx); 3071 else // The two parameters aren't even close 3072 return false; 3073 } 3074 3075 return true; 3076} 3077 3078/// NeedsRebuildingInCurrentInstantiation - Checks whether the given 3079/// declarator needs to be rebuilt in the current instantiation. 3080/// Any bits of declarator which appear before the name are valid for 3081/// consideration here. That's specifically the type in the decl spec 3082/// and the base type in any member-pointer chunks. 3083static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 3084 DeclarationName Name) { 3085 // The types we specifically need to rebuild are: 3086 // - typenames, typeofs, and decltypes 3087 // - types which will become injected class names 3088 // Of course, we also need to rebuild any type referencing such a 3089 // type. It's safest to just say "dependent", but we call out a 3090 // few cases here. 3091 3092 DeclSpec &DS = D.getMutableDeclSpec(); 3093 switch (DS.getTypeSpecType()) { 3094 case DeclSpec::TST_typename: 3095 case DeclSpec::TST_typeofType: 3096 case DeclSpec::TST_decltype: 3097 case DeclSpec::TST_underlyingType: 3098 case DeclSpec::TST_atomic: { 3099 // Grab the type from the parser. 3100 TypeSourceInfo *TSI = 0; 3101 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 3102 if (T.isNull() || !T->isDependentType()) break; 3103 3104 // Make sure there's a type source info. This isn't really much 3105 // of a waste; most dependent types should have type source info 3106 // attached already. 3107 if (!TSI) 3108 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 3109 3110 // Rebuild the type in the current instantiation. 3111 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 3112 if (!TSI) return true; 3113 3114 // Store the new type back in the decl spec. 3115 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 3116 DS.UpdateTypeRep(LocType); 3117 break; 3118 } 3119 3120 case DeclSpec::TST_typeofExpr: { 3121 Expr *E = DS.getRepAsExpr(); 3122 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 3123 if (Result.isInvalid()) return true; 3124 DS.UpdateExprRep(Result.get()); 3125 break; 3126 } 3127 3128 default: 3129 // Nothing to do for these decl specs. 3130 break; 3131 } 3132 3133 // It doesn't matter what order we do this in. 3134 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 3135 DeclaratorChunk &Chunk = D.getTypeObject(I); 3136 3137 // The only type information in the declarator which can come 3138 // before the declaration name is the base type of a member 3139 // pointer. 3140 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 3141 continue; 3142 3143 // Rebuild the scope specifier in-place. 3144 CXXScopeSpec &SS = Chunk.Mem.Scope(); 3145 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 3146 return true; 3147 } 3148 3149 return false; 3150} 3151 3152Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 3153 D.setFunctionDefinitionKind(FDK_Declaration); 3154 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg(*this)); 3155 3156 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 3157 Dcl->getDeclContext()->isFileContext()) 3158 Dcl->setTopLevelDeclInObjCContainer(); 3159 3160 return Dcl; 3161} 3162 3163/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 3164/// If T is the name of a class, then each of the following shall have a 3165/// name different from T: 3166/// - every static data member of class T; 3167/// - every member function of class T 3168/// - every member of class T that is itself a type; 3169/// \returns true if the declaration name violates these rules. 3170bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 3171 DeclarationNameInfo NameInfo) { 3172 DeclarationName Name = NameInfo.getName(); 3173 3174 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 3175 if (Record->getIdentifier() && Record->getDeclName() == Name) { 3176 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 3177 return true; 3178 } 3179 3180 return false; 3181} 3182 3183Decl *Sema::HandleDeclarator(Scope *S, Declarator &D, 3184 MultiTemplateParamsArg TemplateParamLists) { 3185 // TODO: consider using NameInfo for diagnostic. 3186 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3187 DeclarationName Name = NameInfo.getName(); 3188 3189 // All of these full declarators require an identifier. If it doesn't have 3190 // one, the ParsedFreeStandingDeclSpec action should be used. 3191 if (!Name) { 3192 if (!D.isInvalidType()) // Reject this if we think it is valid. 3193 Diag(D.getDeclSpec().getSourceRange().getBegin(), 3194 diag::err_declarator_need_ident) 3195 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 3196 return 0; 3197 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 3198 return 0; 3199 3200 // The scope passed in may not be a decl scope. Zip up the scope tree until 3201 // we find one that is. 3202 while ((S->getFlags() & Scope::DeclScope) == 0 || 3203 (S->getFlags() & Scope::TemplateParamScope) != 0) 3204 S = S->getParent(); 3205 3206 DeclContext *DC = CurContext; 3207 if (D.getCXXScopeSpec().isInvalid()) 3208 D.setInvalidType(); 3209 else if (D.getCXXScopeSpec().isSet()) { 3210 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 3211 UPPC_DeclarationQualifier)) 3212 return 0; 3213 3214 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 3215 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 3216 if (!DC) { 3217 // If we could not compute the declaration context, it's because the 3218 // declaration context is dependent but does not refer to a class, 3219 // class template, or class template partial specialization. Complain 3220 // and return early, to avoid the coming semantic disaster. 3221 Diag(D.getIdentifierLoc(), 3222 diag::err_template_qualified_declarator_no_match) 3223 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 3224 << D.getCXXScopeSpec().getRange(); 3225 return 0; 3226 } 3227 bool IsDependentContext = DC->isDependentContext(); 3228 3229 if (!IsDependentContext && 3230 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 3231 return 0; 3232 3233 if (isa<CXXRecordDecl>(DC)) { 3234 if (!cast<CXXRecordDecl>(DC)->hasDefinition()) { 3235 Diag(D.getIdentifierLoc(), 3236 diag::err_member_def_undefined_record) 3237 << Name << DC << D.getCXXScopeSpec().getRange(); 3238 D.setInvalidType(); 3239 } else if (isa<CXXRecordDecl>(CurContext) && 3240 !D.getDeclSpec().isFriendSpecified()) { 3241 // The user provided a superfluous scope specifier inside a class 3242 // definition: 3243 // 3244 // class X { 3245 // void X::f(); 3246 // }; 3247 if (CurContext->Equals(DC)) { 3248 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification) 3249 << Name << FixItHint::CreateRemoval(D.getCXXScopeSpec().getRange()); 3250 } else { 3251 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3252 << Name << D.getCXXScopeSpec().getRange(); 3253 3254 // C++ constructors and destructors with incorrect scopes can break 3255 // our AST invariants by having the wrong underlying types. If 3256 // that's the case, then drop this declaration entirely. 3257 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 3258 Name.getNameKind() == DeclarationName::CXXDestructorName) && 3259 !Context.hasSameType(Name.getCXXNameType(), 3260 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)))) 3261 return 0; 3262 } 3263 3264 // Pretend that this qualifier was not here. 3265 D.getCXXScopeSpec().clear(); 3266 } 3267 } 3268 3269 // Check whether we need to rebuild the type of the given 3270 // declaration in the current instantiation. 3271 if (EnteringContext && IsDependentContext && 3272 TemplateParamLists.size() != 0) { 3273 ContextRAII SavedContext(*this, DC); 3274 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 3275 D.setInvalidType(); 3276 } 3277 } 3278 3279 if (DiagnoseClassNameShadow(DC, NameInfo)) 3280 // If this is a typedef, we'll end up spewing multiple diagnostics. 3281 // Just return early; it's safer. 3282 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3283 return 0; 3284 3285 NamedDecl *New; 3286 3287 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 3288 QualType R = TInfo->getType(); 3289 3290 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 3291 UPPC_DeclarationType)) 3292 D.setInvalidType(); 3293 3294 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 3295 ForRedeclaration); 3296 3297 // See if this is a redefinition of a variable in the same scope. 3298 if (!D.getCXXScopeSpec().isSet()) { 3299 bool IsLinkageLookup = false; 3300 3301 // If the declaration we're planning to build will be a function 3302 // or object with linkage, then look for another declaration with 3303 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 3304 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3305 /* Do nothing*/; 3306 else if (R->isFunctionType()) { 3307 if (CurContext->isFunctionOrMethod() || 3308 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 3309 IsLinkageLookup = true; 3310 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 3311 IsLinkageLookup = true; 3312 else if (CurContext->getRedeclContext()->isTranslationUnit() && 3313 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 3314 IsLinkageLookup = true; 3315 3316 if (IsLinkageLookup) 3317 Previous.clear(LookupRedeclarationWithLinkage); 3318 3319 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup); 3320 } else { // Something like "int foo::x;" 3321 LookupQualifiedName(Previous, DC); 3322 3323 // Don't consider using declarations as previous declarations for 3324 // out-of-line members. 3325 RemoveUsingDecls(Previous); 3326 3327 // C++ 7.3.1.2p2: 3328 // Members (including explicit specializations of templates) of a named 3329 // namespace can also be defined outside that namespace by explicit 3330 // qualification of the name being defined, provided that the entity being 3331 // defined was already declared in the namespace and the definition appears 3332 // after the point of declaration in a namespace that encloses the 3333 // declarations namespace. 3334 // 3335 // Note that we only check the context at this point. We don't yet 3336 // have enough information to make sure that PrevDecl is actually 3337 // the declaration we want to match. For example, given: 3338 // 3339 // class X { 3340 // void f(); 3341 // void f(float); 3342 // }; 3343 // 3344 // void X::f(int) { } // ill-formed 3345 // 3346 // In this case, PrevDecl will point to the overload set 3347 // containing the two f's declared in X, but neither of them 3348 // matches. 3349 3350 // First check whether we named the global scope. 3351 if (isa<TranslationUnitDecl>(DC)) { 3352 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope) 3353 << Name << D.getCXXScopeSpec().getRange(); 3354 } else { 3355 DeclContext *Cur = CurContext; 3356 while (isa<LinkageSpecDecl>(Cur)) 3357 Cur = Cur->getParent(); 3358 if (!Cur->Encloses(DC)) { 3359 // The qualifying scope doesn't enclose the original declaration. 3360 // Emit diagnostic based on current scope. 3361 SourceLocation L = D.getIdentifierLoc(); 3362 SourceRange R = D.getCXXScopeSpec().getRange(); 3363 if (isa<FunctionDecl>(Cur)) 3364 Diag(L, diag::err_invalid_declarator_in_function) << Name << R; 3365 else 3366 Diag(L, diag::err_invalid_declarator_scope) 3367 << Name << cast<NamedDecl>(DC) << R; 3368 D.setInvalidType(); 3369 } 3370 } 3371 } 3372 3373 if (Previous.isSingleResult() && 3374 Previous.getFoundDecl()->isTemplateParameter()) { 3375 // Maybe we will complain about the shadowed template parameter. 3376 if (!D.isInvalidType()) 3377 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 3378 Previous.getFoundDecl()); 3379 3380 // Just pretend that we didn't see the previous declaration. 3381 Previous.clear(); 3382 } 3383 3384 // In C++, the previous declaration we find might be a tag type 3385 // (class or enum). In this case, the new declaration will hide the 3386 // tag type. Note that this does does not apply if we're declaring a 3387 // typedef (C++ [dcl.typedef]p4). 3388 if (Previous.isSingleTagDecl() && 3389 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 3390 Previous.clear(); 3391 3392 bool AddToScope = true; 3393 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 3394 if (TemplateParamLists.size()) { 3395 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 3396 return 0; 3397 } 3398 3399 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 3400 } else if (R->isFunctionType()) { 3401 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 3402 move(TemplateParamLists), 3403 AddToScope); 3404 } else { 3405 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 3406 move(TemplateParamLists)); 3407 } 3408 3409 if (New == 0) 3410 return 0; 3411 3412 // If this has an identifier and is not an invalid redeclaration or 3413 // function template specialization, add it to the scope stack. 3414 if (New->getDeclName() && AddToScope && 3415 !(D.isRedeclaration() && New->isInvalidDecl())) 3416 PushOnScopeChains(New, S); 3417 3418 return New; 3419} 3420 3421/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array 3422/// types into constant array types in certain situations which would otherwise 3423/// be errors (for GCC compatibility). 3424static QualType TryToFixInvalidVariablyModifiedType(QualType T, 3425 ASTContext &Context, 3426 bool &SizeIsNegative, 3427 llvm::APSInt &Oversized) { 3428 // This method tries to turn a variable array into a constant 3429 // array even when the size isn't an ICE. This is necessary 3430 // for compatibility with code that depends on gcc's buggy 3431 // constant expression folding, like struct {char x[(int)(char*)2];} 3432 SizeIsNegative = false; 3433 Oversized = 0; 3434 3435 if (T->isDependentType()) 3436 return QualType(); 3437 3438 QualifierCollector Qs; 3439 const Type *Ty = Qs.strip(T); 3440 3441 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 3442 QualType Pointee = PTy->getPointeeType(); 3443 QualType FixedType = 3444 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 3445 Oversized); 3446 if (FixedType.isNull()) return FixedType; 3447 FixedType = Context.getPointerType(FixedType); 3448 return Qs.apply(Context, FixedType); 3449 } 3450 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 3451 QualType Inner = PTy->getInnerType(); 3452 QualType FixedType = 3453 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 3454 Oversized); 3455 if (FixedType.isNull()) return FixedType; 3456 FixedType = Context.getParenType(FixedType); 3457 return Qs.apply(Context, FixedType); 3458 } 3459 3460 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 3461 if (!VLATy) 3462 return QualType(); 3463 // FIXME: We should probably handle this case 3464 if (VLATy->getElementType()->isVariablyModifiedType()) 3465 return QualType(); 3466 3467 llvm::APSInt Res; 3468 if (!VLATy->getSizeExpr() || 3469 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 3470 return QualType(); 3471 3472 // Check whether the array size is negative. 3473 if (Res.isSigned() && Res.isNegative()) { 3474 SizeIsNegative = true; 3475 return QualType(); 3476 } 3477 3478 // Check whether the array is too large to be addressed. 3479 unsigned ActiveSizeBits 3480 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 3481 Res); 3482 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 3483 Oversized = Res; 3484 return QualType(); 3485 } 3486 3487 return Context.getConstantArrayType(VLATy->getElementType(), 3488 Res, ArrayType::Normal, 0); 3489} 3490 3491/// \brief Register the given locally-scoped external C declaration so 3492/// that it can be found later for redeclarations 3493void 3494Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, 3495 const LookupResult &Previous, 3496 Scope *S) { 3497 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 3498 "Decl is not a locally-scoped decl!"); 3499 // Note that we have a locally-scoped external with this name. 3500 LocallyScopedExternalDecls[ND->getDeclName()] = ND; 3501 3502 if (!Previous.isSingleResult()) 3503 return; 3504 3505 NamedDecl *PrevDecl = Previous.getFoundDecl(); 3506 3507 // If there was a previous declaration of this variable, it may be 3508 // in our identifier chain. Update the identifier chain with the new 3509 // declaration. 3510 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 3511 // The previous declaration was found on the identifer resolver 3512 // chain, so remove it from its scope. 3513 3514 if (S->isDeclScope(PrevDecl)) { 3515 // Special case for redeclarations in the SAME scope. 3516 // Because this declaration is going to be added to the identifier chain 3517 // later, we should temporarily take it OFF the chain. 3518 IdResolver.RemoveDecl(ND); 3519 3520 } else { 3521 // Find the scope for the original declaration. 3522 while (S && !S->isDeclScope(PrevDecl)) 3523 S = S->getParent(); 3524 } 3525 3526 if (S) 3527 S->RemoveDecl(PrevDecl); 3528 } 3529} 3530 3531llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 3532Sema::findLocallyScopedExternalDecl(DeclarationName Name) { 3533 if (ExternalSource) { 3534 // Load locally-scoped external decls from the external source. 3535 SmallVector<NamedDecl *, 4> Decls; 3536 ExternalSource->ReadLocallyScopedExternalDecls(Decls); 3537 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 3538 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 3539 = LocallyScopedExternalDecls.find(Decls[I]->getDeclName()); 3540 if (Pos == LocallyScopedExternalDecls.end()) 3541 LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I]; 3542 } 3543 } 3544 3545 return LocallyScopedExternalDecls.find(Name); 3546} 3547 3548/// \brief Diagnose function specifiers on a declaration of an identifier that 3549/// does not identify a function. 3550void Sema::DiagnoseFunctionSpecifiers(Declarator& D) { 3551 // FIXME: We should probably indicate the identifier in question to avoid 3552 // confusion for constructs like "inline int a(), b;" 3553 if (D.getDeclSpec().isInlineSpecified()) 3554 Diag(D.getDeclSpec().getInlineSpecLoc(), 3555 diag::err_inline_non_function); 3556 3557 if (D.getDeclSpec().isVirtualSpecified()) 3558 Diag(D.getDeclSpec().getVirtualSpecLoc(), 3559 diag::err_virtual_non_function); 3560 3561 if (D.getDeclSpec().isExplicitSpecified()) 3562 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3563 diag::err_explicit_non_function); 3564} 3565 3566NamedDecl* 3567Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 3568 TypeSourceInfo *TInfo, LookupResult &Previous) { 3569 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 3570 if (D.getCXXScopeSpec().isSet()) { 3571 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 3572 << D.getCXXScopeSpec().getRange(); 3573 D.setInvalidType(); 3574 // Pretend we didn't see the scope specifier. 3575 DC = CurContext; 3576 Previous.clear(); 3577 } 3578 3579 if (getLangOptions().CPlusPlus) { 3580 // Check that there are no default arguments (C++ only). 3581 CheckExtraCXXDefaultArguments(D); 3582 } 3583 3584 DiagnoseFunctionSpecifiers(D); 3585 3586 if (D.getDeclSpec().isThreadSpecified()) 3587 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 3588 if (D.getDeclSpec().isConstexprSpecified()) 3589 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 3590 << 1; 3591 3592 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 3593 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 3594 << D.getName().getSourceRange(); 3595 return 0; 3596 } 3597 3598 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 3599 if (!NewTD) return 0; 3600 3601 // Handle attributes prior to checking for duplicates in MergeVarDecl 3602 ProcessDeclAttributes(S, NewTD, D); 3603 3604 CheckTypedefForVariablyModifiedType(S, NewTD); 3605 3606 bool Redeclaration = D.isRedeclaration(); 3607 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 3608 D.setRedeclaration(Redeclaration); 3609 return ND; 3610} 3611 3612void 3613Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 3614 // C99 6.7.7p2: If a typedef name specifies a variably modified type 3615 // then it shall have block scope. 3616 // Note that variably modified types must be fixed before merging the decl so 3617 // that redeclarations will match. 3618 QualType T = NewTD->getUnderlyingType(); 3619 if (T->isVariablyModifiedType()) { 3620 getCurFunction()->setHasBranchProtectedScope(); 3621 3622 if (S->getFnParent() == 0) { 3623 bool SizeIsNegative; 3624 llvm::APSInt Oversized; 3625 QualType FixedTy = 3626 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 3627 Oversized); 3628 if (!FixedTy.isNull()) { 3629 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 3630 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy)); 3631 } else { 3632 if (SizeIsNegative) 3633 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 3634 else if (T->isVariableArrayType()) 3635 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 3636 else if (Oversized.getBoolValue()) 3637 Diag(NewTD->getLocation(), diag::err_array_too_large) 3638 << Oversized.toString(10); 3639 else 3640 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 3641 NewTD->setInvalidDecl(); 3642 } 3643 } 3644 } 3645} 3646 3647 3648/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 3649/// declares a typedef-name, either using the 'typedef' type specifier or via 3650/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 3651NamedDecl* 3652Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 3653 LookupResult &Previous, bool &Redeclaration) { 3654 // Merge the decl with the existing one if appropriate. If the decl is 3655 // in an outer scope, it isn't the same thing. 3656 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false, 3657 /*ExplicitInstantiationOrSpecialization=*/false); 3658 if (!Previous.empty()) { 3659 Redeclaration = true; 3660 MergeTypedefNameDecl(NewTD, Previous); 3661 } 3662 3663 // If this is the C FILE type, notify the AST context. 3664 if (IdentifierInfo *II = NewTD->getIdentifier()) 3665 if (!NewTD->isInvalidDecl() && 3666 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 3667 if (II->isStr("FILE")) 3668 Context.setFILEDecl(NewTD); 3669 else if (II->isStr("jmp_buf")) 3670 Context.setjmp_bufDecl(NewTD); 3671 else if (II->isStr("sigjmp_buf")) 3672 Context.setsigjmp_bufDecl(NewTD); 3673 else if (II->isStr("ucontext_t")) 3674 Context.setucontext_tDecl(NewTD); 3675 else if (II->isStr("__builtin_va_list")) 3676 Context.setBuiltinVaListType(Context.getTypedefType(NewTD)); 3677 } 3678 3679 return NewTD; 3680} 3681 3682/// \brief Determines whether the given declaration is an out-of-scope 3683/// previous declaration. 3684/// 3685/// This routine should be invoked when name lookup has found a 3686/// previous declaration (PrevDecl) that is not in the scope where a 3687/// new declaration by the same name is being introduced. If the new 3688/// declaration occurs in a local scope, previous declarations with 3689/// linkage may still be considered previous declarations (C99 3690/// 6.2.2p4-5, C++ [basic.link]p6). 3691/// 3692/// \param PrevDecl the previous declaration found by name 3693/// lookup 3694/// 3695/// \param DC the context in which the new declaration is being 3696/// declared. 3697/// 3698/// \returns true if PrevDecl is an out-of-scope previous declaration 3699/// for a new delcaration with the same name. 3700static bool 3701isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 3702 ASTContext &Context) { 3703 if (!PrevDecl) 3704 return false; 3705 3706 if (!PrevDecl->hasLinkage()) 3707 return false; 3708 3709 if (Context.getLangOptions().CPlusPlus) { 3710 // C++ [basic.link]p6: 3711 // If there is a visible declaration of an entity with linkage 3712 // having the same name and type, ignoring entities declared 3713 // outside the innermost enclosing namespace scope, the block 3714 // scope declaration declares that same entity and receives the 3715 // linkage of the previous declaration. 3716 DeclContext *OuterContext = DC->getRedeclContext(); 3717 if (!OuterContext->isFunctionOrMethod()) 3718 // This rule only applies to block-scope declarations. 3719 return false; 3720 3721 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 3722 if (PrevOuterContext->isRecord()) 3723 // We found a member function: ignore it. 3724 return false; 3725 3726 // Find the innermost enclosing namespace for the new and 3727 // previous declarations. 3728 OuterContext = OuterContext->getEnclosingNamespaceContext(); 3729 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 3730 3731 // The previous declaration is in a different namespace, so it 3732 // isn't the same function. 3733 if (!OuterContext->Equals(PrevOuterContext)) 3734 return false; 3735 } 3736 3737 return true; 3738} 3739 3740static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 3741 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3742 if (!SS.isSet()) return; 3743 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 3744} 3745 3746bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 3747 QualType type = decl->getType(); 3748 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 3749 if (lifetime == Qualifiers::OCL_Autoreleasing) { 3750 // Various kinds of declaration aren't allowed to be __autoreleasing. 3751 unsigned kind = -1U; 3752 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 3753 if (var->hasAttr<BlocksAttr>()) 3754 kind = 0; // __block 3755 else if (!var->hasLocalStorage()) 3756 kind = 1; // global 3757 } else if (isa<ObjCIvarDecl>(decl)) { 3758 kind = 3; // ivar 3759 } else if (isa<FieldDecl>(decl)) { 3760 kind = 2; // field 3761 } 3762 3763 if (kind != -1U) { 3764 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 3765 << kind; 3766 } 3767 } else if (lifetime == Qualifiers::OCL_None) { 3768 // Try to infer lifetime. 3769 if (!type->isObjCLifetimeType()) 3770 return false; 3771 3772 lifetime = type->getObjCARCImplicitLifetime(); 3773 type = Context.getLifetimeQualifiedType(type, lifetime); 3774 decl->setType(type); 3775 } 3776 3777 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 3778 // Thread-local variables cannot have lifetime. 3779 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 3780 var->isThreadSpecified()) { 3781 Diag(var->getLocation(), diag::err_arc_thread_ownership) 3782 << var->getType(); 3783 return true; 3784 } 3785 } 3786 3787 return false; 3788} 3789 3790NamedDecl* 3791Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 3792 TypeSourceInfo *TInfo, LookupResult &Previous, 3793 MultiTemplateParamsArg TemplateParamLists) { 3794 QualType R = TInfo->getType(); 3795 DeclarationName Name = GetNameForDeclarator(D).getName(); 3796 3797 // Check that there are no default arguments (C++ only). 3798 if (getLangOptions().CPlusPlus) 3799 CheckExtraCXXDefaultArguments(D); 3800 3801 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 3802 assert(SCSpec != DeclSpec::SCS_typedef && 3803 "Parser allowed 'typedef' as storage class VarDecl."); 3804 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 3805 if (SCSpec == DeclSpec::SCS_mutable) { 3806 // mutable can only appear on non-static class members, so it's always 3807 // an error here 3808 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 3809 D.setInvalidType(); 3810 SC = SC_None; 3811 } 3812 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 3813 VarDecl::StorageClass SCAsWritten 3814 = StorageClassSpecToVarDeclStorageClass(SCSpec); 3815 3816 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3817 if (!II) { 3818 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 3819 << Name; 3820 return 0; 3821 } 3822 3823 DiagnoseFunctionSpecifiers(D); 3824 3825 if (!DC->isRecord() && S->getFnParent() == 0) { 3826 // C99 6.9p2: The storage-class specifiers auto and register shall not 3827 // appear in the declaration specifiers in an external declaration. 3828 if (SC == SC_Auto || SC == SC_Register) { 3829 3830 // If this is a register variable with an asm label specified, then this 3831 // is a GNU extension. 3832 if (SC == SC_Register && D.getAsmLabel()) 3833 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 3834 else 3835 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 3836 D.setInvalidType(); 3837 } 3838 } 3839 3840 if (getLangOptions().OpenCL) { 3841 // Set up the special work-group-local storage class for variables in the 3842 // OpenCL __local address space. 3843 if (R.getAddressSpace() == LangAS::opencl_local) 3844 SC = SC_OpenCLWorkGroupLocal; 3845 } 3846 3847 bool isExplicitSpecialization = false; 3848 VarDecl *NewVD; 3849 if (!getLangOptions().CPlusPlus) { 3850 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(), 3851 D.getIdentifierLoc(), II, 3852 R, TInfo, SC, SCAsWritten); 3853 3854 if (D.isInvalidType()) 3855 NewVD->setInvalidDecl(); 3856 } else { 3857 if (DC->isRecord() && !CurContext->isRecord()) { 3858 // This is an out-of-line definition of a static data member. 3859 if (SC == SC_Static) { 3860 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 3861 diag::err_static_out_of_line) 3862 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 3863 } else if (SC == SC_None) 3864 SC = SC_Static; 3865 } 3866 if (SC == SC_Static) { 3867 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 3868 if (RD->isLocalClass()) 3869 Diag(D.getIdentifierLoc(), 3870 diag::err_static_data_member_not_allowed_in_local_class) 3871 << Name << RD->getDeclName(); 3872 3873 // C++ [class.union]p1: If a union contains a static data member, 3874 // the program is ill-formed. 3875 // 3876 // We also disallow static data members in anonymous structs. 3877 if (CurContext->isRecord() && (RD->isUnion() || !RD->getDeclName())) 3878 Diag(D.getIdentifierLoc(), 3879 diag::err_static_data_member_not_allowed_in_union_or_anon_struct) 3880 << Name << RD->isUnion(); 3881 } 3882 } 3883 3884 // Match up the template parameter lists with the scope specifier, then 3885 // determine whether we have a template or a template specialization. 3886 isExplicitSpecialization = false; 3887 bool Invalid = false; 3888 if (TemplateParameterList *TemplateParams 3889 = MatchTemplateParametersToScopeSpecifier( 3890 D.getDeclSpec().getSourceRange().getBegin(), 3891 D.getIdentifierLoc(), 3892 D.getCXXScopeSpec(), 3893 TemplateParamLists.get(), 3894 TemplateParamLists.size(), 3895 /*never a friend*/ false, 3896 isExplicitSpecialization, 3897 Invalid)) { 3898 if (TemplateParams->size() > 0) { 3899 // There is no such thing as a variable template. 3900 Diag(D.getIdentifierLoc(), diag::err_template_variable) 3901 << II 3902 << SourceRange(TemplateParams->getTemplateLoc(), 3903 TemplateParams->getRAngleLoc()); 3904 return 0; 3905 } else { 3906 // There is an extraneous 'template<>' for this variable. Complain 3907 // about it, but allow the declaration of the variable. 3908 Diag(TemplateParams->getTemplateLoc(), 3909 diag::err_template_variable_noparams) 3910 << II 3911 << SourceRange(TemplateParams->getTemplateLoc(), 3912 TemplateParams->getRAngleLoc()); 3913 } 3914 } 3915 3916 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(), 3917 D.getIdentifierLoc(), II, 3918 R, TInfo, SC, SCAsWritten); 3919 3920 // If this decl has an auto type in need of deduction, make a note of the 3921 // Decl so we can diagnose uses of it in its own initializer. 3922 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 3923 R->getContainedAutoType()) 3924 ParsingInitForAutoVars.insert(NewVD); 3925 3926 if (D.isInvalidType() || Invalid) 3927 NewVD->setInvalidDecl(); 3928 3929 SetNestedNameSpecifier(NewVD, D); 3930 3931 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) { 3932 NewVD->setTemplateParameterListsInfo(Context, 3933 TemplateParamLists.size(), 3934 TemplateParamLists.release()); 3935 } 3936 3937 if (D.getDeclSpec().isConstexprSpecified()) { 3938 // FIXME: once we know whether there's an initializer, apply this to 3939 // static data members too. 3940 if (!NewVD->isStaticDataMember() && 3941 !NewVD->isThisDeclarationADefinition()) { 3942 // 'constexpr' is redundant and ill-formed on a non-defining declaration 3943 // of a variable. Suggest replacing it with 'const' if appropriate. 3944 SourceLocation ConstexprLoc = D.getDeclSpec().getConstexprSpecLoc(); 3945 SourceRange ConstexprRange(ConstexprLoc, ConstexprLoc); 3946 // If the declarator is complex, we need to move the keyword to the 3947 // innermost chunk as we switch it from 'constexpr' to 'const'. 3948 int Kind = DeclaratorChunk::Paren; 3949 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 3950 Kind = D.getTypeObject(I).Kind; 3951 if (Kind != DeclaratorChunk::Paren) 3952 break; 3953 } 3954 if ((D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) || 3955 Kind == DeclaratorChunk::Reference) 3956 Diag(ConstexprLoc, diag::err_invalid_constexpr_var_decl) 3957 << FixItHint::CreateRemoval(ConstexprRange); 3958 else if (Kind == DeclaratorChunk::Paren) 3959 Diag(ConstexprLoc, diag::err_invalid_constexpr_var_decl) 3960 << FixItHint::CreateReplacement(ConstexprRange, "const"); 3961 else 3962 Diag(ConstexprLoc, diag::err_invalid_constexpr_var_decl) 3963 << FixItHint::CreateRemoval(ConstexprRange) 3964 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "const "); 3965 } else { 3966 NewVD->setConstexpr(true); 3967 } 3968 } 3969 } 3970 3971 // Set the lexical context. If the declarator has a C++ scope specifier, the 3972 // lexical context will be different from the semantic context. 3973 NewVD->setLexicalDeclContext(CurContext); 3974 3975 if (D.getDeclSpec().isThreadSpecified()) { 3976 if (NewVD->hasLocalStorage()) 3977 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global); 3978 else if (!Context.getTargetInfo().isTLSSupported()) 3979 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported); 3980 else 3981 NewVD->setThreadSpecified(true); 3982 } 3983 3984 if (D.getDeclSpec().isModulePrivateSpecified()) { 3985 if (isExplicitSpecialization) 3986 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 3987 << 2 3988 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 3989 else if (NewVD->hasLocalStorage()) 3990 Diag(NewVD->getLocation(), diag::err_module_private_local) 3991 << 0 << NewVD->getDeclName() 3992 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 3993 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 3994 else 3995 NewVD->setModulePrivate(); 3996 } 3997 3998 // Handle attributes prior to checking for duplicates in MergeVarDecl 3999 ProcessDeclAttributes(S, NewVD, D); 4000 4001 // In auto-retain/release, infer strong retension for variables of 4002 // retainable type. 4003 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 4004 NewVD->setInvalidDecl(); 4005 4006 // Handle GNU asm-label extension (encoded as an attribute). 4007 if (Expr *E = (Expr*)D.getAsmLabel()) { 4008 // The parser guarantees this is a string. 4009 StringLiteral *SE = cast<StringLiteral>(E); 4010 StringRef Label = SE->getString(); 4011 if (S->getFnParent() != 0) { 4012 switch (SC) { 4013 case SC_None: 4014 case SC_Auto: 4015 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 4016 break; 4017 case SC_Register: 4018 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 4019 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 4020 break; 4021 case SC_Static: 4022 case SC_Extern: 4023 case SC_PrivateExtern: 4024 case SC_OpenCLWorkGroupLocal: 4025 break; 4026 } 4027 } 4028 4029 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 4030 Context, Label)); 4031 } 4032 4033 // Diagnose shadowed variables before filtering for scope. 4034 if (!D.getCXXScopeSpec().isSet()) 4035 CheckShadow(S, NewVD, Previous); 4036 4037 // Don't consider existing declarations that are in a different 4038 // scope and are out-of-semantic-context declarations (if the new 4039 // declaration has linkage). 4040 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(), 4041 isExplicitSpecialization); 4042 4043 if (!getLangOptions().CPlusPlus) { 4044 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 4045 } else { 4046 // Merge the decl with the existing one if appropriate. 4047 if (!Previous.empty()) { 4048 if (Previous.isSingleResult() && 4049 isa<FieldDecl>(Previous.getFoundDecl()) && 4050 D.getCXXScopeSpec().isSet()) { 4051 // The user tried to define a non-static data member 4052 // out-of-line (C++ [dcl.meaning]p1). 4053 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 4054 << D.getCXXScopeSpec().getRange(); 4055 Previous.clear(); 4056 NewVD->setInvalidDecl(); 4057 } 4058 } else if (D.getCXXScopeSpec().isSet()) { 4059 // No previous declaration in the qualifying scope. 4060 Diag(D.getIdentifierLoc(), diag::err_no_member) 4061 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 4062 << D.getCXXScopeSpec().getRange(); 4063 NewVD->setInvalidDecl(); 4064 } 4065 4066 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 4067 4068 // This is an explicit specialization of a static data member. Check it. 4069 if (isExplicitSpecialization && !NewVD->isInvalidDecl() && 4070 CheckMemberSpecialization(NewVD, Previous)) 4071 NewVD->setInvalidDecl(); 4072 } 4073 4074 // attributes declared post-definition are currently ignored 4075 // FIXME: This should be handled in attribute merging, not 4076 // here. 4077 if (Previous.isSingleResult()) { 4078 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4079 if (Def && (Def = Def->getDefinition()) && 4080 Def != NewVD && D.hasAttributes()) { 4081 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition); 4082 Diag(Def->getLocation(), diag::note_previous_definition); 4083 } 4084 } 4085 4086 // If this is a locally-scoped extern C variable, update the map of 4087 // such variables. 4088 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() && 4089 !NewVD->isInvalidDecl()) 4090 RegisterLocallyScopedExternCDecl(NewVD, Previous, S); 4091 4092 // If there's a #pragma GCC visibility in scope, and this isn't a class 4093 // member, set the visibility of this variable. 4094 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord()) 4095 AddPushedVisibilityAttribute(NewVD); 4096 4097 MarkUnusedFileScopedDecl(NewVD); 4098 4099 return NewVD; 4100} 4101 4102/// \brief Diagnose variable or built-in function shadowing. Implements 4103/// -Wshadow. 4104/// 4105/// This method is called whenever a VarDecl is added to a "useful" 4106/// scope. 4107/// 4108/// \param S the scope in which the shadowing name is being declared 4109/// \param R the lookup of the name 4110/// 4111void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 4112 // Return if warning is ignored. 4113 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 4114 DiagnosticsEngine::Ignored) 4115 return; 4116 4117 // Don't diagnose declarations at file scope. 4118 if (D->hasGlobalStorage()) 4119 return; 4120 4121 DeclContext *NewDC = D->getDeclContext(); 4122 4123 // Only diagnose if we're shadowing an unambiguous field or variable. 4124 if (R.getResultKind() != LookupResult::Found) 4125 return; 4126 4127 NamedDecl* ShadowedDecl = R.getFoundDecl(); 4128 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 4129 return; 4130 4131 // Fields are not shadowed by variables in C++ static methods. 4132 if (isa<FieldDecl>(ShadowedDecl)) 4133 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 4134 if (MD->isStatic()) 4135 return; 4136 4137 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 4138 if (shadowedVar->isExternC()) { 4139 // For shadowing external vars, make sure that we point to the global 4140 // declaration, not a locally scoped extern declaration. 4141 for (VarDecl::redecl_iterator 4142 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end(); 4143 I != E; ++I) 4144 if (I->isFileVarDecl()) { 4145 ShadowedDecl = *I; 4146 break; 4147 } 4148 } 4149 4150 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 4151 4152 // Only warn about certain kinds of shadowing for class members. 4153 if (NewDC && NewDC->isRecord()) { 4154 // In particular, don't warn about shadowing non-class members. 4155 if (!OldDC->isRecord()) 4156 return; 4157 4158 // TODO: should we warn about static data members shadowing 4159 // static data members from base classes? 4160 4161 // TODO: don't diagnose for inaccessible shadowed members. 4162 // This is hard to do perfectly because we might friend the 4163 // shadowing context, but that's just a false negative. 4164 } 4165 4166 // Determine what kind of declaration we're shadowing. 4167 unsigned Kind; 4168 if (isa<RecordDecl>(OldDC)) { 4169 if (isa<FieldDecl>(ShadowedDecl)) 4170 Kind = 3; // field 4171 else 4172 Kind = 2; // static data member 4173 } else if (OldDC->isFileContext()) 4174 Kind = 1; // global 4175 else 4176 Kind = 0; // local 4177 4178 DeclarationName Name = R.getLookupName(); 4179 4180 // Emit warning and note. 4181 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 4182 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 4183} 4184 4185/// \brief Check -Wshadow without the advantage of a previous lookup. 4186void Sema::CheckShadow(Scope *S, VarDecl *D) { 4187 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 4188 DiagnosticsEngine::Ignored) 4189 return; 4190 4191 LookupResult R(*this, D->getDeclName(), D->getLocation(), 4192 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 4193 LookupName(R, S); 4194 CheckShadow(S, D, R); 4195} 4196 4197/// \brief Perform semantic checking on a newly-created variable 4198/// declaration. 4199/// 4200/// This routine performs all of the type-checking required for a 4201/// variable declaration once it has been built. It is used both to 4202/// check variables after they have been parsed and their declarators 4203/// have been translated into a declaration, and to check variables 4204/// that have been instantiated from a template. 4205/// 4206/// Sets NewVD->isInvalidDecl() if an error was encountered. 4207/// 4208/// Returns true if the variable declaration is a redeclaration. 4209bool Sema::CheckVariableDeclaration(VarDecl *NewVD, 4210 LookupResult &Previous) { 4211 // If the decl is already known invalid, don't check it. 4212 if (NewVD->isInvalidDecl()) 4213 return false; 4214 4215 QualType T = NewVD->getType(); 4216 4217 if (T->isObjCObjectType()) { 4218 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 4219 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 4220 T = Context.getObjCObjectPointerType(T); 4221 NewVD->setType(T); 4222 } 4223 4224 // Emit an error if an address space was applied to decl with local storage. 4225 // This includes arrays of objects with address space qualifiers, but not 4226 // automatic variables that point to other address spaces. 4227 // ISO/IEC TR 18037 S5.1.2 4228 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 4229 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 4230 NewVD->setInvalidDecl(); 4231 return false; 4232 } 4233 4234 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 4235 && !NewVD->hasAttr<BlocksAttr>()) { 4236 if (getLangOptions().getGC() != LangOptions::NonGC) 4237 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 4238 else 4239 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 4240 } 4241 4242 bool isVM = T->isVariablyModifiedType(); 4243 if (isVM || NewVD->hasAttr<CleanupAttr>() || 4244 NewVD->hasAttr<BlocksAttr>()) 4245 getCurFunction()->setHasBranchProtectedScope(); 4246 4247 if ((isVM && NewVD->hasLinkage()) || 4248 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 4249 bool SizeIsNegative; 4250 llvm::APSInt Oversized; 4251 QualType FixedTy = 4252 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 4253 Oversized); 4254 4255 if (FixedTy.isNull() && T->isVariableArrayType()) { 4256 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 4257 // FIXME: This won't give the correct result for 4258 // int a[10][n]; 4259 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 4260 4261 if (NewVD->isFileVarDecl()) 4262 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 4263 << SizeRange; 4264 else if (NewVD->getStorageClass() == SC_Static) 4265 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 4266 << SizeRange; 4267 else 4268 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 4269 << SizeRange; 4270 NewVD->setInvalidDecl(); 4271 return false; 4272 } 4273 4274 if (FixedTy.isNull()) { 4275 if (NewVD->isFileVarDecl()) 4276 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 4277 else 4278 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 4279 NewVD->setInvalidDecl(); 4280 return false; 4281 } 4282 4283 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 4284 NewVD->setType(FixedTy); 4285 } 4286 4287 if (Previous.empty() && NewVD->isExternC()) { 4288 // Since we did not find anything by this name and we're declaring 4289 // an extern "C" variable, look for a non-visible extern "C" 4290 // declaration with the same name. 4291 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4292 = findLocallyScopedExternalDecl(NewVD->getDeclName()); 4293 if (Pos != LocallyScopedExternalDecls.end()) 4294 Previous.addDecl(Pos->second); 4295 } 4296 4297 if (T->isVoidType() && !NewVD->hasExternalStorage()) { 4298 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 4299 << T; 4300 NewVD->setInvalidDecl(); 4301 return false; 4302 } 4303 4304 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 4305 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 4306 NewVD->setInvalidDecl(); 4307 return false; 4308 } 4309 4310 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 4311 Diag(NewVD->getLocation(), diag::err_block_on_vm); 4312 NewVD->setInvalidDecl(); 4313 return false; 4314 } 4315 4316 // Function pointers and references cannot have qualified function type, only 4317 // function pointer-to-members can do that. 4318 QualType Pointee; 4319 unsigned PtrOrRef = 0; 4320 if (const PointerType *Ptr = T->getAs<PointerType>()) 4321 Pointee = Ptr->getPointeeType(); 4322 else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) { 4323 Pointee = Ref->getPointeeType(); 4324 PtrOrRef = 1; 4325 } 4326 if (!Pointee.isNull() && Pointee->isFunctionProtoType() && 4327 Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) { 4328 Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer) 4329 << PtrOrRef; 4330 NewVD->setInvalidDecl(); 4331 return false; 4332 } 4333 4334 if (!Previous.empty()) { 4335 MergeVarDecl(NewVD, Previous); 4336 return true; 4337 } 4338 return false; 4339} 4340 4341/// \brief Data used with FindOverriddenMethod 4342struct FindOverriddenMethodData { 4343 Sema *S; 4344 CXXMethodDecl *Method; 4345}; 4346 4347/// \brief Member lookup function that determines whether a given C++ 4348/// method overrides a method in a base class, to be used with 4349/// CXXRecordDecl::lookupInBases(). 4350static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 4351 CXXBasePath &Path, 4352 void *UserData) { 4353 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 4354 4355 FindOverriddenMethodData *Data 4356 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 4357 4358 DeclarationName Name = Data->Method->getDeclName(); 4359 4360 // FIXME: Do we care about other names here too? 4361 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4362 // We really want to find the base class destructor here. 4363 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 4364 CanQualType CT = Data->S->Context.getCanonicalType(T); 4365 4366 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 4367 } 4368 4369 for (Path.Decls = BaseRecord->lookup(Name); 4370 Path.Decls.first != Path.Decls.second; 4371 ++Path.Decls.first) { 4372 NamedDecl *D = *Path.Decls.first; 4373 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 4374 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 4375 return true; 4376 } 4377 } 4378 4379 return false; 4380} 4381 4382/// AddOverriddenMethods - See if a method overrides any in the base classes, 4383/// and if so, check that it's a valid override and remember it. 4384bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 4385 // Look for virtual methods in base classes that this method might override. 4386 CXXBasePaths Paths; 4387 FindOverriddenMethodData Data; 4388 Data.Method = MD; 4389 Data.S = this; 4390 bool AddedAny = false; 4391 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 4392 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 4393 E = Paths.found_decls_end(); I != E; ++I) { 4394 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 4395 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 4396 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 4397 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 4398 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 4399 AddedAny = true; 4400 } 4401 } 4402 } 4403 } 4404 4405 return AddedAny; 4406} 4407 4408namespace { 4409 // Struct for holding all of the extra arguments needed by 4410 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 4411 struct ActOnFDArgs { 4412 Scope *S; 4413 Declarator &D; 4414 MultiTemplateParamsArg TemplateParamLists; 4415 bool AddToScope; 4416 }; 4417} 4418 4419/// \brief Generate diagnostics for an invalid function redeclaration. 4420/// 4421/// This routine handles generating the diagnostic messages for an invalid 4422/// function redeclaration, including finding possible similar declarations 4423/// or performing typo correction if there are no previous declarations with 4424/// the same name. 4425/// 4426/// Returns a NamedDecl iff typo correction was performed and substituting in 4427/// the new declaration name does not cause new errors. 4428static NamedDecl* DiagnoseInvalidRedeclaration( 4429 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 4430 ActOnFDArgs &ExtraArgs) { 4431 NamedDecl *Result = NULL; 4432 DeclarationName Name = NewFD->getDeclName(); 4433 DeclContext *NewDC = NewFD->getDeclContext(); 4434 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 4435 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 4436 llvm::SmallVector<unsigned, 1> MismatchedParams; 4437 llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches; 4438 TypoCorrection Correction; 4439 bool isFriendDecl = (SemaRef.getLangOptions().CPlusPlus && 4440 ExtraArgs.D.getDeclSpec().isFriendSpecified()); 4441 unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend 4442 : diag::err_member_def_does_not_match; 4443 4444 NewFD->setInvalidDecl(); 4445 SemaRef.LookupQualifiedName(Prev, NewDC); 4446 assert(!Prev.isAmbiguous() && 4447 "Cannot have an ambiguity in previous-declaration lookup"); 4448 if (!Prev.empty()) { 4449 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 4450 Func != FuncEnd; ++Func) { 4451 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 4452 if (FD && 4453 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 4454 // Add 1 to the index so that 0 can mean the mismatch didn't 4455 // involve a parameter 4456 unsigned ParamNum = 4457 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 4458 NearMatches.push_back(std::make_pair(FD, ParamNum)); 4459 } 4460 } 4461 // If the qualified name lookup yielded nothing, try typo correction 4462 } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(), 4463 Prev.getLookupKind(), 0, 0, NewDC)) && 4464 Correction.getCorrection() != Name) { 4465 // Trap errors. 4466 Sema::SFINAETrap Trap(SemaRef); 4467 4468 // Set up everything for the call to ActOnFunctionDeclarator 4469 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 4470 ExtraArgs.D.getIdentifierLoc()); 4471 Previous.clear(); 4472 Previous.setLookupName(Correction.getCorrection()); 4473 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 4474 CDeclEnd = Correction.end(); 4475 CDecl != CDeclEnd; ++CDecl) { 4476 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 4477 if (FD && hasSimilarParameters(SemaRef.Context, FD, NewFD, 4478 MismatchedParams)) { 4479 Previous.addDecl(FD); 4480 } 4481 } 4482 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 4483 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 4484 // pieces need to verify the typo-corrected C++ declaraction and hopefully 4485 // eliminate the need for the parameter pack ExtraArgs. 4486 Result = SemaRef.ActOnFunctionDeclarator(ExtraArgs.S, ExtraArgs.D, 4487 NewFD->getDeclContext(), 4488 NewFD->getTypeSourceInfo(), 4489 Previous, 4490 ExtraArgs.TemplateParamLists, 4491 ExtraArgs.AddToScope); 4492 if (Trap.hasErrorOccurred()) { 4493 // Pretend the typo correction never occurred 4494 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 4495 ExtraArgs.D.getIdentifierLoc()); 4496 ExtraArgs.D.setRedeclaration(wasRedeclaration); 4497 Previous.clear(); 4498 Previous.setLookupName(Name); 4499 Result = NULL; 4500 } else { 4501 for (LookupResult::iterator Func = Previous.begin(), 4502 FuncEnd = Previous.end(); 4503 Func != FuncEnd; ++Func) { 4504 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) 4505 NearMatches.push_back(std::make_pair(FD, 0)); 4506 } 4507 } 4508 if (NearMatches.empty()) { 4509 // Ignore the correction if it didn't yield any close FunctionDecl matches 4510 Correction = TypoCorrection(); 4511 } else { 4512 DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest 4513 : diag::err_member_def_does_not_match_suggest; 4514 } 4515 } 4516 4517 if (Correction) 4518 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 4519 << Name << NewDC << Correction.getQuoted(SemaRef.getLangOptions()) 4520 << FixItHint::CreateReplacement( 4521 NewFD->getLocation(), 4522 Correction.getAsString(SemaRef.getLangOptions())); 4523 else 4524 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 4525 << Name << NewDC << NewFD->getLocation(); 4526 4527 bool NewFDisConst = false; 4528 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 4529 NewFDisConst = NewMD->getTypeQualifiers() & Qualifiers::Const; 4530 4531 for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator 4532 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 4533 NearMatch != NearMatchEnd; ++NearMatch) { 4534 FunctionDecl *FD = NearMatch->first; 4535 bool FDisConst = false; 4536 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 4537 FDisConst = MD->getTypeQualifiers() & Qualifiers::Const; 4538 4539 if (unsigned Idx = NearMatch->second) { 4540 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 4541 SemaRef.Diag(FDParam->getTypeSpecStartLoc(), 4542 diag::note_member_def_close_param_match) 4543 << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType(); 4544 } else if (Correction) { 4545 SemaRef.Diag(FD->getLocation(), diag::note_previous_decl) 4546 << Correction.getQuoted(SemaRef.getLangOptions()); 4547 } else if (FDisConst != NewFDisConst) { 4548 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 4549 << NewFDisConst << FD->getSourceRange().getEnd(); 4550 } else 4551 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match); 4552 } 4553 return Result; 4554} 4555 4556static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 4557 Declarator &D) { 4558 switch (D.getDeclSpec().getStorageClassSpec()) { 4559 default: llvm_unreachable("Unknown storage class!"); 4560 case DeclSpec::SCS_auto: 4561 case DeclSpec::SCS_register: 4562 case DeclSpec::SCS_mutable: 4563 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4564 diag::err_typecheck_sclass_func); 4565 D.setInvalidType(); 4566 break; 4567 case DeclSpec::SCS_unspecified: break; 4568 case DeclSpec::SCS_extern: return SC_Extern; 4569 case DeclSpec::SCS_static: { 4570 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 4571 // C99 6.7.1p5: 4572 // The declaration of an identifier for a function that has 4573 // block scope shall have no explicit storage-class specifier 4574 // other than extern 4575 // See also (C++ [dcl.stc]p4). 4576 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4577 diag::err_static_block_func); 4578 break; 4579 } else 4580 return SC_Static; 4581 } 4582 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4583 } 4584 4585 // No explicit storage class has already been returned 4586 return SC_None; 4587} 4588 4589static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 4590 DeclContext *DC, QualType &R, 4591 TypeSourceInfo *TInfo, 4592 FunctionDecl::StorageClass SC, 4593 bool &IsVirtualOkay) { 4594 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 4595 DeclarationName Name = NameInfo.getName(); 4596 4597 FunctionDecl *NewFD = 0; 4598 bool isInline = D.getDeclSpec().isInlineSpecified(); 4599 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 4600 FunctionDecl::StorageClass SCAsWritten 4601 = StorageClassSpecToFunctionDeclStorageClass(SCSpec); 4602 4603 if (!SemaRef.getLangOptions().CPlusPlus) { 4604 // Determine whether the function was written with a 4605 // prototype. This true when: 4606 // - there is a prototype in the declarator, or 4607 // - the type R of the function is some kind of typedef or other reference 4608 // to a type name (which eventually refers to a function type). 4609 bool HasPrototype = 4610 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 4611 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 4612 4613 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 4614 D.getSourceRange().getBegin(), NameInfo, R, 4615 TInfo, SC, SCAsWritten, isInline, 4616 HasPrototype); 4617 if (D.isInvalidType()) 4618 NewFD->setInvalidDecl(); 4619 4620 // Set the lexical context. 4621 NewFD->setLexicalDeclContext(SemaRef.CurContext); 4622 4623 return NewFD; 4624 } 4625 4626 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 4627 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 4628 4629 // Check that the return type is not an abstract class type. 4630 // For record types, this is done by the AbstractClassUsageDiagnoser once 4631 // the class has been completely parsed. 4632 if (!DC->isRecord() && 4633 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(), 4634 R->getAs<FunctionType>()->getResultType(), 4635 diag::err_abstract_type_in_decl, 4636 SemaRef.AbstractReturnType)) 4637 D.setInvalidType(); 4638 4639 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 4640 // This is a C++ constructor declaration. 4641 assert(DC->isRecord() && 4642 "Constructors can only be declared in a member context"); 4643 4644 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 4645 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 4646 D.getSourceRange().getBegin(), NameInfo, 4647 R, TInfo, isExplicit, isInline, 4648 /*isImplicitlyDeclared=*/false, 4649 isConstexpr); 4650 4651 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4652 // This is a C++ destructor declaration. 4653 if (DC->isRecord()) { 4654 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 4655 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 4656 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 4657 SemaRef.Context, Record, 4658 D.getSourceRange().getBegin(), 4659 NameInfo, R, TInfo, isInline, 4660 /*isImplicitlyDeclared=*/false); 4661 4662 // If the class is complete, then we now create the implicit exception 4663 // specification. If the class is incomplete or dependent, we can't do 4664 // it yet. 4665 if (SemaRef.getLangOptions().CPlusPlus0x && !Record->isDependentType() && 4666 Record->getDefinition() && !Record->isBeingDefined() && 4667 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 4668 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 4669 } 4670 4671 IsVirtualOkay = true; 4672 return NewDD; 4673 4674 } else { 4675 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 4676 D.setInvalidType(); 4677 4678 // Create a FunctionDecl to satisfy the function definition parsing 4679 // code path. 4680 return FunctionDecl::Create(SemaRef.Context, DC, 4681 D.getSourceRange().getBegin(), 4682 D.getIdentifierLoc(), Name, R, TInfo, 4683 SC, SCAsWritten, isInline, 4684 /*hasPrototype=*/true, isConstexpr); 4685 } 4686 4687 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 4688 if (!DC->isRecord()) { 4689 SemaRef.Diag(D.getIdentifierLoc(), 4690 diag::err_conv_function_not_member); 4691 return 0; 4692 } 4693 4694 SemaRef.CheckConversionDeclarator(D, R, SC); 4695 IsVirtualOkay = true; 4696 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 4697 D.getSourceRange().getBegin(), NameInfo, 4698 R, TInfo, isInline, isExplicit, 4699 isConstexpr, SourceLocation()); 4700 4701 } else if (DC->isRecord()) { 4702 // If the name of the function is the same as the name of the record, 4703 // then this must be an invalid constructor that has a return type. 4704 // (The parser checks for a return type and makes the declarator a 4705 // constructor if it has no return type). 4706 if (Name.getAsIdentifierInfo() && 4707 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 4708 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 4709 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 4710 << SourceRange(D.getIdentifierLoc()); 4711 return 0; 4712 } 4713 4714 bool isStatic = SC == SC_Static; 4715 4716 // [class.free]p1: 4717 // Any allocation function for a class T is a static member 4718 // (even if not explicitly declared static). 4719 if (Name.getCXXOverloadedOperator() == OO_New || 4720 Name.getCXXOverloadedOperator() == OO_Array_New) 4721 isStatic = true; 4722 4723 // [class.free]p6 Any deallocation function for a class X is a static member 4724 // (even if not explicitly declared static). 4725 if (Name.getCXXOverloadedOperator() == OO_Delete || 4726 Name.getCXXOverloadedOperator() == OO_Array_Delete) 4727 isStatic = true; 4728 4729 IsVirtualOkay = !isStatic; 4730 4731 // This is a C++ method declaration. 4732 return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 4733 D.getSourceRange().getBegin(), NameInfo, R, 4734 TInfo, isStatic, SCAsWritten, isInline, 4735 isConstexpr, SourceLocation()); 4736 4737 } else { 4738 // Determine whether the function was written with a 4739 // prototype. This true when: 4740 // - we're in C++ (where every function has a prototype), 4741 return FunctionDecl::Create(SemaRef.Context, DC, 4742 D.getSourceRange().getBegin(), 4743 NameInfo, R, TInfo, SC, SCAsWritten, isInline, 4744 true/*HasPrototype*/, isConstexpr); 4745 } 4746} 4747 4748NamedDecl* 4749Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4750 TypeSourceInfo *TInfo, LookupResult &Previous, 4751 MultiTemplateParamsArg TemplateParamLists, 4752 bool &AddToScope) { 4753 QualType R = TInfo->getType(); 4754 4755 assert(R.getTypePtr()->isFunctionType()); 4756 4757 // TODO: consider using NameInfo for diagnostic. 4758 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4759 DeclarationName Name = NameInfo.getName(); 4760 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 4761 4762 if (D.getDeclSpec().isThreadSpecified()) 4763 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 4764 4765 // Do not allow returning a objc interface by-value. 4766 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) { 4767 Diag(D.getIdentifierLoc(), 4768 diag::err_object_cannot_be_passed_returned_by_value) << 0 4769 << R->getAs<FunctionType>()->getResultType() 4770 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*"); 4771 4772 QualType T = R->getAs<FunctionType>()->getResultType(); 4773 T = Context.getObjCObjectPointerType(T); 4774 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) { 4775 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4776 R = Context.getFunctionType(T, FPT->arg_type_begin(), 4777 FPT->getNumArgs(), EPI); 4778 } 4779 else if (isa<FunctionNoProtoType>(R)) 4780 R = Context.getFunctionNoProtoType(T); 4781 } 4782 4783 bool isFriend = false; 4784 FunctionTemplateDecl *FunctionTemplate = 0; 4785 bool isExplicitSpecialization = false; 4786 bool isFunctionTemplateSpecialization = false; 4787 bool isDependentClassScopeExplicitSpecialization = false; 4788 bool isVirtualOkay = false; 4789 4790 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 4791 isVirtualOkay); 4792 if (!NewFD) return 0; 4793 4794 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 4795 NewFD->setTopLevelDeclInObjCContainer(); 4796 4797 if (getLangOptions().CPlusPlus) { 4798 bool isInline = D.getDeclSpec().isInlineSpecified(); 4799 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 4800 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 4801 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 4802 isFriend = D.getDeclSpec().isFriendSpecified(); 4803 if (isFriend && !isInline && D.isFunctionDefinition()) { 4804 // C++ [class.friend]p5 4805 // A function can be defined in a friend declaration of a 4806 // class . . . . Such a function is implicitly inline. 4807 NewFD->setImplicitlyInline(); 4808 } 4809 4810 SetNestedNameSpecifier(NewFD, D); 4811 isExplicitSpecialization = false; 4812 isFunctionTemplateSpecialization = false; 4813 if (D.isInvalidType()) 4814 NewFD->setInvalidDecl(); 4815 4816 // Set the lexical context. If the declarator has a C++ 4817 // scope specifier, or is the object of a friend declaration, the 4818 // lexical context will be different from the semantic context. 4819 NewFD->setLexicalDeclContext(CurContext); 4820 4821 // Match up the template parameter lists with the scope specifier, then 4822 // determine whether we have a template or a template specialization. 4823 bool Invalid = false; 4824 if (TemplateParameterList *TemplateParams 4825 = MatchTemplateParametersToScopeSpecifier( 4826 D.getDeclSpec().getSourceRange().getBegin(), 4827 D.getIdentifierLoc(), 4828 D.getCXXScopeSpec(), 4829 TemplateParamLists.get(), 4830 TemplateParamLists.size(), 4831 isFriend, 4832 isExplicitSpecialization, 4833 Invalid)) { 4834 if (TemplateParams->size() > 0) { 4835 // This is a function template 4836 4837 // Check that we can declare a template here. 4838 if (CheckTemplateDeclScope(S, TemplateParams)) 4839 return 0; 4840 4841 // A destructor cannot be a template. 4842 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4843 Diag(NewFD->getLocation(), diag::err_destructor_template); 4844 return 0; 4845 } 4846 4847 // If we're adding a template to a dependent context, we may need to 4848 // rebuilding some of the types used within the template parameter list, 4849 // now that we know what the current instantiation is. 4850 if (DC->isDependentContext()) { 4851 ContextRAII SavedContext(*this, DC); 4852 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 4853 Invalid = true; 4854 } 4855 4856 4857 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 4858 NewFD->getLocation(), 4859 Name, TemplateParams, 4860 NewFD); 4861 FunctionTemplate->setLexicalDeclContext(CurContext); 4862 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 4863 4864 // For source fidelity, store the other template param lists. 4865 if (TemplateParamLists.size() > 1) { 4866 NewFD->setTemplateParameterListsInfo(Context, 4867 TemplateParamLists.size() - 1, 4868 TemplateParamLists.release()); 4869 } 4870 } else { 4871 // This is a function template specialization. 4872 isFunctionTemplateSpecialization = true; 4873 // For source fidelity, store all the template param lists. 4874 NewFD->setTemplateParameterListsInfo(Context, 4875 TemplateParamLists.size(), 4876 TemplateParamLists.release()); 4877 4878 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 4879 if (isFriend) { 4880 // We want to remove the "template<>", found here. 4881 SourceRange RemoveRange = TemplateParams->getSourceRange(); 4882 4883 // If we remove the template<> and the name is not a 4884 // template-id, we're actually silently creating a problem: 4885 // the friend declaration will refer to an untemplated decl, 4886 // and clearly the user wants a template specialization. So 4887 // we need to insert '<>' after the name. 4888 SourceLocation InsertLoc; 4889 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 4890 InsertLoc = D.getName().getSourceRange().getEnd(); 4891 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 4892 } 4893 4894 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 4895 << Name << RemoveRange 4896 << FixItHint::CreateRemoval(RemoveRange) 4897 << FixItHint::CreateInsertion(InsertLoc, "<>"); 4898 } 4899 } 4900 } 4901 else { 4902 // All template param lists were matched against the scope specifier: 4903 // this is NOT (an explicit specialization of) a template. 4904 if (TemplateParamLists.size() > 0) 4905 // For source fidelity, store all the template param lists. 4906 NewFD->setTemplateParameterListsInfo(Context, 4907 TemplateParamLists.size(), 4908 TemplateParamLists.release()); 4909 } 4910 4911 if (Invalid) { 4912 NewFD->setInvalidDecl(); 4913 if (FunctionTemplate) 4914 FunctionTemplate->setInvalidDecl(); 4915 } 4916 4917 // C++ [dcl.fct.spec]p5: 4918 // The virtual specifier shall only be used in declarations of 4919 // nonstatic class member functions that appear within a 4920 // member-specification of a class declaration; see 10.3. 4921 // 4922 if (isVirtual && !NewFD->isInvalidDecl()) { 4923 if (!isVirtualOkay) { 4924 Diag(D.getDeclSpec().getVirtualSpecLoc(), 4925 diag::err_virtual_non_function); 4926 } else if (!CurContext->isRecord()) { 4927 // 'virtual' was specified outside of the class. 4928 Diag(D.getDeclSpec().getVirtualSpecLoc(), 4929 diag::err_virtual_out_of_class) 4930 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 4931 } else if (NewFD->getDescribedFunctionTemplate()) { 4932 // C++ [temp.mem]p3: 4933 // A member function template shall not be virtual. 4934 Diag(D.getDeclSpec().getVirtualSpecLoc(), 4935 diag::err_virtual_member_function_template) 4936 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 4937 } else { 4938 // Okay: Add virtual to the method. 4939 NewFD->setVirtualAsWritten(true); 4940 } 4941 } 4942 4943 // C++ [dcl.fct.spec]p3: 4944 // The inline specifier shall not appear on a block scope function 4945 // declaration. 4946 if (isInline && !NewFD->isInvalidDecl()) { 4947 if (CurContext->isFunctionOrMethod()) { 4948 // 'inline' is not allowed on block scope function declaration. 4949 Diag(D.getDeclSpec().getInlineSpecLoc(), 4950 diag::err_inline_declaration_block_scope) << Name 4951 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 4952 } 4953 } 4954 4955 // C++ [dcl.fct.spec]p6: 4956 // The explicit specifier shall be used only in the declaration of a 4957 // constructor or conversion function within its class definition; 4958 // see 12.3.1 and 12.3.2. 4959 if (isExplicit && !NewFD->isInvalidDecl()) { 4960 if (!CurContext->isRecord()) { 4961 // 'explicit' was specified outside of the class. 4962 Diag(D.getDeclSpec().getExplicitSpecLoc(), 4963 diag::err_explicit_out_of_class) 4964 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 4965 } else if (!isa<CXXConstructorDecl>(NewFD) && 4966 !isa<CXXConversionDecl>(NewFD)) { 4967 // 'explicit' was specified on a function that wasn't a constructor 4968 // or conversion function. 4969 Diag(D.getDeclSpec().getExplicitSpecLoc(), 4970 diag::err_explicit_non_ctor_or_conv_function) 4971 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 4972 } 4973 } 4974 4975 if (isConstexpr) { 4976 // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors 4977 // are implicitly inline. 4978 NewFD->setImplicitlyInline(); 4979 4980 // C++0x [dcl.constexpr]p3: functions declared constexpr are required to 4981 // be either constructors or to return a literal type. Therefore, 4982 // destructors cannot be declared constexpr. 4983 if (isa<CXXDestructorDecl>(NewFD)) 4984 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 4985 } 4986 4987 // If __module_private__ was specified, mark the function accordingly. 4988 if (D.getDeclSpec().isModulePrivateSpecified()) { 4989 if (isFunctionTemplateSpecialization) { 4990 SourceLocation ModulePrivateLoc 4991 = D.getDeclSpec().getModulePrivateSpecLoc(); 4992 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 4993 << 0 4994 << FixItHint::CreateRemoval(ModulePrivateLoc); 4995 } else { 4996 NewFD->setModulePrivate(); 4997 if (FunctionTemplate) 4998 FunctionTemplate->setModulePrivate(); 4999 } 5000 } 5001 5002 if (isFriend) { 5003 // For now, claim that the objects have no previous declaration. 5004 if (FunctionTemplate) { 5005 FunctionTemplate->setObjectOfFriendDecl(false); 5006 FunctionTemplate->setAccess(AS_public); 5007 } 5008 NewFD->setObjectOfFriendDecl(false); 5009 NewFD->setAccess(AS_public); 5010 } 5011 5012 // If a function is defined as defaulted or deleted, mark it as such now. 5013 switch (D.getFunctionDefinitionKind()) { 5014 case FDK_Declaration: 5015 case FDK_Definition: 5016 break; 5017 5018 case FDK_Defaulted: 5019 NewFD->setDefaulted(); 5020 break; 5021 5022 case FDK_Deleted: 5023 NewFD->setDeletedAsWritten(); 5024 break; 5025 } 5026 5027 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 5028 D.isFunctionDefinition()) { 5029 // C++ [class.mfct]p2: 5030 // A member function may be defined (8.4) in its class definition, in 5031 // which case it is an inline member function (7.1.2) 5032 NewFD->setImplicitlyInline(); 5033 } 5034 5035 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 5036 !CurContext->isRecord()) { 5037 // C++ [class.static]p1: 5038 // A data or function member of a class may be declared static 5039 // in a class definition, in which case it is a static member of 5040 // the class. 5041 5042 // Complain about the 'static' specifier if it's on an out-of-line 5043 // member function definition. 5044 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5045 diag::err_static_out_of_line) 5046 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5047 } 5048 } 5049 5050 // Filter out previous declarations that don't match the scope. 5051 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(), 5052 isExplicitSpecialization || 5053 isFunctionTemplateSpecialization); 5054 5055 // Handle GNU asm-label extension (encoded as an attribute). 5056 if (Expr *E = (Expr*) D.getAsmLabel()) { 5057 // The parser guarantees this is a string. 5058 StringLiteral *SE = cast<StringLiteral>(E); 5059 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 5060 SE->getString())); 5061 } 5062 5063 // Copy the parameter declarations from the declarator D to the function 5064 // declaration NewFD, if they are available. First scavenge them into Params. 5065 SmallVector<ParmVarDecl*, 16> Params; 5066 if (D.isFunctionDeclarator()) { 5067 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5068 5069 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 5070 // function that takes no arguments, not a function that takes a 5071 // single void argument. 5072 // We let through "const void" here because Sema::GetTypeForDeclarator 5073 // already checks for that case. 5074 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5075 FTI.ArgInfo[0].Param && 5076 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 5077 // Empty arg list, don't push any params. 5078 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param); 5079 5080 // In C++, the empty parameter-type-list must be spelled "void"; a 5081 // typedef of void is not permitted. 5082 if (getLangOptions().CPlusPlus && 5083 Param->getType().getUnqualifiedType() != Context.VoidTy) { 5084 bool IsTypeAlias = false; 5085 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>()) 5086 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl()); 5087 else if (const TemplateSpecializationType *TST = 5088 Param->getType()->getAs<TemplateSpecializationType>()) 5089 IsTypeAlias = TST->isTypeAlias(); 5090 Diag(Param->getLocation(), diag::err_param_typedef_of_void) 5091 << IsTypeAlias; 5092 } 5093 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 5094 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 5095 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 5096 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 5097 Param->setDeclContext(NewFD); 5098 Params.push_back(Param); 5099 5100 if (Param->isInvalidDecl()) 5101 NewFD->setInvalidDecl(); 5102 } 5103 } 5104 5105 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 5106 // When we're declaring a function with a typedef, typeof, etc as in the 5107 // following example, we'll need to synthesize (unnamed) 5108 // parameters for use in the declaration. 5109 // 5110 // @code 5111 // typedef void fn(int); 5112 // fn f; 5113 // @endcode 5114 5115 // Synthesize a parameter for each argument type. 5116 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 5117 AE = FT->arg_type_end(); AI != AE; ++AI) { 5118 ParmVarDecl *Param = 5119 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 5120 Param->setScopeInfo(0, Params.size()); 5121 Params.push_back(Param); 5122 } 5123 } else { 5124 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 5125 "Should not need args for typedef of non-prototype fn"); 5126 } 5127 5128 // Finally, we know we have the right number of parameters, install them. 5129 NewFD->setParams(Params); 5130 5131 // Process the non-inheritable attributes on this declaration. 5132 ProcessDeclAttributes(S, NewFD, D, 5133 /*NonInheritable=*/true, /*Inheritable=*/false); 5134 5135 if (!getLangOptions().CPlusPlus) { 5136 // Perform semantic checking on the function declaration. 5137 bool isExplicitSpecialization=false; 5138 if (!NewFD->isInvalidDecl()) { 5139 if (NewFD->getResultType()->isVariablyModifiedType()) { 5140 // Functions returning a variably modified type violate C99 6.7.5.2p2 5141 // because all functions have linkage. 5142 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 5143 NewFD->setInvalidDecl(); 5144 } else { 5145 if (NewFD->isMain()) 5146 CheckMain(NewFD, D.getDeclSpec()); 5147 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 5148 isExplicitSpecialization)); 5149 } 5150 } 5151 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 5152 Previous.getResultKind() != LookupResult::FoundOverloaded) && 5153 "previous declaration set still overloaded"); 5154 } else { 5155 // If the declarator is a template-id, translate the parser's template 5156 // argument list into our AST format. 5157 bool HasExplicitTemplateArgs = false; 5158 TemplateArgumentListInfo TemplateArgs; 5159 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5160 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 5161 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 5162 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 5163 ASTTemplateArgsPtr TemplateArgsPtr(*this, 5164 TemplateId->getTemplateArgs(), 5165 TemplateId->NumArgs); 5166 translateTemplateArguments(TemplateArgsPtr, 5167 TemplateArgs); 5168 TemplateArgsPtr.release(); 5169 5170 HasExplicitTemplateArgs = true; 5171 5172 if (NewFD->isInvalidDecl()) { 5173 HasExplicitTemplateArgs = false; 5174 } else if (FunctionTemplate) { 5175 // Function template with explicit template arguments. 5176 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 5177 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 5178 5179 HasExplicitTemplateArgs = false; 5180 } else if (!isFunctionTemplateSpecialization && 5181 !D.getDeclSpec().isFriendSpecified()) { 5182 // We have encountered something that the user meant to be a 5183 // specialization (because it has explicitly-specified template 5184 // arguments) but that was not introduced with a "template<>" (or had 5185 // too few of them). 5186 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 5187 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 5188 << FixItHint::CreateInsertion( 5189 D.getDeclSpec().getSourceRange().getBegin(), 5190 "template<> "); 5191 isFunctionTemplateSpecialization = true; 5192 } else { 5193 // "friend void foo<>(int);" is an implicit specialization decl. 5194 isFunctionTemplateSpecialization = true; 5195 } 5196 } else if (isFriend && isFunctionTemplateSpecialization) { 5197 // This combination is only possible in a recovery case; the user 5198 // wrote something like: 5199 // template <> friend void foo(int); 5200 // which we're recovering from as if the user had written: 5201 // friend void foo<>(int); 5202 // Go ahead and fake up a template id. 5203 HasExplicitTemplateArgs = true; 5204 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 5205 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 5206 } 5207 5208 // If it's a friend (and only if it's a friend), it's possible 5209 // that either the specialized function type or the specialized 5210 // template is dependent, and therefore matching will fail. In 5211 // this case, don't check the specialization yet. 5212 bool InstantiationDependent = false; 5213 if (isFunctionTemplateSpecialization && isFriend && 5214 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 5215 TemplateSpecializationType::anyDependentTemplateArguments( 5216 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 5217 InstantiationDependent))) { 5218 assert(HasExplicitTemplateArgs && 5219 "friend function specialization without template args"); 5220 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 5221 Previous)) 5222 NewFD->setInvalidDecl(); 5223 } else if (isFunctionTemplateSpecialization) { 5224 if (CurContext->isDependentContext() && CurContext->isRecord() 5225 && !isFriend) { 5226 isDependentClassScopeExplicitSpecialization = true; 5227 Diag(NewFD->getLocation(), getLangOptions().MicrosoftExt ? 5228 diag::ext_function_specialization_in_class : 5229 diag::err_function_specialization_in_class) 5230 << NewFD->getDeclName(); 5231 } else if (CheckFunctionTemplateSpecialization(NewFD, 5232 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 5233 Previous)) 5234 NewFD->setInvalidDecl(); 5235 5236 // C++ [dcl.stc]p1: 5237 // A storage-class-specifier shall not be specified in an explicit 5238 // specialization (14.7.3) 5239 if (SC != SC_None) { 5240 if (SC != NewFD->getStorageClass()) 5241 Diag(NewFD->getLocation(), 5242 diag::err_explicit_specialization_inconsistent_storage_class) 5243 << SC 5244 << FixItHint::CreateRemoval( 5245 D.getDeclSpec().getStorageClassSpecLoc()); 5246 5247 else 5248 Diag(NewFD->getLocation(), 5249 diag::ext_explicit_specialization_storage_class) 5250 << FixItHint::CreateRemoval( 5251 D.getDeclSpec().getStorageClassSpecLoc()); 5252 } 5253 5254 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 5255 if (CheckMemberSpecialization(NewFD, Previous)) 5256 NewFD->setInvalidDecl(); 5257 } 5258 5259 // Perform semantic checking on the function declaration. 5260 if (!isDependentClassScopeExplicitSpecialization) { 5261 if (NewFD->isInvalidDecl()) { 5262 // If this is a class member, mark the class invalid immediately. 5263 // This avoids some consistency errors later. 5264 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD)) 5265 methodDecl->getParent()->setInvalidDecl(); 5266 } else { 5267 if (NewFD->isMain()) 5268 CheckMain(NewFD, D.getDeclSpec()); 5269 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 5270 isExplicitSpecialization)); 5271 } 5272 } 5273 5274 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 5275 Previous.getResultKind() != LookupResult::FoundOverloaded) && 5276 "previous declaration set still overloaded"); 5277 5278 if (NewFD->isConstexpr() && !NewFD->isInvalidDecl() && 5279 !CheckConstexprFunctionDecl(NewFD, CCK_Declaration)) 5280 NewFD->setInvalidDecl(); 5281 5282 NamedDecl *PrincipalDecl = (FunctionTemplate 5283 ? cast<NamedDecl>(FunctionTemplate) 5284 : NewFD); 5285 5286 if (isFriend && D.isRedeclaration()) { 5287 AccessSpecifier Access = AS_public; 5288 if (!NewFD->isInvalidDecl()) 5289 Access = NewFD->getPreviousDeclaration()->getAccess(); 5290 5291 NewFD->setAccess(Access); 5292 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 5293 5294 PrincipalDecl->setObjectOfFriendDecl(true); 5295 } 5296 5297 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 5298 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 5299 PrincipalDecl->setNonMemberOperator(); 5300 5301 // If we have a function template, check the template parameter 5302 // list. This will check and merge default template arguments. 5303 if (FunctionTemplate) { 5304 FunctionTemplateDecl *PrevTemplate = 5305 FunctionTemplate->getPreviousDeclaration(); 5306 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 5307 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 5308 D.getDeclSpec().isFriendSpecified() 5309 ? (D.isFunctionDefinition() 5310 ? TPC_FriendFunctionTemplateDefinition 5311 : TPC_FriendFunctionTemplate) 5312 : (D.getCXXScopeSpec().isSet() && 5313 DC && DC->isRecord() && 5314 DC->isDependentContext()) 5315 ? TPC_ClassTemplateMember 5316 : TPC_FunctionTemplate); 5317 } 5318 5319 if (NewFD->isInvalidDecl()) { 5320 // Ignore all the rest of this. 5321 } else if (!D.isRedeclaration()) { 5322 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 5323 AddToScope }; 5324 // Fake up an access specifier if it's supposed to be a class member. 5325 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 5326 NewFD->setAccess(AS_public); 5327 5328 // Qualified decls generally require a previous declaration. 5329 if (D.getCXXScopeSpec().isSet()) { 5330 // ...with the major exception of templated-scope or 5331 // dependent-scope friend declarations. 5332 5333 // TODO: we currently also suppress this check in dependent 5334 // contexts because (1) the parameter depth will be off when 5335 // matching friend templates and (2) we might actually be 5336 // selecting a friend based on a dependent factor. But there 5337 // are situations where these conditions don't apply and we 5338 // can actually do this check immediately. 5339 if (isFriend && 5340 (TemplateParamLists.size() || 5341 D.getCXXScopeSpec().getScopeRep()->isDependent() || 5342 CurContext->isDependentContext())) { 5343 // ignore these 5344 } else { 5345 // The user tried to provide an out-of-line definition for a 5346 // function that is a member of a class or namespace, but there 5347 // was no such member function declared (C++ [class.mfct]p2, 5348 // C++ [namespace.memdef]p2). For example: 5349 // 5350 // class X { 5351 // void f() const; 5352 // }; 5353 // 5354 // void X::f() { } // ill-formed 5355 // 5356 // Complain about this problem, and attempt to suggest close 5357 // matches (e.g., those that differ only in cv-qualifiers and 5358 // whether the parameter types are references). 5359 5360 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous, 5361 NewFD, 5362 ExtraArgs)) { 5363 AddToScope = ExtraArgs.AddToScope; 5364 return Result; 5365 } 5366 } 5367 5368 // Unqualified local friend declarations are required to resolve 5369 // to something. 5370 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 5371 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous, 5372 NewFD, 5373 ExtraArgs)) { 5374 AddToScope = ExtraArgs.AddToScope; 5375 return Result; 5376 } 5377 } 5378 5379 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() && 5380 !isFriend && !isFunctionTemplateSpecialization && 5381 !isExplicitSpecialization) { 5382 // An out-of-line member function declaration must also be a 5383 // definition (C++ [dcl.meaning]p1). 5384 // Note that this is not the case for explicit specializations of 5385 // function templates or member functions of class templates, per 5386 // C++ [temp.expl.spec]p2. We also allow these declarations as an 5387 // extension for compatibility with old SWIG code which likes to 5388 // generate them. 5389 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 5390 << D.getCXXScopeSpec().getRange(); 5391 } 5392 } 5393 5394 5395 // Handle attributes. We need to have merged decls when handling attributes 5396 // (for example to check for conflicts, etc). 5397 // FIXME: This needs to happen before we merge declarations. Then, 5398 // let attribute merging cope with attribute conflicts. 5399 ProcessDeclAttributes(S, NewFD, D, 5400 /*NonInheritable=*/false, /*Inheritable=*/true); 5401 5402 // attributes declared post-definition are currently ignored 5403 // FIXME: This should happen during attribute merging 5404 if (D.isRedeclaration() && Previous.isSingleResult()) { 5405 const FunctionDecl *Def; 5406 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl()); 5407 if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) { 5408 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition); 5409 Diag(Def->getLocation(), diag::note_previous_definition); 5410 } 5411 } 5412 5413 AddKnownFunctionAttributes(NewFD); 5414 5415 if (NewFD->hasAttr<OverloadableAttr>() && 5416 !NewFD->getType()->getAs<FunctionProtoType>()) { 5417 Diag(NewFD->getLocation(), 5418 diag::err_attribute_overloadable_no_prototype) 5419 << NewFD; 5420 5421 // Turn this into a variadic function with no parameters. 5422 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 5423 FunctionProtoType::ExtProtoInfo EPI; 5424 EPI.Variadic = true; 5425 EPI.ExtInfo = FT->getExtInfo(); 5426 5427 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI); 5428 NewFD->setType(R); 5429 } 5430 5431 // If there's a #pragma GCC visibility in scope, and this isn't a class 5432 // member, set the visibility of this function. 5433 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord()) 5434 AddPushedVisibilityAttribute(NewFD); 5435 5436 // If there's a #pragma clang arc_cf_code_audited in scope, consider 5437 // marking the function. 5438 AddCFAuditedAttribute(NewFD); 5439 5440 // If this is a locally-scoped extern C function, update the 5441 // map of such names. 5442 if (CurContext->isFunctionOrMethod() && NewFD->isExternC() 5443 && !NewFD->isInvalidDecl()) 5444 RegisterLocallyScopedExternCDecl(NewFD, Previous, S); 5445 5446 // Set this FunctionDecl's range up to the right paren. 5447 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 5448 5449 if (getLangOptions().CPlusPlus) { 5450 if (FunctionTemplate) { 5451 if (NewFD->isInvalidDecl()) 5452 FunctionTemplate->setInvalidDecl(); 5453 return FunctionTemplate; 5454 } 5455 } 5456 5457 MarkUnusedFileScopedDecl(NewFD); 5458 5459 if (getLangOptions().CUDA) 5460 if (IdentifierInfo *II = NewFD->getIdentifier()) 5461 if (!NewFD->isInvalidDecl() && 5462 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5463 if (II->isStr("cudaConfigureCall")) { 5464 if (!R->getAs<FunctionType>()->getResultType()->isScalarType()) 5465 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 5466 5467 Context.setcudaConfigureCallDecl(NewFD); 5468 } 5469 } 5470 5471 // Here we have an function template explicit specialization at class scope. 5472 // The actually specialization will be postponed to template instatiation 5473 // time via the ClassScopeFunctionSpecializationDecl node. 5474 if (isDependentClassScopeExplicitSpecialization) { 5475 ClassScopeFunctionSpecializationDecl *NewSpec = 5476 ClassScopeFunctionSpecializationDecl::Create( 5477 Context, CurContext, SourceLocation(), 5478 cast<CXXMethodDecl>(NewFD)); 5479 CurContext->addDecl(NewSpec); 5480 AddToScope = false; 5481 } 5482 5483 return NewFD; 5484} 5485 5486/// \brief Perform semantic checking of a new function declaration. 5487/// 5488/// Performs semantic analysis of the new function declaration 5489/// NewFD. This routine performs all semantic checking that does not 5490/// require the actual declarator involved in the declaration, and is 5491/// used both for the declaration of functions as they are parsed 5492/// (called via ActOnDeclarator) and for the declaration of functions 5493/// that have been instantiated via C++ template instantiation (called 5494/// via InstantiateDecl). 5495/// 5496/// \param IsExplicitSpecialiation whether this new function declaration is 5497/// an explicit specialization of the previous declaration. 5498/// 5499/// This sets NewFD->isInvalidDecl() to true if there was an error. 5500/// 5501/// Returns true if the function declaration is a redeclaration. 5502bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 5503 LookupResult &Previous, 5504 bool IsExplicitSpecialization) { 5505 assert(!NewFD->getResultType()->isVariablyModifiedType() 5506 && "Variably modified return types are not handled here"); 5507 5508 // Check for a previous declaration of this name. 5509 if (Previous.empty() && NewFD->isExternC()) { 5510 // Since we did not find anything by this name and we're declaring 5511 // an extern "C" function, look for a non-visible extern "C" 5512 // declaration with the same name. 5513 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 5514 = findLocallyScopedExternalDecl(NewFD->getDeclName()); 5515 if (Pos != LocallyScopedExternalDecls.end()) 5516 Previous.addDecl(Pos->second); 5517 } 5518 5519 bool Redeclaration = false; 5520 5521 // Merge or overload the declaration with an existing declaration of 5522 // the same name, if appropriate. 5523 if (!Previous.empty()) { 5524 // Determine whether NewFD is an overload of PrevDecl or 5525 // a declaration that requires merging. If it's an overload, 5526 // there's no more work to do here; we'll just add the new 5527 // function to the scope. 5528 5529 NamedDecl *OldDecl = 0; 5530 if (!AllowOverloadingOfFunction(Previous, Context)) { 5531 Redeclaration = true; 5532 OldDecl = Previous.getFoundDecl(); 5533 } else { 5534 switch (CheckOverload(S, NewFD, Previous, OldDecl, 5535 /*NewIsUsingDecl*/ false)) { 5536 case Ovl_Match: 5537 Redeclaration = true; 5538 break; 5539 5540 case Ovl_NonFunction: 5541 Redeclaration = true; 5542 break; 5543 5544 case Ovl_Overload: 5545 Redeclaration = false; 5546 break; 5547 } 5548 5549 if (!getLangOptions().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 5550 // If a function name is overloadable in C, then every function 5551 // with that name must be marked "overloadable". 5552 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 5553 << Redeclaration << NewFD; 5554 NamedDecl *OverloadedDecl = 0; 5555 if (Redeclaration) 5556 OverloadedDecl = OldDecl; 5557 else if (!Previous.empty()) 5558 OverloadedDecl = Previous.getRepresentativeDecl(); 5559 if (OverloadedDecl) 5560 Diag(OverloadedDecl->getLocation(), 5561 diag::note_attribute_overloadable_prev_overload); 5562 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 5563 Context)); 5564 } 5565 } 5566 5567 if (Redeclaration) { 5568 // NewFD and OldDecl represent declarations that need to be 5569 // merged. 5570 if (MergeFunctionDecl(NewFD, OldDecl)) { 5571 NewFD->setInvalidDecl(); 5572 return Redeclaration; 5573 } 5574 5575 Previous.clear(); 5576 Previous.addDecl(OldDecl); 5577 5578 if (FunctionTemplateDecl *OldTemplateDecl 5579 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 5580 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 5581 FunctionTemplateDecl *NewTemplateDecl 5582 = NewFD->getDescribedFunctionTemplate(); 5583 assert(NewTemplateDecl && "Template/non-template mismatch"); 5584 if (CXXMethodDecl *Method 5585 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 5586 Method->setAccess(OldTemplateDecl->getAccess()); 5587 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 5588 } 5589 5590 // If this is an explicit specialization of a member that is a function 5591 // template, mark it as a member specialization. 5592 if (IsExplicitSpecialization && 5593 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 5594 NewTemplateDecl->setMemberSpecialization(); 5595 assert(OldTemplateDecl->isMemberSpecialization()); 5596 } 5597 5598 if (OldTemplateDecl->isModulePrivate()) 5599 NewTemplateDecl->setModulePrivate(); 5600 5601 } else { 5602 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions 5603 NewFD->setAccess(OldDecl->getAccess()); 5604 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 5605 } 5606 } 5607 } 5608 5609 // Semantic checking for this function declaration (in isolation). 5610 if (getLangOptions().CPlusPlus) { 5611 // C++-specific checks. 5612 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 5613 CheckConstructor(Constructor); 5614 } else if (CXXDestructorDecl *Destructor = 5615 dyn_cast<CXXDestructorDecl>(NewFD)) { 5616 CXXRecordDecl *Record = Destructor->getParent(); 5617 QualType ClassType = Context.getTypeDeclType(Record); 5618 5619 // FIXME: Shouldn't we be able to perform this check even when the class 5620 // type is dependent? Both gcc and edg can handle that. 5621 if (!ClassType->isDependentType()) { 5622 DeclarationName Name 5623 = Context.DeclarationNames.getCXXDestructorName( 5624 Context.getCanonicalType(ClassType)); 5625 if (NewFD->getDeclName() != Name) { 5626 Diag(NewFD->getLocation(), diag::err_destructor_name); 5627 NewFD->setInvalidDecl(); 5628 return Redeclaration; 5629 } 5630 } 5631 } else if (CXXConversionDecl *Conversion 5632 = dyn_cast<CXXConversionDecl>(NewFD)) { 5633 ActOnConversionDeclarator(Conversion); 5634 } 5635 5636 // Find any virtual functions that this function overrides. 5637 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 5638 if (!Method->isFunctionTemplateSpecialization() && 5639 !Method->getDescribedFunctionTemplate()) { 5640 if (AddOverriddenMethods(Method->getParent(), Method)) { 5641 // If the function was marked as "static", we have a problem. 5642 if (NewFD->getStorageClass() == SC_Static) { 5643 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual) 5644 << NewFD->getDeclName(); 5645 for (CXXMethodDecl::method_iterator 5646 Overridden = Method->begin_overridden_methods(), 5647 OverriddenEnd = Method->end_overridden_methods(); 5648 Overridden != OverriddenEnd; 5649 ++Overridden) { 5650 Diag((*Overridden)->getLocation(), 5651 diag::note_overridden_virtual_function); 5652 } 5653 } 5654 } 5655 } 5656 } 5657 5658 // Extra checking for C++ overloaded operators (C++ [over.oper]). 5659 if (NewFD->isOverloadedOperator() && 5660 CheckOverloadedOperatorDeclaration(NewFD)) { 5661 NewFD->setInvalidDecl(); 5662 return Redeclaration; 5663 } 5664 5665 // Extra checking for C++0x literal operators (C++0x [over.literal]). 5666 if (NewFD->getLiteralIdentifier() && 5667 CheckLiteralOperatorDeclaration(NewFD)) { 5668 NewFD->setInvalidDecl(); 5669 return Redeclaration; 5670 } 5671 5672 // In C++, check default arguments now that we have merged decls. Unless 5673 // the lexical context is the class, because in this case this is done 5674 // during delayed parsing anyway. 5675 if (!CurContext->isRecord()) 5676 CheckCXXDefaultArguments(NewFD); 5677 5678 // If this function declares a builtin function, check the type of this 5679 // declaration against the expected type for the builtin. 5680 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 5681 ASTContext::GetBuiltinTypeError Error; 5682 QualType T = Context.GetBuiltinType(BuiltinID, Error); 5683 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 5684 // The type of this function differs from the type of the builtin, 5685 // so forget about the builtin entirely. 5686 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 5687 } 5688 } 5689 } 5690 return Redeclaration; 5691} 5692 5693void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 5694 // C++ [basic.start.main]p3: A program that declares main to be inline 5695 // or static is ill-formed. 5696 // C99 6.7.4p4: In a hosted environment, the inline function specifier 5697 // shall not appear in a declaration of main. 5698 // static main is not an error under C99, but we should warn about it. 5699 if (FD->getStorageClass() == SC_Static) 5700 Diag(DS.getStorageClassSpecLoc(), getLangOptions().CPlusPlus 5701 ? diag::err_static_main : diag::warn_static_main) 5702 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5703 if (FD->isInlineSpecified()) 5704 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 5705 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 5706 5707 QualType T = FD->getType(); 5708 assert(T->isFunctionType() && "function decl is not of function type"); 5709 const FunctionType* FT = T->getAs<FunctionType>(); 5710 5711 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 5712 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 5713 FD->setInvalidDecl(true); 5714 } 5715 5716 // Treat protoless main() as nullary. 5717 if (isa<FunctionNoProtoType>(FT)) return; 5718 5719 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 5720 unsigned nparams = FTP->getNumArgs(); 5721 assert(FD->getNumParams() == nparams); 5722 5723 bool HasExtraParameters = (nparams > 3); 5724 5725 // Darwin passes an undocumented fourth argument of type char**. If 5726 // other platforms start sprouting these, the logic below will start 5727 // getting shifty. 5728 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 5729 HasExtraParameters = false; 5730 5731 if (HasExtraParameters) { 5732 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 5733 FD->setInvalidDecl(true); 5734 nparams = 3; 5735 } 5736 5737 // FIXME: a lot of the following diagnostics would be improved 5738 // if we had some location information about types. 5739 5740 QualType CharPP = 5741 Context.getPointerType(Context.getPointerType(Context.CharTy)); 5742 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 5743 5744 for (unsigned i = 0; i < nparams; ++i) { 5745 QualType AT = FTP->getArgType(i); 5746 5747 bool mismatch = true; 5748 5749 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 5750 mismatch = false; 5751 else if (Expected[i] == CharPP) { 5752 // As an extension, the following forms are okay: 5753 // char const ** 5754 // char const * const * 5755 // char * const * 5756 5757 QualifierCollector qs; 5758 const PointerType* PT; 5759 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 5760 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 5761 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) { 5762 qs.removeConst(); 5763 mismatch = !qs.empty(); 5764 } 5765 } 5766 5767 if (mismatch) { 5768 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 5769 // TODO: suggest replacing given type with expected type 5770 FD->setInvalidDecl(true); 5771 } 5772 } 5773 5774 if (nparams == 1 && !FD->isInvalidDecl()) { 5775 Diag(FD->getLocation(), diag::warn_main_one_arg); 5776 } 5777 5778 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 5779 Diag(FD->getLocation(), diag::err_main_template_decl); 5780 FD->setInvalidDecl(); 5781 } 5782} 5783 5784bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 5785 // FIXME: Need strict checking. In C89, we need to check for 5786 // any assignment, increment, decrement, function-calls, or 5787 // commas outside of a sizeof. In C99, it's the same list, 5788 // except that the aforementioned are allowed in unevaluated 5789 // expressions. Everything else falls under the 5790 // "may accept other forms of constant expressions" exception. 5791 // (We never end up here for C++, so the constant expression 5792 // rules there don't matter.) 5793 if (Init->isConstantInitializer(Context, false)) 5794 return false; 5795 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 5796 << Init->getSourceRange(); 5797 return true; 5798} 5799 5800namespace { 5801 // Visits an initialization expression to see if OrigDecl is evaluated in 5802 // its own initialization and throws a warning if it does. 5803 class SelfReferenceChecker 5804 : public EvaluatedExprVisitor<SelfReferenceChecker> { 5805 Sema &S; 5806 Decl *OrigDecl; 5807 bool isRecordType; 5808 bool isPODType; 5809 5810 public: 5811 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 5812 5813 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 5814 S(S), OrigDecl(OrigDecl) { 5815 isPODType = false; 5816 isRecordType = false; 5817 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 5818 isPODType = VD->getType().isPODType(S.Context); 5819 isRecordType = VD->getType()->isRecordType(); 5820 } 5821 } 5822 5823 void VisitExpr(Expr *E) { 5824 if (isa<ObjCMessageExpr>(*E)) return; 5825 if (isRecordType) { 5826 Expr *expr = E; 5827 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 5828 ValueDecl *VD = ME->getMemberDecl(); 5829 if (isa<EnumConstantDecl>(VD) || isa<VarDecl>(VD)) return; 5830 expr = ME->getBase(); 5831 } 5832 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(expr)) { 5833 HandleDeclRefExpr(DRE); 5834 return; 5835 } 5836 } 5837 Inherited::VisitExpr(E); 5838 } 5839 5840 void VisitMemberExpr(MemberExpr *E) { 5841 if (E->getType()->canDecayToPointerType()) return; 5842 if (isa<FieldDecl>(E->getMemberDecl())) 5843 if (DeclRefExpr *DRE 5844 = dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts())) { 5845 HandleDeclRefExpr(DRE); 5846 return; 5847 } 5848 Inherited::VisitMemberExpr(E); 5849 } 5850 5851 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 5852 if ((!isRecordType &&E->getCastKind() == CK_LValueToRValue) || 5853 (isRecordType && E->getCastKind() == CK_NoOp)) { 5854 Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts(); 5855 if (MemberExpr *ME = dyn_cast<MemberExpr>(SubExpr)) 5856 SubExpr = ME->getBase()->IgnoreParenImpCasts(); 5857 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) { 5858 HandleDeclRefExpr(DRE); 5859 return; 5860 } 5861 } 5862 Inherited::VisitImplicitCastExpr(E); 5863 } 5864 5865 void VisitUnaryOperator(UnaryOperator *E) { 5866 // For POD record types, addresses of its own members are well-defined. 5867 if (isRecordType && isPODType) return; 5868 Inherited::VisitUnaryOperator(E); 5869 } 5870 5871 void HandleDeclRefExpr(DeclRefExpr *DRE) { 5872 Decl* ReferenceDecl = DRE->getDecl(); 5873 if (OrigDecl != ReferenceDecl) return; 5874 LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName, 5875 Sema::NotForRedeclaration); 5876 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 5877 S.PDiag(diag::warn_uninit_self_reference_in_init) 5878 << Result.getLookupName() 5879 << OrigDecl->getLocation() 5880 << DRE->getSourceRange()); 5881 } 5882 }; 5883} 5884 5885/// CheckSelfReference - Warns if OrigDecl is used in expression E. 5886void Sema::CheckSelfReference(Decl* OrigDecl, Expr *E) { 5887 SelfReferenceChecker(*this, OrigDecl).VisitExpr(E); 5888} 5889 5890/// AddInitializerToDecl - Adds the initializer Init to the 5891/// declaration dcl. If DirectInit is true, this is C++ direct 5892/// initialization rather than copy initialization. 5893void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 5894 bool DirectInit, bool TypeMayContainAuto) { 5895 // If there is no declaration, there was an error parsing it. Just ignore 5896 // the initializer. 5897 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 5898 return; 5899 5900 // Check for self-references within variable initializers. 5901 if (VarDecl *vd = dyn_cast<VarDecl>(RealDecl)) { 5902 // Variables declared within a function/method body are handled 5903 // by a dataflow analysis. 5904 if (!vd->hasLocalStorage() && !vd->isStaticLocal()) 5905 CheckSelfReference(RealDecl, Init); 5906 } 5907 else { 5908 CheckSelfReference(RealDecl, Init); 5909 } 5910 5911 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 5912 // With declarators parsed the way they are, the parser cannot 5913 // distinguish between a normal initializer and a pure-specifier. 5914 // Thus this grotesque test. 5915 IntegerLiteral *IL; 5916 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 5917 Context.getCanonicalType(IL->getType()) == Context.IntTy) 5918 CheckPureMethod(Method, Init->getSourceRange()); 5919 else { 5920 Diag(Method->getLocation(), diag::err_member_function_initialization) 5921 << Method->getDeclName() << Init->getSourceRange(); 5922 Method->setInvalidDecl(); 5923 } 5924 return; 5925 } 5926 5927 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 5928 if (!VDecl) { 5929 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 5930 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 5931 RealDecl->setInvalidDecl(); 5932 return; 5933 } 5934 5935 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 5936 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) { 5937 TypeSourceInfo *DeducedType = 0; 5938 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType)) 5939 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure) 5940 << VDecl->getDeclName() << VDecl->getType() << Init->getType() 5941 << Init->getSourceRange(); 5942 if (!DeducedType) { 5943 RealDecl->setInvalidDecl(); 5944 return; 5945 } 5946 VDecl->setTypeSourceInfo(DeducedType); 5947 VDecl->setType(DeducedType->getType()); 5948 5949 // In ARC, infer lifetime. 5950 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 5951 VDecl->setInvalidDecl(); 5952 5953 // If this is a redeclaration, check that the type we just deduced matches 5954 // the previously declared type. 5955 if (VarDecl *Old = VDecl->getPreviousDeclaration()) 5956 MergeVarDeclTypes(VDecl, Old); 5957 } 5958 5959 5960 // A definition must end up with a complete type, which means it must be 5961 // complete with the restriction that an array type might be completed by the 5962 // initializer; note that later code assumes this restriction. 5963 QualType BaseDeclType = VDecl->getType(); 5964 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 5965 BaseDeclType = Array->getElementType(); 5966 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 5967 diag::err_typecheck_decl_incomplete_type)) { 5968 RealDecl->setInvalidDecl(); 5969 return; 5970 } 5971 5972 // The variable can not have an abstract class type. 5973 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 5974 diag::err_abstract_type_in_decl, 5975 AbstractVariableType)) 5976 VDecl->setInvalidDecl(); 5977 5978 const VarDecl *Def; 5979 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 5980 Diag(VDecl->getLocation(), diag::err_redefinition) 5981 << VDecl->getDeclName(); 5982 Diag(Def->getLocation(), diag::note_previous_definition); 5983 VDecl->setInvalidDecl(); 5984 return; 5985 } 5986 5987 const VarDecl* PrevInit = 0; 5988 if (getLangOptions().CPlusPlus) { 5989 // C++ [class.static.data]p4 5990 // If a static data member is of const integral or const 5991 // enumeration type, its declaration in the class definition can 5992 // specify a constant-initializer which shall be an integral 5993 // constant expression (5.19). In that case, the member can appear 5994 // in integral constant expressions. The member shall still be 5995 // defined in a namespace scope if it is used in the program and the 5996 // namespace scope definition shall not contain an initializer. 5997 // 5998 // We already performed a redefinition check above, but for static 5999 // data members we also need to check whether there was an in-class 6000 // declaration with an initializer. 6001 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 6002 Diag(VDecl->getLocation(), diag::err_redefinition) 6003 << VDecl->getDeclName(); 6004 Diag(PrevInit->getLocation(), diag::note_previous_definition); 6005 return; 6006 } 6007 6008 if (VDecl->hasLocalStorage()) 6009 getCurFunction()->setHasBranchProtectedScope(); 6010 6011 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 6012 VDecl->setInvalidDecl(); 6013 return; 6014 } 6015 } 6016 6017 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 6018 // a kernel function cannot be initialized." 6019 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 6020 Diag(VDecl->getLocation(), diag::err_local_cant_init); 6021 VDecl->setInvalidDecl(); 6022 return; 6023 } 6024 6025 // Capture the variable that is being initialized and the style of 6026 // initialization. 6027 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 6028 6029 // FIXME: Poor source location information. 6030 InitializationKind Kind 6031 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(), 6032 Init->getLocStart(), 6033 Init->getLocEnd()) 6034 : InitializationKind::CreateCopy(VDecl->getLocation(), 6035 Init->getLocStart()); 6036 6037 // Get the decls type and save a reference for later, since 6038 // CheckInitializerTypes may change it. 6039 QualType DclT = VDecl->getType(), SavT = DclT; 6040 if (VDecl->isLocalVarDecl()) { 6041 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5 6042 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 6043 VDecl->setInvalidDecl(); 6044 } else if (!VDecl->isInvalidDecl()) { 6045 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 6046 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 6047 MultiExprArg(*this, &Init, 1), 6048 &DclT); 6049 if (Result.isInvalid()) { 6050 VDecl->setInvalidDecl(); 6051 return; 6052 } 6053 6054 Init = Result.takeAs<Expr>(); 6055 6056 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 6057 // Don't check invalid declarations to avoid emitting useless diagnostics. 6058 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 6059 if (VDecl->getStorageClass() == SC_Static) // C99 6.7.8p4. 6060 CheckForConstantInitializer(Init, DclT); 6061 } 6062 } 6063 } else if (VDecl->isStaticDataMember() && 6064 VDecl->getLexicalDeclContext()->isRecord()) { 6065 // This is an in-class initialization for a static data member, e.g., 6066 // 6067 // struct S { 6068 // static const int value = 17; 6069 // }; 6070 6071 // Try to perform the initialization regardless. 6072 if (!VDecl->isInvalidDecl()) { 6073 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 6074 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 6075 MultiExprArg(*this, &Init, 1), 6076 &DclT); 6077 if (Result.isInvalid()) { 6078 VDecl->setInvalidDecl(); 6079 return; 6080 } 6081 6082 Init = Result.takeAs<Expr>(); 6083 } 6084 6085 // C++ [class.mem]p4: 6086 // A member-declarator can contain a constant-initializer only 6087 // if it declares a static member (9.4) of const integral or 6088 // const enumeration type, see 9.4.2. 6089 // 6090 // C++0x [class.static.data]p3: 6091 // If a non-volatile const static data member is of integral or 6092 // enumeration type, its declaration in the class definition can 6093 // specify a brace-or-equal-initializer in which every initalizer-clause 6094 // that is an assignment-expression is a constant expression. A static 6095 // data member of literal type can be declared in the class definition 6096 // with the constexpr specifier; if so, its declaration shall specify a 6097 // brace-or-equal-initializer in which every initializer-clause that is 6098 // an assignment-expression is a constant expression. 6099 QualType T = VDecl->getType(); 6100 6101 // Do nothing on dependent types. 6102 if (T->isDependentType()) { 6103 6104 // Allow any 'static constexpr' members, whether or not they are of literal 6105 // type. We separately check that the initializer is a constant expression, 6106 // which implicitly requires the member to be of literal type. 6107 } else if (VDecl->isConstexpr()) { 6108 6109 // Require constness. 6110 } else if (!T.isConstQualified()) { 6111 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 6112 << Init->getSourceRange(); 6113 VDecl->setInvalidDecl(); 6114 6115 // We allow integer constant expressions in all cases. 6116 } else if (T->isIntegralOrEnumerationType()) { 6117 // Check whether the expression is a constant expression. 6118 SourceLocation Loc; 6119 if (getLangOptions().CPlusPlus0x && T.isVolatileQualified()) 6120 // In C++0x, a non-constexpr const static data member with an 6121 // in-class initializer cannot be volatile. 6122 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 6123 else if (Init->isValueDependent()) 6124 ; // Nothing to check. 6125 else if (Init->isIntegerConstantExpr(Context, &Loc)) 6126 ; // Ok, it's an ICE! 6127 else if (Init->isEvaluatable(Context)) { 6128 // If we can constant fold the initializer through heroics, accept it, 6129 // but report this as a use of an extension for -pedantic. 6130 Diag(Loc, diag::ext_in_class_initializer_non_constant) 6131 << Init->getSourceRange(); 6132 } else { 6133 // Otherwise, this is some crazy unknown case. Report the issue at the 6134 // location provided by the isIntegerConstantExpr failed check. 6135 Diag(Loc, diag::err_in_class_initializer_non_constant) 6136 << Init->getSourceRange(); 6137 VDecl->setInvalidDecl(); 6138 } 6139 6140 // We allow floating-point constants as an extension. 6141 } else if (T->isFloatingType()) { // also permits complex, which is ok 6142 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 6143 << T << Init->getSourceRange(); 6144 if (getLangOptions().CPlusPlus0x) 6145 Diag(VDecl->getLocation(), 6146 diag::note_in_class_initializer_float_type_constexpr) 6147 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 6148 6149 if (!Init->isValueDependent() && 6150 !Init->isConstantInitializer(Context, false)) { 6151 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 6152 << Init->getSourceRange(); 6153 VDecl->setInvalidDecl(); 6154 } 6155 6156 // Suggest adding 'constexpr' in C++0x for literal types. 6157 } else if (getLangOptions().CPlusPlus0x && T->isLiteralType()) { 6158 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 6159 << T << Init->getSourceRange() 6160 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 6161 VDecl->setConstexpr(true); 6162 6163 } else { 6164 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 6165 << T << Init->getSourceRange(); 6166 VDecl->setInvalidDecl(); 6167 } 6168 } else if (VDecl->isFileVarDecl()) { 6169 if (VDecl->getStorageClassAsWritten() == SC_Extern && 6170 (!getLangOptions().CPlusPlus || 6171 !Context.getBaseElementType(VDecl->getType()).isConstQualified())) 6172 Diag(VDecl->getLocation(), diag::warn_extern_init); 6173 if (!VDecl->isInvalidDecl()) { 6174 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 6175 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 6176 MultiExprArg(*this, &Init, 1), 6177 &DclT); 6178 if (Result.isInvalid()) { 6179 VDecl->setInvalidDecl(); 6180 return; 6181 } 6182 6183 Init = Result.takeAs<Expr>(); 6184 } 6185 6186 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 6187 // Don't check invalid declarations to avoid emitting useless diagnostics. 6188 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 6189 // C99 6.7.8p4. All file scoped initializers need to be constant. 6190 CheckForConstantInitializer(Init, DclT); 6191 } 6192 } 6193 // If the type changed, it means we had an incomplete type that was 6194 // completed by the initializer. For example: 6195 // int ary[] = { 1, 3, 5 }; 6196 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 6197 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 6198 VDecl->setType(DclT); 6199 Init->setType(DclT.getNonReferenceType()); 6200 } 6201 6202 // Check any implicit conversions within the expression. 6203 CheckImplicitConversions(Init, VDecl->getLocation()); 6204 6205 if (!VDecl->isInvalidDecl()) 6206 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 6207 6208 Init = MaybeCreateExprWithCleanups(Init); 6209 // Attach the initializer to the decl. 6210 VDecl->setInit(Init); 6211 6212 CheckCompleteVariableDeclaration(VDecl); 6213} 6214 6215/// ActOnInitializerError - Given that there was an error parsing an 6216/// initializer for the given declaration, try to return to some form 6217/// of sanity. 6218void Sema::ActOnInitializerError(Decl *D) { 6219 // Our main concern here is re-establishing invariants like "a 6220 // variable's type is either dependent or complete". 6221 if (!D || D->isInvalidDecl()) return; 6222 6223 VarDecl *VD = dyn_cast<VarDecl>(D); 6224 if (!VD) return; 6225 6226 // Auto types are meaningless if we can't make sense of the initializer. 6227 if (ParsingInitForAutoVars.count(D)) { 6228 D->setInvalidDecl(); 6229 return; 6230 } 6231 6232 QualType Ty = VD->getType(); 6233 if (Ty->isDependentType()) return; 6234 6235 // Require a complete type. 6236 if (RequireCompleteType(VD->getLocation(), 6237 Context.getBaseElementType(Ty), 6238 diag::err_typecheck_decl_incomplete_type)) { 6239 VD->setInvalidDecl(); 6240 return; 6241 } 6242 6243 // Require an abstract type. 6244 if (RequireNonAbstractType(VD->getLocation(), Ty, 6245 diag::err_abstract_type_in_decl, 6246 AbstractVariableType)) { 6247 VD->setInvalidDecl(); 6248 return; 6249 } 6250 6251 // Don't bother complaining about constructors or destructors, 6252 // though. 6253} 6254 6255void Sema::ActOnUninitializedDecl(Decl *RealDecl, 6256 bool TypeMayContainAuto) { 6257 // If there is no declaration, there was an error parsing it. Just ignore it. 6258 if (RealDecl == 0) 6259 return; 6260 6261 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 6262 QualType Type = Var->getType(); 6263 6264 // C++0x [dcl.spec.auto]p3 6265 if (TypeMayContainAuto && Type->getContainedAutoType()) { 6266 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 6267 << Var->getDeclName() << Type; 6268 Var->setInvalidDecl(); 6269 return; 6270 } 6271 6272 // C++0x [class.static.data]p3: A static data member can be declared with 6273 // the constexpr specifier; if so, its declaration shall specify 6274 // a brace-or-equal-initializer. 6275 if (Var->isConstexpr() && Var->isStaticDataMember() && 6276 !Var->isThisDeclarationADefinition()) { 6277 Diag(Var->getLocation(), diag::err_constexpr_static_mem_var_requires_init) 6278 << Var->getDeclName(); 6279 Var->setInvalidDecl(); 6280 return; 6281 } 6282 6283 switch (Var->isThisDeclarationADefinition()) { 6284 case VarDecl::Definition: 6285 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 6286 break; 6287 6288 // We have an out-of-line definition of a static data member 6289 // that has an in-class initializer, so we type-check this like 6290 // a declaration. 6291 // 6292 // Fall through 6293 6294 case VarDecl::DeclarationOnly: 6295 // It's only a declaration. 6296 6297 // Block scope. C99 6.7p7: If an identifier for an object is 6298 // declared with no linkage (C99 6.2.2p6), the type for the 6299 // object shall be complete. 6300 if (!Type->isDependentType() && Var->isLocalVarDecl() && 6301 !Var->getLinkage() && !Var->isInvalidDecl() && 6302 RequireCompleteType(Var->getLocation(), Type, 6303 diag::err_typecheck_decl_incomplete_type)) 6304 Var->setInvalidDecl(); 6305 6306 // Make sure that the type is not abstract. 6307 if (!Type->isDependentType() && !Var->isInvalidDecl() && 6308 RequireNonAbstractType(Var->getLocation(), Type, 6309 diag::err_abstract_type_in_decl, 6310 AbstractVariableType)) 6311 Var->setInvalidDecl(); 6312 return; 6313 6314 case VarDecl::TentativeDefinition: 6315 // File scope. C99 6.9.2p2: A declaration of an identifier for an 6316 // object that has file scope without an initializer, and without a 6317 // storage-class specifier or with the storage-class specifier "static", 6318 // constitutes a tentative definition. Note: A tentative definition with 6319 // external linkage is valid (C99 6.2.2p5). 6320 if (!Var->isInvalidDecl()) { 6321 if (const IncompleteArrayType *ArrayT 6322 = Context.getAsIncompleteArrayType(Type)) { 6323 if (RequireCompleteType(Var->getLocation(), 6324 ArrayT->getElementType(), 6325 diag::err_illegal_decl_array_incomplete_type)) 6326 Var->setInvalidDecl(); 6327 } else if (Var->getStorageClass() == SC_Static) { 6328 // C99 6.9.2p3: If the declaration of an identifier for an object is 6329 // a tentative definition and has internal linkage (C99 6.2.2p3), the 6330 // declared type shall not be an incomplete type. 6331 // NOTE: code such as the following 6332 // static struct s; 6333 // struct s { int a; }; 6334 // is accepted by gcc. Hence here we issue a warning instead of 6335 // an error and we do not invalidate the static declaration. 6336 // NOTE: to avoid multiple warnings, only check the first declaration. 6337 if (Var->getPreviousDeclaration() == 0) 6338 RequireCompleteType(Var->getLocation(), Type, 6339 diag::ext_typecheck_decl_incomplete_type); 6340 } 6341 } 6342 6343 // Record the tentative definition; we're done. 6344 if (!Var->isInvalidDecl()) 6345 TentativeDefinitions.push_back(Var); 6346 return; 6347 } 6348 6349 // Provide a specific diagnostic for uninitialized variable 6350 // definitions with incomplete array type. 6351 if (Type->isIncompleteArrayType()) { 6352 Diag(Var->getLocation(), 6353 diag::err_typecheck_incomplete_array_needs_initializer); 6354 Var->setInvalidDecl(); 6355 return; 6356 } 6357 6358 // Provide a specific diagnostic for uninitialized variable 6359 // definitions with reference type. 6360 if (Type->isReferenceType()) { 6361 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 6362 << Var->getDeclName() 6363 << SourceRange(Var->getLocation(), Var->getLocation()); 6364 Var->setInvalidDecl(); 6365 return; 6366 } 6367 6368 // Do not attempt to type-check the default initializer for a 6369 // variable with dependent type. 6370 if (Type->isDependentType()) 6371 return; 6372 6373 if (Var->isInvalidDecl()) 6374 return; 6375 6376 if (RequireCompleteType(Var->getLocation(), 6377 Context.getBaseElementType(Type), 6378 diag::err_typecheck_decl_incomplete_type)) { 6379 Var->setInvalidDecl(); 6380 return; 6381 } 6382 6383 // The variable can not have an abstract class type. 6384 if (RequireNonAbstractType(Var->getLocation(), Type, 6385 diag::err_abstract_type_in_decl, 6386 AbstractVariableType)) { 6387 Var->setInvalidDecl(); 6388 return; 6389 } 6390 6391 // Check for jumps past the implicit initializer. C++0x 6392 // clarifies that this applies to a "variable with automatic 6393 // storage duration", not a "local variable". 6394 // C++11 [stmt.dcl]p3 6395 // A program that jumps from a point where a variable with automatic 6396 // storage duration is not in scope to a point where it is in scope is 6397 // ill-formed unless the variable has scalar type, class type with a 6398 // trivial default constructor and a trivial destructor, a cv-qualified 6399 // version of one of these types, or an array of one of the preceding 6400 // types and is declared without an initializer. 6401 if (getLangOptions().CPlusPlus && Var->hasLocalStorage()) { 6402 if (const RecordType *Record 6403 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 6404 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 6405 // Mark the function for further checking even if the looser rules of 6406 // C++11 do not require such checks, so that we can diagnose 6407 // incompatibilities with C++98. 6408 if (!CXXRecord->isPOD()) 6409 getCurFunction()->setHasBranchProtectedScope(); 6410 } 6411 } 6412 6413 // C++03 [dcl.init]p9: 6414 // If no initializer is specified for an object, and the 6415 // object is of (possibly cv-qualified) non-POD class type (or 6416 // array thereof), the object shall be default-initialized; if 6417 // the object is of const-qualified type, the underlying class 6418 // type shall have a user-declared default 6419 // constructor. Otherwise, if no initializer is specified for 6420 // a non- static object, the object and its subobjects, if 6421 // any, have an indeterminate initial value); if the object 6422 // or any of its subobjects are of const-qualified type, the 6423 // program is ill-formed. 6424 // C++0x [dcl.init]p11: 6425 // If no initializer is specified for an object, the object is 6426 // default-initialized; [...]. 6427 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 6428 InitializationKind Kind 6429 = InitializationKind::CreateDefault(Var->getLocation()); 6430 6431 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0); 6432 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, 6433 MultiExprArg(*this, 0, 0)); 6434 if (Init.isInvalid()) 6435 Var->setInvalidDecl(); 6436 else if (Init.get()) 6437 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 6438 6439 CheckCompleteVariableDeclaration(Var); 6440 } 6441} 6442 6443void Sema::ActOnCXXForRangeDecl(Decl *D) { 6444 VarDecl *VD = dyn_cast<VarDecl>(D); 6445 if (!VD) { 6446 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 6447 D->setInvalidDecl(); 6448 return; 6449 } 6450 6451 VD->setCXXForRangeDecl(true); 6452 6453 // for-range-declaration cannot be given a storage class specifier. 6454 int Error = -1; 6455 switch (VD->getStorageClassAsWritten()) { 6456 case SC_None: 6457 break; 6458 case SC_Extern: 6459 Error = 0; 6460 break; 6461 case SC_Static: 6462 Error = 1; 6463 break; 6464 case SC_PrivateExtern: 6465 Error = 2; 6466 break; 6467 case SC_Auto: 6468 Error = 3; 6469 break; 6470 case SC_Register: 6471 Error = 4; 6472 break; 6473 case SC_OpenCLWorkGroupLocal: 6474 llvm_unreachable("Unexpected storage class"); 6475 } 6476 if (VD->isConstexpr()) 6477 Error = 5; 6478 if (Error != -1) { 6479 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 6480 << VD->getDeclName() << Error; 6481 D->setInvalidDecl(); 6482 } 6483} 6484 6485void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 6486 if (var->isInvalidDecl()) return; 6487 6488 // In ARC, don't allow jumps past the implicit initialization of a 6489 // local retaining variable. 6490 if (getLangOptions().ObjCAutoRefCount && 6491 var->hasLocalStorage()) { 6492 switch (var->getType().getObjCLifetime()) { 6493 case Qualifiers::OCL_None: 6494 case Qualifiers::OCL_ExplicitNone: 6495 case Qualifiers::OCL_Autoreleasing: 6496 break; 6497 6498 case Qualifiers::OCL_Weak: 6499 case Qualifiers::OCL_Strong: 6500 getCurFunction()->setHasBranchProtectedScope(); 6501 break; 6502 } 6503 } 6504 6505 // All the following checks are C++ only. 6506 if (!getLangOptions().CPlusPlus) return; 6507 6508 QualType baseType = Context.getBaseElementType(var->getType()); 6509 if (baseType->isDependentType()) return; 6510 6511 // __block variables might require us to capture a copy-initializer. 6512 if (var->hasAttr<BlocksAttr>()) { 6513 // It's currently invalid to ever have a __block variable with an 6514 // array type; should we diagnose that here? 6515 6516 // Regardless, we don't want to ignore array nesting when 6517 // constructing this copy. 6518 QualType type = var->getType(); 6519 6520 if (type->isStructureOrClassType()) { 6521 SourceLocation poi = var->getLocation(); 6522 Expr *varRef = new (Context) DeclRefExpr(var, type, VK_LValue, poi); 6523 ExprResult result = 6524 PerformCopyInitialization( 6525 InitializedEntity::InitializeBlock(poi, type, false), 6526 poi, Owned(varRef)); 6527 if (!result.isInvalid()) { 6528 result = MaybeCreateExprWithCleanups(result); 6529 Expr *init = result.takeAs<Expr>(); 6530 Context.setBlockVarCopyInits(var, init); 6531 } 6532 } 6533 } 6534 6535 Expr *Init = var->getInit(); 6536 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 6537 6538 if (!var->getDeclContext()->isDependentContext() && 6539 (var->isConstexpr() || IsGlobal) && Init && 6540 !Init->isConstantInitializer(Context, baseType->isReferenceType())) { 6541 // FIXME: Improve this diagnostic to explain why the initializer is not 6542 // a constant expression. 6543 if (var->isConstexpr()) 6544 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init) 6545 << var << Init->getSourceRange(); 6546 if (IsGlobal) 6547 Diag(var->getLocation(), diag::warn_global_constructor) 6548 << Init->getSourceRange(); 6549 } 6550 6551 // Require the destructor. 6552 if (const RecordType *recordType = baseType->getAs<RecordType>()) 6553 FinalizeVarWithDestructor(var, recordType); 6554} 6555 6556/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 6557/// any semantic actions necessary after any initializer has been attached. 6558void 6559Sema::FinalizeDeclaration(Decl *ThisDecl) { 6560 // Note that we are no longer parsing the initializer for this declaration. 6561 ParsingInitForAutoVars.erase(ThisDecl); 6562} 6563 6564Sema::DeclGroupPtrTy 6565Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 6566 Decl **Group, unsigned NumDecls) { 6567 SmallVector<Decl*, 8> Decls; 6568 6569 if (DS.isTypeSpecOwned()) 6570 Decls.push_back(DS.getRepAsDecl()); 6571 6572 for (unsigned i = 0; i != NumDecls; ++i) 6573 if (Decl *D = Group[i]) 6574 Decls.push_back(D); 6575 6576 return BuildDeclaratorGroup(Decls.data(), Decls.size(), 6577 DS.getTypeSpecType() == DeclSpec::TST_auto); 6578} 6579 6580/// BuildDeclaratorGroup - convert a list of declarations into a declaration 6581/// group, performing any necessary semantic checking. 6582Sema::DeclGroupPtrTy 6583Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls, 6584 bool TypeMayContainAuto) { 6585 // C++0x [dcl.spec.auto]p7: 6586 // If the type deduced for the template parameter U is not the same in each 6587 // deduction, the program is ill-formed. 6588 // FIXME: When initializer-list support is added, a distinction is needed 6589 // between the deduced type U and the deduced type which 'auto' stands for. 6590 // auto a = 0, b = { 1, 2, 3 }; 6591 // is legal because the deduced type U is 'int' in both cases. 6592 if (TypeMayContainAuto && NumDecls > 1) { 6593 QualType Deduced; 6594 CanQualType DeducedCanon; 6595 VarDecl *DeducedDecl = 0; 6596 for (unsigned i = 0; i != NumDecls; ++i) { 6597 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 6598 AutoType *AT = D->getType()->getContainedAutoType(); 6599 // Don't reissue diagnostics when instantiating a template. 6600 if (AT && D->isInvalidDecl()) 6601 break; 6602 if (AT && AT->isDeduced()) { 6603 QualType U = AT->getDeducedType(); 6604 CanQualType UCanon = Context.getCanonicalType(U); 6605 if (Deduced.isNull()) { 6606 Deduced = U; 6607 DeducedCanon = UCanon; 6608 DeducedDecl = D; 6609 } else if (DeducedCanon != UCanon) { 6610 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 6611 diag::err_auto_different_deductions) 6612 << Deduced << DeducedDecl->getDeclName() 6613 << U << D->getDeclName() 6614 << DeducedDecl->getInit()->getSourceRange() 6615 << D->getInit()->getSourceRange(); 6616 D->setInvalidDecl(); 6617 break; 6618 } 6619 } 6620 } 6621 } 6622 } 6623 6624 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls)); 6625} 6626 6627 6628/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 6629/// to introduce parameters into function prototype scope. 6630Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 6631 const DeclSpec &DS = D.getDeclSpec(); 6632 6633 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 6634 // C++03 [dcl.stc]p2 also permits 'auto'. 6635 VarDecl::StorageClass StorageClass = SC_None; 6636 VarDecl::StorageClass StorageClassAsWritten = SC_None; 6637 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 6638 StorageClass = SC_Register; 6639 StorageClassAsWritten = SC_Register; 6640 } else if (getLangOptions().CPlusPlus && 6641 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 6642 StorageClass = SC_Auto; 6643 StorageClassAsWritten = SC_Auto; 6644 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 6645 Diag(DS.getStorageClassSpecLoc(), 6646 diag::err_invalid_storage_class_in_func_decl); 6647 D.getMutableDeclSpec().ClearStorageClassSpecs(); 6648 } 6649 6650 if (D.getDeclSpec().isThreadSpecified()) 6651 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 6652 if (D.getDeclSpec().isConstexprSpecified()) 6653 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6654 << 0; 6655 6656 DiagnoseFunctionSpecifiers(D); 6657 6658 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6659 QualType parmDeclType = TInfo->getType(); 6660 6661 if (getLangOptions().CPlusPlus) { 6662 // Check that there are no default arguments inside the type of this 6663 // parameter. 6664 CheckExtraCXXDefaultArguments(D); 6665 6666 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 6667 if (D.getCXXScopeSpec().isSet()) { 6668 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 6669 << D.getCXXScopeSpec().getRange(); 6670 D.getCXXScopeSpec().clear(); 6671 } 6672 } 6673 6674 // Ensure we have a valid name 6675 IdentifierInfo *II = 0; 6676 if (D.hasName()) { 6677 II = D.getIdentifier(); 6678 if (!II) { 6679 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 6680 << GetNameForDeclarator(D).getName().getAsString(); 6681 D.setInvalidType(true); 6682 } 6683 } 6684 6685 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 6686 if (II) { 6687 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 6688 ForRedeclaration); 6689 LookupName(R, S); 6690 if (R.isSingleResult()) { 6691 NamedDecl *PrevDecl = R.getFoundDecl(); 6692 if (PrevDecl->isTemplateParameter()) { 6693 // Maybe we will complain about the shadowed template parameter. 6694 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 6695 // Just pretend that we didn't see the previous declaration. 6696 PrevDecl = 0; 6697 } else if (S->isDeclScope(PrevDecl)) { 6698 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 6699 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 6700 6701 // Recover by removing the name 6702 II = 0; 6703 D.SetIdentifier(0, D.getIdentifierLoc()); 6704 D.setInvalidType(true); 6705 } 6706 } 6707 } 6708 6709 // Temporarily put parameter variables in the translation unit, not 6710 // the enclosing context. This prevents them from accidentally 6711 // looking like class members in C++. 6712 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 6713 D.getSourceRange().getBegin(), 6714 D.getIdentifierLoc(), II, 6715 parmDeclType, TInfo, 6716 StorageClass, StorageClassAsWritten); 6717 6718 if (D.isInvalidType()) 6719 New->setInvalidDecl(); 6720 6721 assert(S->isFunctionPrototypeScope()); 6722 assert(S->getFunctionPrototypeDepth() >= 1); 6723 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 6724 S->getNextFunctionPrototypeIndex()); 6725 6726 // Add the parameter declaration into this scope. 6727 S->AddDecl(New); 6728 if (II) 6729 IdResolver.AddDecl(New); 6730 6731 ProcessDeclAttributes(S, New, D); 6732 6733 if (D.getDeclSpec().isModulePrivateSpecified()) 6734 Diag(New->getLocation(), diag::err_module_private_local) 6735 << 1 << New->getDeclName() 6736 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6737 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6738 6739 if (New->hasAttr<BlocksAttr>()) { 6740 Diag(New->getLocation(), diag::err_block_on_nonlocal); 6741 } 6742 return New; 6743} 6744 6745/// \brief Synthesizes a variable for a parameter arising from a 6746/// typedef. 6747ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 6748 SourceLocation Loc, 6749 QualType T) { 6750 /* FIXME: setting StartLoc == Loc. 6751 Would it be worth to modify callers so as to provide proper source 6752 location for the unnamed parameters, embedding the parameter's type? */ 6753 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 6754 T, Context.getTrivialTypeSourceInfo(T, Loc), 6755 SC_None, SC_None, 0); 6756 Param->setImplicit(); 6757 return Param; 6758} 6759 6760void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 6761 ParmVarDecl * const *ParamEnd) { 6762 // Don't diagnose unused-parameter errors in template instantiations; we 6763 // will already have done so in the template itself. 6764 if (!ActiveTemplateInstantiations.empty()) 6765 return; 6766 6767 for (; Param != ParamEnd; ++Param) { 6768 if (!(*Param)->isUsed() && (*Param)->getDeclName() && 6769 !(*Param)->hasAttr<UnusedAttr>()) { 6770 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 6771 << (*Param)->getDeclName(); 6772 } 6773 } 6774} 6775 6776void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 6777 ParmVarDecl * const *ParamEnd, 6778 QualType ReturnTy, 6779 NamedDecl *D) { 6780 if (LangOpts.NumLargeByValueCopy == 0) // No check. 6781 return; 6782 6783 // Warn if the return value is pass-by-value and larger than the specified 6784 // threshold. 6785 if (ReturnTy.isPODType(Context)) { 6786 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 6787 if (Size > LangOpts.NumLargeByValueCopy) 6788 Diag(D->getLocation(), diag::warn_return_value_size) 6789 << D->getDeclName() << Size; 6790 } 6791 6792 // Warn if any parameter is pass-by-value and larger than the specified 6793 // threshold. 6794 for (; Param != ParamEnd; ++Param) { 6795 QualType T = (*Param)->getType(); 6796 if (!T.isPODType(Context)) 6797 continue; 6798 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 6799 if (Size > LangOpts.NumLargeByValueCopy) 6800 Diag((*Param)->getLocation(), diag::warn_parameter_size) 6801 << (*Param)->getDeclName() << Size; 6802 } 6803} 6804 6805ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 6806 SourceLocation NameLoc, IdentifierInfo *Name, 6807 QualType T, TypeSourceInfo *TSInfo, 6808 VarDecl::StorageClass StorageClass, 6809 VarDecl::StorageClass StorageClassAsWritten) { 6810 // In ARC, infer a lifetime qualifier for appropriate parameter types. 6811 if (getLangOptions().ObjCAutoRefCount && 6812 T.getObjCLifetime() == Qualifiers::OCL_None && 6813 T->isObjCLifetimeType()) { 6814 6815 Qualifiers::ObjCLifetime lifetime; 6816 6817 // Special cases for arrays: 6818 // - if it's const, use __unsafe_unretained 6819 // - otherwise, it's an error 6820 if (T->isArrayType()) { 6821 if (!T.isConstQualified()) { 6822 DelayedDiagnostics.add( 6823 sema::DelayedDiagnostic::makeForbiddenType( 6824 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 6825 } 6826 lifetime = Qualifiers::OCL_ExplicitNone; 6827 } else { 6828 lifetime = T->getObjCARCImplicitLifetime(); 6829 } 6830 T = Context.getLifetimeQualifiedType(T, lifetime); 6831 } 6832 6833 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 6834 Context.getAdjustedParameterType(T), 6835 TSInfo, 6836 StorageClass, StorageClassAsWritten, 6837 0); 6838 6839 // Parameters can not be abstract class types. 6840 // For record types, this is done by the AbstractClassUsageDiagnoser once 6841 // the class has been completely parsed. 6842 if (!CurContext->isRecord() && 6843 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 6844 AbstractParamType)) 6845 New->setInvalidDecl(); 6846 6847 // Parameter declarators cannot be interface types. All ObjC objects are 6848 // passed by reference. 6849 if (T->isObjCObjectType()) { 6850 Diag(NameLoc, 6851 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 6852 << FixItHint::CreateInsertion(NameLoc, "*"); 6853 T = Context.getObjCObjectPointerType(T); 6854 New->setType(T); 6855 } 6856 6857 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 6858 // duration shall not be qualified by an address-space qualifier." 6859 // Since all parameters have automatic store duration, they can not have 6860 // an address space. 6861 if (T.getAddressSpace() != 0) { 6862 Diag(NameLoc, diag::err_arg_with_address_space); 6863 New->setInvalidDecl(); 6864 } 6865 6866 return New; 6867} 6868 6869void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 6870 SourceLocation LocAfterDecls) { 6871 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6872 6873 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 6874 // for a K&R function. 6875 if (!FTI.hasPrototype) { 6876 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 6877 --i; 6878 if (FTI.ArgInfo[i].Param == 0) { 6879 llvm::SmallString<256> Code; 6880 llvm::raw_svector_ostream(Code) << " int " 6881 << FTI.ArgInfo[i].Ident->getName() 6882 << ";\n"; 6883 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 6884 << FTI.ArgInfo[i].Ident 6885 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 6886 6887 // Implicitly declare the argument as type 'int' for lack of a better 6888 // type. 6889 AttributeFactory attrs; 6890 DeclSpec DS(attrs); 6891 const char* PrevSpec; // unused 6892 unsigned DiagID; // unused 6893 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 6894 PrevSpec, DiagID); 6895 Declarator ParamD(DS, Declarator::KNRTypeListContext); 6896 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 6897 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 6898 } 6899 } 6900 } 6901} 6902 6903Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, 6904 Declarator &D) { 6905 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 6906 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 6907 Scope *ParentScope = FnBodyScope->getParent(); 6908 6909 D.setFunctionDefinitionKind(FDK_Definition); 6910 Decl *DP = HandleDeclarator(ParentScope, D, 6911 MultiTemplateParamsArg(*this)); 6912 return ActOnStartOfFunctionDef(FnBodyScope, DP); 6913} 6914 6915static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) { 6916 // Don't warn about invalid declarations. 6917 if (FD->isInvalidDecl()) 6918 return false; 6919 6920 // Or declarations that aren't global. 6921 if (!FD->isGlobal()) 6922 return false; 6923 6924 // Don't warn about C++ member functions. 6925 if (isa<CXXMethodDecl>(FD)) 6926 return false; 6927 6928 // Don't warn about 'main'. 6929 if (FD->isMain()) 6930 return false; 6931 6932 // Don't warn about inline functions. 6933 if (FD->isInlined()) 6934 return false; 6935 6936 // Don't warn about function templates. 6937 if (FD->getDescribedFunctionTemplate()) 6938 return false; 6939 6940 // Don't warn about function template specializations. 6941 if (FD->isFunctionTemplateSpecialization()) 6942 return false; 6943 6944 bool MissingPrototype = true; 6945 for (const FunctionDecl *Prev = FD->getPreviousDeclaration(); 6946 Prev; Prev = Prev->getPreviousDeclaration()) { 6947 // Ignore any declarations that occur in function or method 6948 // scope, because they aren't visible from the header. 6949 if (Prev->getDeclContext()->isFunctionOrMethod()) 6950 continue; 6951 6952 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 6953 break; 6954 } 6955 6956 return MissingPrototype; 6957} 6958 6959void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) { 6960 // Don't complain if we're in GNU89 mode and the previous definition 6961 // was an extern inline function. 6962 const FunctionDecl *Definition; 6963 if (FD->isDefined(Definition) && 6964 !canRedefineFunction(Definition, getLangOptions())) { 6965 if (getLangOptions().GNUMode && Definition->isInlineSpecified() && 6966 Definition->getStorageClass() == SC_Extern) 6967 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 6968 << FD->getDeclName() << getLangOptions().CPlusPlus; 6969 else 6970 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 6971 Diag(Definition->getLocation(), diag::note_previous_definition); 6972 } 6973} 6974 6975Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 6976 // Clear the last template instantiation error context. 6977 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 6978 6979 if (!D) 6980 return D; 6981 FunctionDecl *FD = 0; 6982 6983 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 6984 FD = FunTmpl->getTemplatedDecl(); 6985 else 6986 FD = cast<FunctionDecl>(D); 6987 6988 // Enter a new function scope 6989 PushFunctionScope(); 6990 6991 // See if this is a redefinition. 6992 if (!FD->isLateTemplateParsed()) 6993 CheckForFunctionRedefinition(FD); 6994 6995 // Builtin functions cannot be defined. 6996 if (unsigned BuiltinID = FD->getBuiltinID()) { 6997 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 6998 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 6999 FD->setInvalidDecl(); 7000 } 7001 } 7002 7003 // The return type of a function definition must be complete 7004 // (C99 6.9.1p3, C++ [dcl.fct]p6). 7005 QualType ResultType = FD->getResultType(); 7006 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 7007 !FD->isInvalidDecl() && 7008 RequireCompleteType(FD->getLocation(), ResultType, 7009 diag::err_func_def_incomplete_result)) 7010 FD->setInvalidDecl(); 7011 7012 // GNU warning -Wmissing-prototypes: 7013 // Warn if a global function is defined without a previous 7014 // prototype declaration. This warning is issued even if the 7015 // definition itself provides a prototype. The aim is to detect 7016 // global functions that fail to be declared in header files. 7017 if (ShouldWarnAboutMissingPrototype(FD)) 7018 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 7019 7020 if (FnBodyScope) 7021 PushDeclContext(FnBodyScope, FD); 7022 7023 // Check the validity of our function parameters 7024 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 7025 /*CheckParameterNames=*/true); 7026 7027 // Introduce our parameters into the function scope 7028 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 7029 ParmVarDecl *Param = FD->getParamDecl(p); 7030 Param->setOwningFunction(FD); 7031 7032 // If this has an identifier, add it to the scope stack. 7033 if (Param->getIdentifier() && FnBodyScope) { 7034 CheckShadow(FnBodyScope, Param); 7035 7036 PushOnScopeChains(Param, FnBodyScope); 7037 } 7038 } 7039 7040 // Checking attributes of current function definition 7041 // dllimport attribute. 7042 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 7043 if (DA && (!FD->getAttr<DLLExportAttr>())) { 7044 // dllimport attribute cannot be directly applied to definition. 7045 // Microsoft accepts dllimport for functions defined within class scope. 7046 if (!DA->isInherited() && 7047 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 7048 Diag(FD->getLocation(), 7049 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 7050 << "dllimport"; 7051 FD->setInvalidDecl(); 7052 return FD; 7053 } 7054 7055 // Visual C++ appears to not think this is an issue, so only issue 7056 // a warning when Microsoft extensions are disabled. 7057 if (!LangOpts.MicrosoftExt) { 7058 // If a symbol previously declared dllimport is later defined, the 7059 // attribute is ignored in subsequent references, and a warning is 7060 // emitted. 7061 Diag(FD->getLocation(), 7062 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 7063 << FD->getName() << "dllimport"; 7064 } 7065 } 7066 return FD; 7067} 7068 7069/// \brief Given the set of return statements within a function body, 7070/// compute the variables that are subject to the named return value 7071/// optimization. 7072/// 7073/// Each of the variables that is subject to the named return value 7074/// optimization will be marked as NRVO variables in the AST, and any 7075/// return statement that has a marked NRVO variable as its NRVO candidate can 7076/// use the named return value optimization. 7077/// 7078/// This function applies a very simplistic algorithm for NRVO: if every return 7079/// statement in the function has the same NRVO candidate, that candidate is 7080/// the NRVO variable. 7081/// 7082/// FIXME: Employ a smarter algorithm that accounts for multiple return 7083/// statements and the lifetimes of the NRVO candidates. We should be able to 7084/// find a maximal set of NRVO variables. 7085void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 7086 ReturnStmt **Returns = Scope->Returns.data(); 7087 7088 const VarDecl *NRVOCandidate = 0; 7089 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 7090 if (!Returns[I]->getNRVOCandidate()) 7091 return; 7092 7093 if (!NRVOCandidate) 7094 NRVOCandidate = Returns[I]->getNRVOCandidate(); 7095 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 7096 return; 7097 } 7098 7099 if (NRVOCandidate) 7100 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 7101} 7102 7103Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 7104 return ActOnFinishFunctionBody(D, move(BodyArg), false); 7105} 7106 7107Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 7108 bool IsInstantiation) { 7109 FunctionDecl *FD = 0; 7110 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 7111 if (FunTmpl) 7112 FD = FunTmpl->getTemplatedDecl(); 7113 else 7114 FD = dyn_cast_or_null<FunctionDecl>(dcl); 7115 7116 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 7117 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 7118 7119 if (FD) { 7120 FD->setBody(Body); 7121 if (FD->isMain()) { 7122 // C and C++ allow for main to automagically return 0. 7123 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3. 7124 FD->setHasImplicitReturnZero(true); 7125 WP.disableCheckFallThrough(); 7126 } else if (FD->hasAttr<NakedAttr>()) { 7127 // If the function is marked 'naked', don't complain about missing return 7128 // statements. 7129 WP.disableCheckFallThrough(); 7130 } 7131 7132 // MSVC permits the use of pure specifier (=0) on function definition, 7133 // defined at class scope, warn about this non standard construct. 7134 if (getLangOptions().MicrosoftExt && FD->isPure()) 7135 Diag(FD->getLocation(), diag::warn_pure_function_definition); 7136 7137 if (!FD->isInvalidDecl()) { 7138 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 7139 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 7140 FD->getResultType(), FD); 7141 7142 // If this is a constructor, we need a vtable. 7143 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 7144 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 7145 7146 computeNRVO(Body, getCurFunction()); 7147 } 7148 7149 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 7150 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 7151 assert(MD == getCurMethodDecl() && "Method parsing confused"); 7152 MD->setBody(Body); 7153 if (Body) 7154 MD->setEndLoc(Body->getLocEnd()); 7155 if (!MD->isInvalidDecl()) { 7156 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 7157 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 7158 MD->getResultType(), MD); 7159 7160 if (Body) 7161 computeNRVO(Body, getCurFunction()); 7162 } 7163 if (ObjCShouldCallSuperDealloc) { 7164 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_dealloc); 7165 ObjCShouldCallSuperDealloc = false; 7166 } 7167 if (ObjCShouldCallSuperFinalize) { 7168 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_finalize); 7169 ObjCShouldCallSuperFinalize = false; 7170 } 7171 } else { 7172 return 0; 7173 } 7174 7175 assert(!ObjCShouldCallSuperDealloc && "This should only be set for " 7176 "ObjC methods, which should have been handled in the block above."); 7177 assert(!ObjCShouldCallSuperFinalize && "This should only be set for " 7178 "ObjC methods, which should have been handled in the block above."); 7179 7180 // Verify and clean out per-function state. 7181 if (Body) { 7182 // C++ constructors that have function-try-blocks can't have return 7183 // statements in the handlers of that block. (C++ [except.handle]p14) 7184 // Verify this. 7185 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 7186 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 7187 7188 // Verify that gotos and switch cases don't jump into scopes illegally. 7189 if (getCurFunction()->NeedsScopeChecking() && 7190 !dcl->isInvalidDecl() && 7191 !hasAnyUnrecoverableErrorsInThisFunction()) 7192 DiagnoseInvalidJumps(Body); 7193 7194 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 7195 if (!Destructor->getParent()->isDependentType()) 7196 CheckDestructor(Destructor); 7197 7198 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 7199 Destructor->getParent()); 7200 } 7201 7202 // If any errors have occurred, clear out any temporaries that may have 7203 // been leftover. This ensures that these temporaries won't be picked up for 7204 // deletion in some later function. 7205 if (PP.getDiagnostics().hasErrorOccurred() || 7206 PP.getDiagnostics().getSuppressAllDiagnostics()) { 7207 DiscardCleanupsInEvaluationContext(); 7208 } else if (!isa<FunctionTemplateDecl>(dcl)) { 7209 // Since the body is valid, issue any analysis-based warnings that are 7210 // enabled. 7211 ActivePolicy = &WP; 7212 } 7213 7214 if (FD && FD->isConstexpr() && !FD->isInvalidDecl() && 7215 !CheckConstexprFunctionBody(FD, Body)) 7216 FD->setInvalidDecl(); 7217 7218 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 7219 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 7220 } 7221 7222 if (!IsInstantiation) 7223 PopDeclContext(); 7224 7225 PopFunctionOrBlockScope(ActivePolicy, dcl); 7226 7227 // If any errors have occurred, clear out any temporaries that may have 7228 // been leftover. This ensures that these temporaries won't be picked up for 7229 // deletion in some later function. 7230 if (getDiagnostics().hasErrorOccurred()) { 7231 DiscardCleanupsInEvaluationContext(); 7232 } 7233 7234 return dcl; 7235} 7236 7237 7238/// When we finish delayed parsing of an attribute, we must attach it to the 7239/// relevant Decl. 7240void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 7241 ParsedAttributes &Attrs) { 7242 ProcessDeclAttributeList(S, D, Attrs.getList()); 7243} 7244 7245 7246/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 7247/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 7248NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 7249 IdentifierInfo &II, Scope *S) { 7250 // Before we produce a declaration for an implicitly defined 7251 // function, see whether there was a locally-scoped declaration of 7252 // this name as a function or variable. If so, use that 7253 // (non-visible) declaration, and complain about it. 7254 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 7255 = findLocallyScopedExternalDecl(&II); 7256 if (Pos != LocallyScopedExternalDecls.end()) { 7257 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 7258 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 7259 return Pos->second; 7260 } 7261 7262 // See if we can find a typo correction. 7263 TypoCorrection Corrected; 7264 FunctionDecl *Func = 0; 7265 std::string CorrectedStr; 7266 std::string CorrectedQuotedStr; 7267 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 7268 LookupOrdinaryName, S, 0))) { 7269 // Since this is an implicit function declaration, we are only 7270 // interested in a potential typo for a function name. 7271 if ((Func = dyn_cast_or_null<FunctionDecl>( 7272 Corrected.getCorrectionDecl()))) { 7273 CorrectedStr = Corrected.getAsString(getLangOptions()); 7274 CorrectedQuotedStr = Corrected.getQuoted(getLangOptions()); 7275 } 7276 } 7277 7278 // Extension in C99. Legal in C90, but warn about it. 7279 if (II.getName().startswith("__builtin_")) 7280 Diag(Loc, diag::err_builtin_unknown) << &II; 7281 else if (getLangOptions().C99) 7282 Diag(Loc, diag::ext_implicit_function_decl) << &II; 7283 else 7284 Diag(Loc, diag::warn_implicit_function_decl) << &II; 7285 7286 if (Func) { 7287 // If we found a typo correction, then suggest that. 7288 Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr 7289 << FixItHint::CreateReplacement(Loc, CorrectedStr); 7290 if (Func->getLocation().isValid() && !II.getName().startswith("__builtin_")) 7291 Diag(Func->getLocation(), diag::note_previous_decl) << CorrectedQuotedStr; 7292 } 7293 7294 // Set a Declarator for the implicit definition: int foo(); 7295 const char *Dummy; 7296 AttributeFactory attrFactory; 7297 DeclSpec DS(attrFactory); 7298 unsigned DiagID; 7299 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 7300 (void)Error; // Silence warning. 7301 assert(!Error && "Error setting up implicit decl!"); 7302 Declarator D(DS, Declarator::BlockContext); 7303 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0, 7304 0, 0, true, SourceLocation(), 7305 SourceLocation(), SourceLocation(), 7306 SourceLocation(), 7307 EST_None, SourceLocation(), 7308 0, 0, 0, 0, Loc, Loc, D), 7309 DS.getAttributes(), 7310 SourceLocation()); 7311 D.SetIdentifier(&II, Loc); 7312 7313 // Insert this function into translation-unit scope. 7314 7315 DeclContext *PrevDC = CurContext; 7316 CurContext = Context.getTranslationUnitDecl(); 7317 7318 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 7319 FD->setImplicit(); 7320 7321 CurContext = PrevDC; 7322 7323 AddKnownFunctionAttributes(FD); 7324 7325 return FD; 7326} 7327 7328/// \brief Adds any function attributes that we know a priori based on 7329/// the declaration of this function. 7330/// 7331/// These attributes can apply both to implicitly-declared builtins 7332/// (like __builtin___printf_chk) or to library-declared functions 7333/// like NSLog or printf. 7334/// 7335/// We need to check for duplicate attributes both here and where user-written 7336/// attributes are applied to declarations. 7337void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 7338 if (FD->isInvalidDecl()) 7339 return; 7340 7341 // If this is a built-in function, map its builtin attributes to 7342 // actual attributes. 7343 if (unsigned BuiltinID = FD->getBuiltinID()) { 7344 // Handle printf-formatting attributes. 7345 unsigned FormatIdx; 7346 bool HasVAListArg; 7347 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 7348 if (!FD->getAttr<FormatAttr>()) 7349 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 7350 "printf", FormatIdx+1, 7351 HasVAListArg ? 0 : FormatIdx+2)); 7352 } 7353 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 7354 HasVAListArg)) { 7355 if (!FD->getAttr<FormatAttr>()) 7356 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 7357 "scanf", FormatIdx+1, 7358 HasVAListArg ? 0 : FormatIdx+2)); 7359 } 7360 7361 // Mark const if we don't care about errno and that is the only 7362 // thing preventing the function from being const. This allows 7363 // IRgen to use LLVM intrinsics for such functions. 7364 if (!getLangOptions().MathErrno && 7365 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 7366 if (!FD->getAttr<ConstAttr>()) 7367 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 7368 } 7369 7370 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 7371 !FD->getAttr<ReturnsTwiceAttr>()) 7372 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context)); 7373 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>()) 7374 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context)); 7375 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>()) 7376 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 7377 } 7378 7379 IdentifierInfo *Name = FD->getIdentifier(); 7380 if (!Name) 7381 return; 7382 if ((!getLangOptions().CPlusPlus && 7383 FD->getDeclContext()->isTranslationUnit()) || 7384 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 7385 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 7386 LinkageSpecDecl::lang_c)) { 7387 // Okay: this could be a libc/libm/Objective-C function we know 7388 // about. 7389 } else 7390 return; 7391 7392 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) { 7393 // FIXME: NSLog and NSLogv should be target specific 7394 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) { 7395 // FIXME: We known better than our headers. 7396 const_cast<FormatAttr *>(Format)->setType(Context, "printf"); 7397 } else 7398 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 7399 "printf", 1, 7400 Name->isStr("NSLogv") ? 0 : 2)); 7401 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 7402 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 7403 // target-specific builtins, perhaps? 7404 if (!FD->getAttr<FormatAttr>()) 7405 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 7406 "printf", 2, 7407 Name->isStr("vasprintf") ? 0 : 3)); 7408 } 7409} 7410 7411TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 7412 TypeSourceInfo *TInfo) { 7413 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 7414 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 7415 7416 if (!TInfo) { 7417 assert(D.isInvalidType() && "no declarator info for valid type"); 7418 TInfo = Context.getTrivialTypeSourceInfo(T); 7419 } 7420 7421 // Scope manipulation handled by caller. 7422 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 7423 D.getSourceRange().getBegin(), 7424 D.getIdentifierLoc(), 7425 D.getIdentifier(), 7426 TInfo); 7427 7428 // Bail out immediately if we have an invalid declaration. 7429 if (D.isInvalidType()) { 7430 NewTD->setInvalidDecl(); 7431 return NewTD; 7432 } 7433 7434 if (D.getDeclSpec().isModulePrivateSpecified()) { 7435 if (CurContext->isFunctionOrMethod()) 7436 Diag(NewTD->getLocation(), diag::err_module_private_local) 7437 << 2 << NewTD->getDeclName() 7438 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7439 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7440 else 7441 NewTD->setModulePrivate(); 7442 } 7443 7444 // C++ [dcl.typedef]p8: 7445 // If the typedef declaration defines an unnamed class (or 7446 // enum), the first typedef-name declared by the declaration 7447 // to be that class type (or enum type) is used to denote the 7448 // class type (or enum type) for linkage purposes only. 7449 // We need to check whether the type was declared in the declaration. 7450 switch (D.getDeclSpec().getTypeSpecType()) { 7451 case TST_enum: 7452 case TST_struct: 7453 case TST_union: 7454 case TST_class: { 7455 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 7456 7457 // Do nothing if the tag is not anonymous or already has an 7458 // associated typedef (from an earlier typedef in this decl group). 7459 if (tagFromDeclSpec->getIdentifier()) break; 7460 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 7461 7462 // A well-formed anonymous tag must always be a TUK_Definition. 7463 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 7464 7465 // The type must match the tag exactly; no qualifiers allowed. 7466 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 7467 break; 7468 7469 // Otherwise, set this is the anon-decl typedef for the tag. 7470 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 7471 break; 7472 } 7473 7474 default: 7475 break; 7476 } 7477 7478 return NewTD; 7479} 7480 7481 7482/// \brief Determine whether a tag with a given kind is acceptable 7483/// as a redeclaration of the given tag declaration. 7484/// 7485/// \returns true if the new tag kind is acceptable, false otherwise. 7486bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 7487 TagTypeKind NewTag, bool isDefinition, 7488 SourceLocation NewTagLoc, 7489 const IdentifierInfo &Name) { 7490 // C++ [dcl.type.elab]p3: 7491 // The class-key or enum keyword present in the 7492 // elaborated-type-specifier shall agree in kind with the 7493 // declaration to which the name in the elaborated-type-specifier 7494 // refers. This rule also applies to the form of 7495 // elaborated-type-specifier that declares a class-name or 7496 // friend class since it can be construed as referring to the 7497 // definition of the class. Thus, in any 7498 // elaborated-type-specifier, the enum keyword shall be used to 7499 // refer to an enumeration (7.2), the union class-key shall be 7500 // used to refer to a union (clause 9), and either the class or 7501 // struct class-key shall be used to refer to a class (clause 9) 7502 // declared using the class or struct class-key. 7503 TagTypeKind OldTag = Previous->getTagKind(); 7504 if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct)) 7505 if (OldTag == NewTag) 7506 return true; 7507 7508 if ((OldTag == TTK_Struct || OldTag == TTK_Class) && 7509 (NewTag == TTK_Struct || NewTag == TTK_Class)) { 7510 // Warn about the struct/class tag mismatch. 7511 bool isTemplate = false; 7512 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 7513 isTemplate = Record->getDescribedClassTemplate(); 7514 7515 if (!ActiveTemplateInstantiations.empty()) { 7516 // In a template instantiation, do not offer fix-its for tag mismatches 7517 // since they usually mess up the template instead of fixing the problem. 7518 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 7519 << (NewTag == TTK_Class) << isTemplate << &Name; 7520 return true; 7521 } 7522 7523 if (isDefinition) { 7524 // On definitions, check previous tags and issue a fix-it for each 7525 // one that doesn't match the current tag. 7526 if (Previous->getDefinition()) { 7527 // Don't suggest fix-its for redefinitions. 7528 return true; 7529 } 7530 7531 bool previousMismatch = false; 7532 for (TagDecl::redecl_iterator I(Previous->redecls_begin()), 7533 E(Previous->redecls_end()); I != E; ++I) { 7534 if (I->getTagKind() != NewTag) { 7535 if (!previousMismatch) { 7536 previousMismatch = true; 7537 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 7538 << (NewTag == TTK_Class) << isTemplate << &Name; 7539 } 7540 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 7541 << (NewTag == TTK_Class) 7542 << FixItHint::CreateReplacement(I->getInnerLocStart(), 7543 NewTag == TTK_Class? 7544 "class" : "struct"); 7545 } 7546 } 7547 return true; 7548 } 7549 7550 // Check for a previous definition. If current tag and definition 7551 // are same type, do nothing. If no definition, but disagree with 7552 // with previous tag type, give a warning, but no fix-it. 7553 const TagDecl *Redecl = Previous->getDefinition() ? 7554 Previous->getDefinition() : Previous; 7555 if (Redecl->getTagKind() == NewTag) { 7556 return true; 7557 } 7558 7559 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 7560 << (NewTag == TTK_Class) 7561 << isTemplate << &Name; 7562 Diag(Redecl->getLocation(), diag::note_previous_use); 7563 7564 // If there is a previous defintion, suggest a fix-it. 7565 if (Previous->getDefinition()) { 7566 Diag(NewTagLoc, diag::note_struct_class_suggestion) 7567 << (Redecl->getTagKind() == TTK_Class) 7568 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 7569 Redecl->getTagKind() == TTK_Class? "class" : "struct"); 7570 } 7571 7572 return true; 7573 } 7574 return false; 7575} 7576 7577/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 7578/// former case, Name will be non-null. In the later case, Name will be null. 7579/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 7580/// reference/declaration/definition of a tag. 7581Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 7582 SourceLocation KWLoc, CXXScopeSpec &SS, 7583 IdentifierInfo *Name, SourceLocation NameLoc, 7584 AttributeList *Attr, AccessSpecifier AS, 7585 SourceLocation ModulePrivateLoc, 7586 MultiTemplateParamsArg TemplateParameterLists, 7587 bool &OwnedDecl, bool &IsDependent, 7588 bool ScopedEnum, bool ScopedEnumUsesClassTag, 7589 TypeResult UnderlyingType) { 7590 // If this is not a definition, it must have a name. 7591 assert((Name != 0 || TUK == TUK_Definition) && 7592 "Nameless record must be a definition!"); 7593 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 7594 7595 OwnedDecl = false; 7596 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 7597 7598 // FIXME: Check explicit specializations more carefully. 7599 bool isExplicitSpecialization = false; 7600 bool Invalid = false; 7601 7602 // We only need to do this matching if we have template parameters 7603 // or a scope specifier, which also conveniently avoids this work 7604 // for non-C++ cases. 7605 if (TemplateParameterLists.size() > 0 || 7606 (SS.isNotEmpty() && TUK != TUK_Reference)) { 7607 if (TemplateParameterList *TemplateParams 7608 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS, 7609 TemplateParameterLists.get(), 7610 TemplateParameterLists.size(), 7611 TUK == TUK_Friend, 7612 isExplicitSpecialization, 7613 Invalid)) { 7614 if (TemplateParams->size() > 0) { 7615 // This is a declaration or definition of a class template (which may 7616 // be a member of another template). 7617 7618 if (Invalid) 7619 return 0; 7620 7621 OwnedDecl = false; 7622 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 7623 SS, Name, NameLoc, Attr, 7624 TemplateParams, AS, 7625 ModulePrivateLoc, 7626 TemplateParameterLists.size() - 1, 7627 (TemplateParameterList**) TemplateParameterLists.release()); 7628 return Result.get(); 7629 } else { 7630 // The "template<>" header is extraneous. 7631 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 7632 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 7633 isExplicitSpecialization = true; 7634 } 7635 } 7636 } 7637 7638 // Figure out the underlying type if this a enum declaration. We need to do 7639 // this early, because it's needed to detect if this is an incompatible 7640 // redeclaration. 7641 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 7642 7643 if (Kind == TTK_Enum) { 7644 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 7645 // No underlying type explicitly specified, or we failed to parse the 7646 // type, default to int. 7647 EnumUnderlying = Context.IntTy.getTypePtr(); 7648 else if (UnderlyingType.get()) { 7649 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 7650 // integral type; any cv-qualification is ignored. 7651 TypeSourceInfo *TI = 0; 7652 QualType T = GetTypeFromParser(UnderlyingType.get(), &TI); 7653 EnumUnderlying = TI; 7654 7655 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 7656 7657 if (!T->isDependentType() && !T->isIntegralType(Context)) { 7658 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) 7659 << T; 7660 // Recover by falling back to int. 7661 EnumUnderlying = Context.IntTy.getTypePtr(); 7662 } 7663 7664 if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI, 7665 UPPC_FixedUnderlyingType)) 7666 EnumUnderlying = Context.IntTy.getTypePtr(); 7667 7668 } else if (getLangOptions().MicrosoftExt) 7669 // Microsoft enums are always of int type. 7670 EnumUnderlying = Context.IntTy.getTypePtr(); 7671 } 7672 7673 DeclContext *SearchDC = CurContext; 7674 DeclContext *DC = CurContext; 7675 bool isStdBadAlloc = false; 7676 7677 RedeclarationKind Redecl = ForRedeclaration; 7678 if (TUK == TUK_Friend || TUK == TUK_Reference) 7679 Redecl = NotForRedeclaration; 7680 7681 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 7682 7683 if (Name && SS.isNotEmpty()) { 7684 // We have a nested-name tag ('struct foo::bar'). 7685 7686 // Check for invalid 'foo::'. 7687 if (SS.isInvalid()) { 7688 Name = 0; 7689 goto CreateNewDecl; 7690 } 7691 7692 // If this is a friend or a reference to a class in a dependent 7693 // context, don't try to make a decl for it. 7694 if (TUK == TUK_Friend || TUK == TUK_Reference) { 7695 DC = computeDeclContext(SS, false); 7696 if (!DC) { 7697 IsDependent = true; 7698 return 0; 7699 } 7700 } else { 7701 DC = computeDeclContext(SS, true); 7702 if (!DC) { 7703 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 7704 << SS.getRange(); 7705 return 0; 7706 } 7707 } 7708 7709 if (RequireCompleteDeclContext(SS, DC)) 7710 return 0; 7711 7712 SearchDC = DC; 7713 // Look-up name inside 'foo::'. 7714 LookupQualifiedName(Previous, DC); 7715 7716 if (Previous.isAmbiguous()) 7717 return 0; 7718 7719 if (Previous.empty()) { 7720 // Name lookup did not find anything. However, if the 7721 // nested-name-specifier refers to the current instantiation, 7722 // and that current instantiation has any dependent base 7723 // classes, we might find something at instantiation time: treat 7724 // this as a dependent elaborated-type-specifier. 7725 // But this only makes any sense for reference-like lookups. 7726 if (Previous.wasNotFoundInCurrentInstantiation() && 7727 (TUK == TUK_Reference || TUK == TUK_Friend)) { 7728 IsDependent = true; 7729 return 0; 7730 } 7731 7732 // A tag 'foo::bar' must already exist. 7733 Diag(NameLoc, diag::err_not_tag_in_scope) 7734 << Kind << Name << DC << SS.getRange(); 7735 Name = 0; 7736 Invalid = true; 7737 goto CreateNewDecl; 7738 } 7739 } else if (Name) { 7740 // If this is a named struct, check to see if there was a previous forward 7741 // declaration or definition. 7742 // FIXME: We're looking into outer scopes here, even when we 7743 // shouldn't be. Doing so can result in ambiguities that we 7744 // shouldn't be diagnosing. 7745 LookupName(Previous, S); 7746 7747 if (Previous.isAmbiguous() && 7748 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 7749 LookupResult::Filter F = Previous.makeFilter(); 7750 while (F.hasNext()) { 7751 NamedDecl *ND = F.next(); 7752 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 7753 F.erase(); 7754 } 7755 F.done(); 7756 } 7757 7758 // Note: there used to be some attempt at recovery here. 7759 if (Previous.isAmbiguous()) 7760 return 0; 7761 7762 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) { 7763 // FIXME: This makes sure that we ignore the contexts associated 7764 // with C structs, unions, and enums when looking for a matching 7765 // tag declaration or definition. See the similar lookup tweak 7766 // in Sema::LookupName; is there a better way to deal with this? 7767 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 7768 SearchDC = SearchDC->getParent(); 7769 } 7770 } else if (S->isFunctionPrototypeScope()) { 7771 // If this is an enum declaration in function prototype scope, set its 7772 // initial context to the translation unit. 7773 SearchDC = Context.getTranslationUnitDecl(); 7774 } 7775 7776 if (Previous.isSingleResult() && 7777 Previous.getFoundDecl()->isTemplateParameter()) { 7778 // Maybe we will complain about the shadowed template parameter. 7779 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 7780 // Just pretend that we didn't see the previous declaration. 7781 Previous.clear(); 7782 } 7783 7784 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace && 7785 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 7786 // This is a declaration of or a reference to "std::bad_alloc". 7787 isStdBadAlloc = true; 7788 7789 if (Previous.empty() && StdBadAlloc) { 7790 // std::bad_alloc has been implicitly declared (but made invisible to 7791 // name lookup). Fill in this implicit declaration as the previous 7792 // declaration, so that the declarations get chained appropriately. 7793 Previous.addDecl(getStdBadAlloc()); 7794 } 7795 } 7796 7797 // If we didn't find a previous declaration, and this is a reference 7798 // (or friend reference), move to the correct scope. In C++, we 7799 // also need to do a redeclaration lookup there, just in case 7800 // there's a shadow friend decl. 7801 if (Name && Previous.empty() && 7802 (TUK == TUK_Reference || TUK == TUK_Friend)) { 7803 if (Invalid) goto CreateNewDecl; 7804 assert(SS.isEmpty()); 7805 7806 if (TUK == TUK_Reference) { 7807 // C++ [basic.scope.pdecl]p5: 7808 // -- for an elaborated-type-specifier of the form 7809 // 7810 // class-key identifier 7811 // 7812 // if the elaborated-type-specifier is used in the 7813 // decl-specifier-seq or parameter-declaration-clause of a 7814 // function defined in namespace scope, the identifier is 7815 // declared as a class-name in the namespace that contains 7816 // the declaration; otherwise, except as a friend 7817 // declaration, the identifier is declared in the smallest 7818 // non-class, non-function-prototype scope that contains the 7819 // declaration. 7820 // 7821 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 7822 // C structs and unions. 7823 // 7824 // It is an error in C++ to declare (rather than define) an enum 7825 // type, including via an elaborated type specifier. We'll 7826 // diagnose that later; for now, declare the enum in the same 7827 // scope as we would have picked for any other tag type. 7828 // 7829 // GNU C also supports this behavior as part of its incomplete 7830 // enum types extension, while GNU C++ does not. 7831 // 7832 // Find the context where we'll be declaring the tag. 7833 // FIXME: We would like to maintain the current DeclContext as the 7834 // lexical context, 7835 while (SearchDC->isRecord() || SearchDC->isTransparentContext()) 7836 SearchDC = SearchDC->getParent(); 7837 7838 // Find the scope where we'll be declaring the tag. 7839 while (S->isClassScope() || 7840 (getLangOptions().CPlusPlus && 7841 S->isFunctionPrototypeScope()) || 7842 ((S->getFlags() & Scope::DeclScope) == 0) || 7843 (S->getEntity() && 7844 ((DeclContext *)S->getEntity())->isTransparentContext())) 7845 S = S->getParent(); 7846 } else { 7847 assert(TUK == TUK_Friend); 7848 // C++ [namespace.memdef]p3: 7849 // If a friend declaration in a non-local class first declares a 7850 // class or function, the friend class or function is a member of 7851 // the innermost enclosing namespace. 7852 SearchDC = SearchDC->getEnclosingNamespaceContext(); 7853 } 7854 7855 // In C++, we need to do a redeclaration lookup to properly 7856 // diagnose some problems. 7857 if (getLangOptions().CPlusPlus) { 7858 Previous.setRedeclarationKind(ForRedeclaration); 7859 LookupQualifiedName(Previous, SearchDC); 7860 } 7861 } 7862 7863 if (!Previous.empty()) { 7864 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 7865 7866 // It's okay to have a tag decl in the same scope as a typedef 7867 // which hides a tag decl in the same scope. Finding this 7868 // insanity with a redeclaration lookup can only actually happen 7869 // in C++. 7870 // 7871 // This is also okay for elaborated-type-specifiers, which is 7872 // technically forbidden by the current standard but which is 7873 // okay according to the likely resolution of an open issue; 7874 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 7875 if (getLangOptions().CPlusPlus) { 7876 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 7877 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 7878 TagDecl *Tag = TT->getDecl(); 7879 if (Tag->getDeclName() == Name && 7880 Tag->getDeclContext()->getRedeclContext() 7881 ->Equals(TD->getDeclContext()->getRedeclContext())) { 7882 PrevDecl = Tag; 7883 Previous.clear(); 7884 Previous.addDecl(Tag); 7885 Previous.resolveKind(); 7886 } 7887 } 7888 } 7889 } 7890 7891 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 7892 // If this is a use of a previous tag, or if the tag is already declared 7893 // in the same scope (so that the definition/declaration completes or 7894 // rementions the tag), reuse the decl. 7895 if (TUK == TUK_Reference || TUK == TUK_Friend || 7896 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) { 7897 // Make sure that this wasn't declared as an enum and now used as a 7898 // struct or something similar. 7899 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 7900 TUK == TUK_Definition, KWLoc, 7901 *Name)) { 7902 bool SafeToContinue 7903 = (PrevTagDecl->getTagKind() != TTK_Enum && 7904 Kind != TTK_Enum); 7905 if (SafeToContinue) 7906 Diag(KWLoc, diag::err_use_with_wrong_tag) 7907 << Name 7908 << FixItHint::CreateReplacement(SourceRange(KWLoc), 7909 PrevTagDecl->getKindName()); 7910 else 7911 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 7912 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7913 7914 if (SafeToContinue) 7915 Kind = PrevTagDecl->getTagKind(); 7916 else { 7917 // Recover by making this an anonymous redefinition. 7918 Name = 0; 7919 Previous.clear(); 7920 Invalid = true; 7921 } 7922 } 7923 7924 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 7925 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 7926 7927 // All conflicts with previous declarations are recovered by 7928 // returning the previous declaration. 7929 if (ScopedEnum != PrevEnum->isScoped()) { 7930 Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch) 7931 << PrevEnum->isScoped(); 7932 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7933 return PrevTagDecl; 7934 } 7935 else if (EnumUnderlying && PrevEnum->isFixed()) { 7936 QualType T; 7937 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 7938 T = TI->getType(); 7939 else 7940 T = QualType(EnumUnderlying.get<const Type*>(), 0); 7941 7942 if (!Context.hasSameUnqualifiedType(T, 7943 PrevEnum->getIntegerType())) { 7944 Diag(NameLoc.isValid() ? NameLoc : KWLoc, 7945 diag::err_enum_redeclare_type_mismatch) 7946 << T 7947 << PrevEnum->getIntegerType(); 7948 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7949 return PrevTagDecl; 7950 } 7951 } 7952 else if (!EnumUnderlying.isNull() != PrevEnum->isFixed()) { 7953 Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch) 7954 << PrevEnum->isFixed(); 7955 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7956 return PrevTagDecl; 7957 } 7958 } 7959 7960 if (!Invalid) { 7961 // If this is a use, just return the declaration we found. 7962 7963 // FIXME: In the future, return a variant or some other clue 7964 // for the consumer of this Decl to know it doesn't own it. 7965 // For our current ASTs this shouldn't be a problem, but will 7966 // need to be changed with DeclGroups. 7967 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 7968 getLangOptions().MicrosoftExt)) || TUK == TUK_Friend) 7969 return PrevTagDecl; 7970 7971 // Diagnose attempts to redefine a tag. 7972 if (TUK == TUK_Definition) { 7973 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 7974 // If we're defining a specialization and the previous definition 7975 // is from an implicit instantiation, don't emit an error 7976 // here; we'll catch this in the general case below. 7977 if (!isExplicitSpecialization || 7978 !isa<CXXRecordDecl>(Def) || 7979 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind() 7980 == TSK_ExplicitSpecialization) { 7981 Diag(NameLoc, diag::err_redefinition) << Name; 7982 Diag(Def->getLocation(), diag::note_previous_definition); 7983 // If this is a redefinition, recover by making this 7984 // struct be anonymous, which will make any later 7985 // references get the previous definition. 7986 Name = 0; 7987 Previous.clear(); 7988 Invalid = true; 7989 } 7990 } else { 7991 // If the type is currently being defined, complain 7992 // about a nested redefinition. 7993 const TagType *Tag 7994 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 7995 if (Tag->isBeingDefined()) { 7996 Diag(NameLoc, diag::err_nested_redefinition) << Name; 7997 Diag(PrevTagDecl->getLocation(), 7998 diag::note_previous_definition); 7999 Name = 0; 8000 Previous.clear(); 8001 Invalid = true; 8002 } 8003 } 8004 8005 // Okay, this is definition of a previously declared or referenced 8006 // tag PrevDecl. We're going to create a new Decl for it. 8007 } 8008 } 8009 // If we get here we have (another) forward declaration or we 8010 // have a definition. Just create a new decl. 8011 8012 } else { 8013 // If we get here, this is a definition of a new tag type in a nested 8014 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 8015 // new decl/type. We set PrevDecl to NULL so that the entities 8016 // have distinct types. 8017 Previous.clear(); 8018 } 8019 // If we get here, we're going to create a new Decl. If PrevDecl 8020 // is non-NULL, it's a definition of the tag declared by 8021 // PrevDecl. If it's NULL, we have a new definition. 8022 8023 8024 // Otherwise, PrevDecl is not a tag, but was found with tag 8025 // lookup. This is only actually possible in C++, where a few 8026 // things like templates still live in the tag namespace. 8027 } else { 8028 assert(getLangOptions().CPlusPlus); 8029 8030 // Use a better diagnostic if an elaborated-type-specifier 8031 // found the wrong kind of type on the first 8032 // (non-redeclaration) lookup. 8033 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 8034 !Previous.isForRedeclaration()) { 8035 unsigned Kind = 0; 8036 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 8037 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 8038 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 8039 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 8040 Diag(PrevDecl->getLocation(), diag::note_declared_at); 8041 Invalid = true; 8042 8043 // Otherwise, only diagnose if the declaration is in scope. 8044 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 8045 isExplicitSpecialization)) { 8046 // do nothing 8047 8048 // Diagnose implicit declarations introduced by elaborated types. 8049 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 8050 unsigned Kind = 0; 8051 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 8052 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 8053 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 8054 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 8055 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 8056 Invalid = true; 8057 8058 // Otherwise it's a declaration. Call out a particularly common 8059 // case here. 8060 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 8061 unsigned Kind = 0; 8062 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 8063 Diag(NameLoc, diag::err_tag_definition_of_typedef) 8064 << Name << Kind << TND->getUnderlyingType(); 8065 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 8066 Invalid = true; 8067 8068 // Otherwise, diagnose. 8069 } else { 8070 // The tag name clashes with something else in the target scope, 8071 // issue an error and recover by making this tag be anonymous. 8072 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 8073 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8074 Name = 0; 8075 Invalid = true; 8076 } 8077 8078 // The existing declaration isn't relevant to us; we're in a 8079 // new scope, so clear out the previous declaration. 8080 Previous.clear(); 8081 } 8082 } 8083 8084CreateNewDecl: 8085 8086 TagDecl *PrevDecl = 0; 8087 if (Previous.isSingleResult()) 8088 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 8089 8090 // If there is an identifier, use the location of the identifier as the 8091 // location of the decl, otherwise use the location of the struct/union 8092 // keyword. 8093 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 8094 8095 // Otherwise, create a new declaration. If there is a previous 8096 // declaration of the same entity, the two will be linked via 8097 // PrevDecl. 8098 TagDecl *New; 8099 8100 bool IsForwardReference = false; 8101 if (Kind == TTK_Enum) { 8102 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 8103 // enum X { A, B, C } D; D should chain to X. 8104 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 8105 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 8106 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 8107 // If this is an undefined enum, warn. 8108 if (TUK != TUK_Definition && !Invalid) { 8109 TagDecl *Def; 8110 if (getLangOptions().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) { 8111 // C++0x: 7.2p2: opaque-enum-declaration. 8112 // Conflicts are diagnosed above. Do nothing. 8113 } 8114 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 8115 Diag(Loc, diag::ext_forward_ref_enum_def) 8116 << New; 8117 Diag(Def->getLocation(), diag::note_previous_definition); 8118 } else { 8119 unsigned DiagID = diag::ext_forward_ref_enum; 8120 if (getLangOptions().MicrosoftExt) 8121 DiagID = diag::ext_ms_forward_ref_enum; 8122 else if (getLangOptions().CPlusPlus) 8123 DiagID = diag::err_forward_ref_enum; 8124 Diag(Loc, DiagID); 8125 8126 // If this is a forward-declared reference to an enumeration, make a 8127 // note of it; we won't actually be introducing the declaration into 8128 // the declaration context. 8129 if (TUK == TUK_Reference) 8130 IsForwardReference = true; 8131 } 8132 } 8133 8134 if (EnumUnderlying) { 8135 EnumDecl *ED = cast<EnumDecl>(New); 8136 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 8137 ED->setIntegerTypeSourceInfo(TI); 8138 else 8139 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 8140 ED->setPromotionType(ED->getIntegerType()); 8141 } 8142 8143 } else { 8144 // struct/union/class 8145 8146 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 8147 // struct X { int A; } D; D should chain to X. 8148 if (getLangOptions().CPlusPlus) { 8149 // FIXME: Look for a way to use RecordDecl for simple structs. 8150 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 8151 cast_or_null<CXXRecordDecl>(PrevDecl)); 8152 8153 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 8154 StdBadAlloc = cast<CXXRecordDecl>(New); 8155 } else 8156 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 8157 cast_or_null<RecordDecl>(PrevDecl)); 8158 } 8159 8160 // Maybe add qualifier info. 8161 if (SS.isNotEmpty()) { 8162 if (SS.isSet()) { 8163 New->setQualifierInfo(SS.getWithLocInContext(Context)); 8164 if (TemplateParameterLists.size() > 0) { 8165 New->setTemplateParameterListsInfo(Context, 8166 TemplateParameterLists.size(), 8167 (TemplateParameterList**) TemplateParameterLists.release()); 8168 } 8169 } 8170 else 8171 Invalid = true; 8172 } 8173 8174 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 8175 // Add alignment attributes if necessary; these attributes are checked when 8176 // the ASTContext lays out the structure. 8177 // 8178 // It is important for implementing the correct semantics that this 8179 // happen here (in act on tag decl). The #pragma pack stack is 8180 // maintained as a result of parser callbacks which can occur at 8181 // many points during the parsing of a struct declaration (because 8182 // the #pragma tokens are effectively skipped over during the 8183 // parsing of the struct). 8184 AddAlignmentAttributesForRecord(RD); 8185 8186 AddMsStructLayoutForRecord(RD); 8187 } 8188 8189 if (PrevDecl && PrevDecl->isModulePrivate()) 8190 New->setModulePrivate(); 8191 else if (ModulePrivateLoc.isValid()) { 8192 if (isExplicitSpecialization) 8193 Diag(New->getLocation(), diag::err_module_private_specialization) 8194 << 2 8195 << FixItHint::CreateRemoval(ModulePrivateLoc); 8196 else if (PrevDecl && !PrevDecl->isModulePrivate()) 8197 diagnoseModulePrivateRedeclaration(New, PrevDecl, ModulePrivateLoc); 8198 // __module_private__ does not apply to local classes. However, we only 8199 // diagnose this as an error when the declaration specifiers are 8200 // freestanding. Here, we just ignore the __module_private__. 8201 // foobar 8202 else if (!SearchDC->isFunctionOrMethod()) 8203 New->setModulePrivate(); 8204 } 8205 8206 // If this is a specialization of a member class (of a class template), 8207 // check the specialization. 8208 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 8209 Invalid = true; 8210 8211 if (Invalid) 8212 New->setInvalidDecl(); 8213 8214 if (Attr) 8215 ProcessDeclAttributeList(S, New, Attr); 8216 8217 // If we're declaring or defining a tag in function prototype scope 8218 // in C, note that this type can only be used within the function. 8219 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus) 8220 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 8221 8222 // Set the lexical context. If the tag has a C++ scope specifier, the 8223 // lexical context will be different from the semantic context. 8224 New->setLexicalDeclContext(CurContext); 8225 8226 // Mark this as a friend decl if applicable. 8227 // In Microsoft mode, a friend declaration also acts as a forward 8228 // declaration so we always pass true to setObjectOfFriendDecl to make 8229 // the tag name visible. 8230 if (TUK == TUK_Friend) 8231 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() || 8232 getLangOptions().MicrosoftExt); 8233 8234 // Set the access specifier. 8235 if (!Invalid && SearchDC->isRecord()) 8236 SetMemberAccessSpecifier(New, PrevDecl, AS); 8237 8238 if (TUK == TUK_Definition) 8239 New->startDefinition(); 8240 8241 // If this has an identifier, add it to the scope stack. 8242 if (TUK == TUK_Friend) { 8243 // We might be replacing an existing declaration in the lookup tables; 8244 // if so, borrow its access specifier. 8245 if (PrevDecl) 8246 New->setAccess(PrevDecl->getAccess()); 8247 8248 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 8249 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false); 8250 if (Name) // can be null along some error paths 8251 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 8252 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 8253 } else if (Name) { 8254 S = getNonFieldDeclScope(S); 8255 PushOnScopeChains(New, S, !IsForwardReference); 8256 if (IsForwardReference) 8257 SearchDC->makeDeclVisibleInContext(New, /* Recoverable = */ false); 8258 8259 } else { 8260 CurContext->addDecl(New); 8261 } 8262 8263 // If this is the C FILE type, notify the AST context. 8264 if (IdentifierInfo *II = New->getIdentifier()) 8265 if (!New->isInvalidDecl() && 8266 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 8267 II->isStr("FILE")) 8268 Context.setFILEDecl(New); 8269 8270 OwnedDecl = true; 8271 return New; 8272} 8273 8274void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 8275 AdjustDeclIfTemplate(TagD); 8276 TagDecl *Tag = cast<TagDecl>(TagD); 8277 8278 // Enter the tag context. 8279 PushDeclContext(S, Tag); 8280} 8281 8282Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 8283 assert(isa<ObjCContainerDecl>(IDecl) && 8284 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 8285 DeclContext *OCD = cast<DeclContext>(IDecl); 8286 assert(getContainingDC(OCD) == CurContext && 8287 "The next DeclContext should be lexically contained in the current one."); 8288 CurContext = OCD; 8289 return IDecl; 8290} 8291 8292void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 8293 SourceLocation FinalLoc, 8294 SourceLocation LBraceLoc) { 8295 AdjustDeclIfTemplate(TagD); 8296 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 8297 8298 FieldCollector->StartClass(); 8299 8300 if (!Record->getIdentifier()) 8301 return; 8302 8303 if (FinalLoc.isValid()) 8304 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context)); 8305 8306 // C++ [class]p2: 8307 // [...] The class-name is also inserted into the scope of the 8308 // class itself; this is known as the injected-class-name. For 8309 // purposes of access checking, the injected-class-name is treated 8310 // as if it were a public member name. 8311 CXXRecordDecl *InjectedClassName 8312 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 8313 Record->getLocStart(), Record->getLocation(), 8314 Record->getIdentifier(), 8315 /*PrevDecl=*/0, 8316 /*DelayTypeCreation=*/true); 8317 Context.getTypeDeclType(InjectedClassName, Record); 8318 InjectedClassName->setImplicit(); 8319 InjectedClassName->setAccess(AS_public); 8320 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 8321 InjectedClassName->setDescribedClassTemplate(Template); 8322 PushOnScopeChains(InjectedClassName, S); 8323 assert(InjectedClassName->isInjectedClassName() && 8324 "Broken injected-class-name"); 8325} 8326 8327void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 8328 SourceLocation RBraceLoc) { 8329 AdjustDeclIfTemplate(TagD); 8330 TagDecl *Tag = cast<TagDecl>(TagD); 8331 Tag->setRBraceLoc(RBraceLoc); 8332 8333 if (isa<CXXRecordDecl>(Tag)) 8334 FieldCollector->FinishClass(); 8335 8336 // Exit this scope of this tag's definition. 8337 PopDeclContext(); 8338 8339 // Notify the consumer that we've defined a tag. 8340 Consumer.HandleTagDeclDefinition(Tag); 8341} 8342 8343void Sema::ActOnObjCContainerFinishDefinition() { 8344 // Exit this scope of this interface definition. 8345 PopDeclContext(); 8346} 8347 8348void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 8349 assert(DC == CurContext && "Mismatch of container contexts"); 8350 OriginalLexicalContext = DC; 8351 ActOnObjCContainerFinishDefinition(); 8352} 8353 8354void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 8355 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 8356 OriginalLexicalContext = 0; 8357} 8358 8359void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 8360 AdjustDeclIfTemplate(TagD); 8361 TagDecl *Tag = cast<TagDecl>(TagD); 8362 Tag->setInvalidDecl(); 8363 8364 // We're undoing ActOnTagStartDefinition here, not 8365 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 8366 // the FieldCollector. 8367 8368 PopDeclContext(); 8369} 8370 8371// Note that FieldName may be null for anonymous bitfields. 8372bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 8373 QualType FieldTy, const Expr *BitWidth, 8374 bool *ZeroWidth) { 8375 // Default to true; that shouldn't confuse checks for emptiness 8376 if (ZeroWidth) 8377 *ZeroWidth = true; 8378 8379 // C99 6.7.2.1p4 - verify the field type. 8380 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 8381 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 8382 // Handle incomplete types with specific error. 8383 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 8384 return true; 8385 if (FieldName) 8386 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 8387 << FieldName << FieldTy << BitWidth->getSourceRange(); 8388 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 8389 << FieldTy << BitWidth->getSourceRange(); 8390 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 8391 UPPC_BitFieldWidth)) 8392 return true; 8393 8394 // If the bit-width is type- or value-dependent, don't try to check 8395 // it now. 8396 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 8397 return false; 8398 8399 llvm::APSInt Value; 8400 if (VerifyIntegerConstantExpression(BitWidth, &Value)) 8401 return true; 8402 8403 if (Value != 0 && ZeroWidth) 8404 *ZeroWidth = false; 8405 8406 // Zero-width bitfield is ok for anonymous field. 8407 if (Value == 0 && FieldName) 8408 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 8409 8410 if (Value.isSigned() && Value.isNegative()) { 8411 if (FieldName) 8412 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 8413 << FieldName << Value.toString(10); 8414 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 8415 << Value.toString(10); 8416 } 8417 8418 if (!FieldTy->isDependentType()) { 8419 uint64_t TypeSize = Context.getTypeSize(FieldTy); 8420 if (Value.getZExtValue() > TypeSize) { 8421 if (!getLangOptions().CPlusPlus) { 8422 if (FieldName) 8423 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 8424 << FieldName << (unsigned)Value.getZExtValue() 8425 << (unsigned)TypeSize; 8426 8427 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 8428 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 8429 } 8430 8431 if (FieldName) 8432 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 8433 << FieldName << (unsigned)Value.getZExtValue() 8434 << (unsigned)TypeSize; 8435 else 8436 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 8437 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 8438 } 8439 } 8440 8441 return false; 8442} 8443 8444/// ActOnField - Each field of a C struct/union is passed into this in order 8445/// to create a FieldDecl object for it. 8446Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 8447 Declarator &D, Expr *BitfieldWidth) { 8448 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 8449 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 8450 /*HasInit=*/false, AS_public); 8451 return Res; 8452} 8453 8454/// HandleField - Analyze a field of a C struct or a C++ data member. 8455/// 8456FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 8457 SourceLocation DeclStart, 8458 Declarator &D, Expr *BitWidth, bool HasInit, 8459 AccessSpecifier AS) { 8460 IdentifierInfo *II = D.getIdentifier(); 8461 SourceLocation Loc = DeclStart; 8462 if (II) Loc = D.getIdentifierLoc(); 8463 8464 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 8465 QualType T = TInfo->getType(); 8466 if (getLangOptions().CPlusPlus) { 8467 CheckExtraCXXDefaultArguments(D); 8468 8469 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 8470 UPPC_DataMemberType)) { 8471 D.setInvalidType(); 8472 T = Context.IntTy; 8473 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 8474 } 8475 } 8476 8477 DiagnoseFunctionSpecifiers(D); 8478 8479 if (D.getDeclSpec().isThreadSpecified()) 8480 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 8481 if (D.getDeclSpec().isConstexprSpecified()) 8482 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 8483 << 2; 8484 8485 // Check to see if this name was declared as a member previously 8486 NamedDecl *PrevDecl = 0; 8487 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 8488 LookupName(Previous, S); 8489 switch (Previous.getResultKind()) { 8490 case LookupResult::Found: 8491 case LookupResult::FoundUnresolvedValue: 8492 PrevDecl = Previous.getAsSingle<NamedDecl>(); 8493 break; 8494 8495 case LookupResult::FoundOverloaded: 8496 PrevDecl = Previous.getRepresentativeDecl(); 8497 break; 8498 8499 case LookupResult::NotFound: 8500 case LookupResult::NotFoundInCurrentInstantiation: 8501 case LookupResult::Ambiguous: 8502 break; 8503 } 8504 Previous.suppressDiagnostics(); 8505 8506 if (PrevDecl && PrevDecl->isTemplateParameter()) { 8507 // Maybe we will complain about the shadowed template parameter. 8508 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 8509 // Just pretend that we didn't see the previous declaration. 8510 PrevDecl = 0; 8511 } 8512 8513 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 8514 PrevDecl = 0; 8515 8516 bool Mutable 8517 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 8518 SourceLocation TSSL = D.getSourceRange().getBegin(); 8519 FieldDecl *NewFD 8520 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit, 8521 TSSL, AS, PrevDecl, &D); 8522 8523 if (NewFD->isInvalidDecl()) 8524 Record->setInvalidDecl(); 8525 8526 if (D.getDeclSpec().isModulePrivateSpecified()) 8527 NewFD->setModulePrivate(); 8528 8529 if (NewFD->isInvalidDecl() && PrevDecl) { 8530 // Don't introduce NewFD into scope; there's already something 8531 // with the same name in the same scope. 8532 } else if (II) { 8533 PushOnScopeChains(NewFD, S); 8534 } else 8535 Record->addDecl(NewFD); 8536 8537 return NewFD; 8538} 8539 8540/// \brief Build a new FieldDecl and check its well-formedness. 8541/// 8542/// This routine builds a new FieldDecl given the fields name, type, 8543/// record, etc. \p PrevDecl should refer to any previous declaration 8544/// with the same name and in the same scope as the field to be 8545/// created. 8546/// 8547/// \returns a new FieldDecl. 8548/// 8549/// \todo The Declarator argument is a hack. It will be removed once 8550FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 8551 TypeSourceInfo *TInfo, 8552 RecordDecl *Record, SourceLocation Loc, 8553 bool Mutable, Expr *BitWidth, bool HasInit, 8554 SourceLocation TSSL, 8555 AccessSpecifier AS, NamedDecl *PrevDecl, 8556 Declarator *D) { 8557 IdentifierInfo *II = Name.getAsIdentifierInfo(); 8558 bool InvalidDecl = false; 8559 if (D) InvalidDecl = D->isInvalidType(); 8560 8561 // If we receive a broken type, recover by assuming 'int' and 8562 // marking this declaration as invalid. 8563 if (T.isNull()) { 8564 InvalidDecl = true; 8565 T = Context.IntTy; 8566 } 8567 8568 QualType EltTy = Context.getBaseElementType(T); 8569 if (!EltTy->isDependentType() && 8570 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 8571 // Fields of incomplete type force their record to be invalid. 8572 Record->setInvalidDecl(); 8573 InvalidDecl = true; 8574 } 8575 8576 // C99 6.7.2.1p8: A member of a structure or union may have any type other 8577 // than a variably modified type. 8578 if (!InvalidDecl && T->isVariablyModifiedType()) { 8579 bool SizeIsNegative; 8580 llvm::APSInt Oversized; 8581 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context, 8582 SizeIsNegative, 8583 Oversized); 8584 if (!FixedTy.isNull()) { 8585 Diag(Loc, diag::warn_illegal_constant_array_size); 8586 T = FixedTy; 8587 } else { 8588 if (SizeIsNegative) 8589 Diag(Loc, diag::err_typecheck_negative_array_size); 8590 else if (Oversized.getBoolValue()) 8591 Diag(Loc, diag::err_array_too_large) 8592 << Oversized.toString(10); 8593 else 8594 Diag(Loc, diag::err_typecheck_field_variable_size); 8595 InvalidDecl = true; 8596 } 8597 } 8598 8599 // Fields can not have abstract class types 8600 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 8601 diag::err_abstract_type_in_decl, 8602 AbstractFieldType)) 8603 InvalidDecl = true; 8604 8605 bool ZeroWidth = false; 8606 // If this is declared as a bit-field, check the bit-field. 8607 if (!InvalidDecl && BitWidth && 8608 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) { 8609 InvalidDecl = true; 8610 BitWidth = 0; 8611 ZeroWidth = false; 8612 } 8613 8614 // Check that 'mutable' is consistent with the type of the declaration. 8615 if (!InvalidDecl && Mutable) { 8616 unsigned DiagID = 0; 8617 if (T->isReferenceType()) 8618 DiagID = diag::err_mutable_reference; 8619 else if (T.isConstQualified()) 8620 DiagID = diag::err_mutable_const; 8621 8622 if (DiagID) { 8623 SourceLocation ErrLoc = Loc; 8624 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 8625 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 8626 Diag(ErrLoc, DiagID); 8627 Mutable = false; 8628 InvalidDecl = true; 8629 } 8630 } 8631 8632 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 8633 BitWidth, Mutable, HasInit); 8634 if (InvalidDecl) 8635 NewFD->setInvalidDecl(); 8636 8637 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 8638 Diag(Loc, diag::err_duplicate_member) << II; 8639 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 8640 NewFD->setInvalidDecl(); 8641 } 8642 8643 if (!InvalidDecl && getLangOptions().CPlusPlus) { 8644 if (Record->isUnion()) { 8645 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 8646 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 8647 if (RDecl->getDefinition()) { 8648 // C++ [class.union]p1: An object of a class with a non-trivial 8649 // constructor, a non-trivial copy constructor, a non-trivial 8650 // destructor, or a non-trivial copy assignment operator 8651 // cannot be a member of a union, nor can an array of such 8652 // objects. 8653 if (CheckNontrivialField(NewFD)) 8654 NewFD->setInvalidDecl(); 8655 } 8656 } 8657 8658 // C++ [class.union]p1: If a union contains a member of reference type, 8659 // the program is ill-formed. 8660 if (EltTy->isReferenceType()) { 8661 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type) 8662 << NewFD->getDeclName() << EltTy; 8663 NewFD->setInvalidDecl(); 8664 } 8665 } 8666 } 8667 8668 // FIXME: We need to pass in the attributes given an AST 8669 // representation, not a parser representation. 8670 if (D) 8671 // FIXME: What to pass instead of TUScope? 8672 ProcessDeclAttributes(TUScope, NewFD, *D); 8673 8674 // In auto-retain/release, infer strong retension for fields of 8675 // retainable type. 8676 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 8677 NewFD->setInvalidDecl(); 8678 8679 if (T.isObjCGCWeak()) 8680 Diag(Loc, diag::warn_attribute_weak_on_field); 8681 8682 NewFD->setAccess(AS); 8683 return NewFD; 8684} 8685 8686bool Sema::CheckNontrivialField(FieldDecl *FD) { 8687 assert(FD); 8688 assert(getLangOptions().CPlusPlus && "valid check only for C++"); 8689 8690 if (FD->isInvalidDecl()) 8691 return true; 8692 8693 QualType EltTy = Context.getBaseElementType(FD->getType()); 8694 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 8695 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 8696 if (RDecl->getDefinition()) { 8697 // We check for copy constructors before constructors 8698 // because otherwise we'll never get complaints about 8699 // copy constructors. 8700 8701 CXXSpecialMember member = CXXInvalid; 8702 if (!RDecl->hasTrivialCopyConstructor()) 8703 member = CXXCopyConstructor; 8704 else if (!RDecl->hasTrivialDefaultConstructor()) 8705 member = CXXDefaultConstructor; 8706 else if (!RDecl->hasTrivialCopyAssignment()) 8707 member = CXXCopyAssignment; 8708 else if (!RDecl->hasTrivialDestructor()) 8709 member = CXXDestructor; 8710 8711 if (member != CXXInvalid) { 8712 if (!getLangOptions().CPlusPlus0x && 8713 getLangOptions().ObjCAutoRefCount && RDecl->hasObjectMember()) { 8714 // Objective-C++ ARC: it is an error to have a non-trivial field of 8715 // a union. However, system headers in Objective-C programs 8716 // occasionally have Objective-C lifetime objects within unions, 8717 // and rather than cause the program to fail, we make those 8718 // members unavailable. 8719 SourceLocation Loc = FD->getLocation(); 8720 if (getSourceManager().isInSystemHeader(Loc)) { 8721 if (!FD->hasAttr<UnavailableAttr>()) 8722 FD->addAttr(new (Context) UnavailableAttr(Loc, Context, 8723 "this system field has retaining ownership")); 8724 return false; 8725 } 8726 } 8727 8728 Diag(FD->getLocation(), getLangOptions().CPlusPlus0x ? 8729 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 8730 diag::err_illegal_union_or_anon_struct_member) 8731 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 8732 DiagnoseNontrivial(RT, member); 8733 return !getLangOptions().CPlusPlus0x; 8734 } 8735 } 8736 } 8737 8738 return false; 8739} 8740 8741/// DiagnoseNontrivial - Given that a class has a non-trivial 8742/// special member, figure out why. 8743void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) { 8744 QualType QT(T, 0U); 8745 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl()); 8746 8747 // Check whether the member was user-declared. 8748 switch (member) { 8749 case CXXInvalid: 8750 break; 8751 8752 case CXXDefaultConstructor: 8753 if (RD->hasUserDeclaredConstructor()) { 8754 typedef CXXRecordDecl::ctor_iterator ctor_iter; 8755 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){ 8756 const FunctionDecl *body = 0; 8757 ci->hasBody(body); 8758 if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) { 8759 SourceLocation CtorLoc = ci->getLocation(); 8760 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 8761 return; 8762 } 8763 } 8764 8765 llvm_unreachable("found no user-declared constructors"); 8766 } 8767 break; 8768 8769 case CXXCopyConstructor: 8770 if (RD->hasUserDeclaredCopyConstructor()) { 8771 SourceLocation CtorLoc = 8772 RD->getCopyConstructor(0)->getLocation(); 8773 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 8774 return; 8775 } 8776 break; 8777 8778 case CXXMoveConstructor: 8779 if (RD->hasUserDeclaredMoveConstructor()) { 8780 SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation(); 8781 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 8782 return; 8783 } 8784 break; 8785 8786 case CXXCopyAssignment: 8787 if (RD->hasUserDeclaredCopyAssignment()) { 8788 // FIXME: this should use the location of the copy 8789 // assignment, not the type. 8790 SourceLocation TyLoc = RD->getSourceRange().getBegin(); 8791 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member; 8792 return; 8793 } 8794 break; 8795 8796 case CXXMoveAssignment: 8797 if (RD->hasUserDeclaredMoveAssignment()) { 8798 SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation(); 8799 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member; 8800 return; 8801 } 8802 break; 8803 8804 case CXXDestructor: 8805 if (RD->hasUserDeclaredDestructor()) { 8806 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation(); 8807 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member; 8808 return; 8809 } 8810 break; 8811 } 8812 8813 typedef CXXRecordDecl::base_class_iterator base_iter; 8814 8815 // Virtual bases and members inhibit trivial copying/construction, 8816 // but not trivial destruction. 8817 if (member != CXXDestructor) { 8818 // Check for virtual bases. vbases includes indirect virtual bases, 8819 // so we just iterate through the direct bases. 8820 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) 8821 if (bi->isVirtual()) { 8822 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 8823 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1; 8824 return; 8825 } 8826 8827 // Check for virtual methods. 8828 typedef CXXRecordDecl::method_iterator meth_iter; 8829 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me; 8830 ++mi) { 8831 if (mi->isVirtual()) { 8832 SourceLocation MLoc = mi->getSourceRange().getBegin(); 8833 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0; 8834 return; 8835 } 8836 } 8837 } 8838 8839 bool (CXXRecordDecl::*hasTrivial)() const; 8840 switch (member) { 8841 case CXXDefaultConstructor: 8842 hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break; 8843 case CXXCopyConstructor: 8844 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break; 8845 case CXXCopyAssignment: 8846 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break; 8847 case CXXDestructor: 8848 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break; 8849 default: 8850 llvm_unreachable("unexpected special member"); 8851 } 8852 8853 // Check for nontrivial bases (and recurse). 8854 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) { 8855 const RecordType *BaseRT = bi->getType()->getAs<RecordType>(); 8856 assert(BaseRT && "Don't know how to handle dependent bases"); 8857 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl()); 8858 if (!(BaseRecTy->*hasTrivial)()) { 8859 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 8860 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member; 8861 DiagnoseNontrivial(BaseRT, member); 8862 return; 8863 } 8864 } 8865 8866 // Check for nontrivial members (and recurse). 8867 typedef RecordDecl::field_iterator field_iter; 8868 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe; 8869 ++fi) { 8870 QualType EltTy = Context.getBaseElementType((*fi)->getType()); 8871 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) { 8872 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl()); 8873 8874 if (!(EltRD->*hasTrivial)()) { 8875 SourceLocation FLoc = (*fi)->getLocation(); 8876 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member; 8877 DiagnoseNontrivial(EltRT, member); 8878 return; 8879 } 8880 } 8881 8882 if (EltTy->isObjCLifetimeType()) { 8883 switch (EltTy.getObjCLifetime()) { 8884 case Qualifiers::OCL_None: 8885 case Qualifiers::OCL_ExplicitNone: 8886 break; 8887 8888 case Qualifiers::OCL_Autoreleasing: 8889 case Qualifiers::OCL_Weak: 8890 case Qualifiers::OCL_Strong: 8891 Diag((*fi)->getLocation(), diag::note_nontrivial_objc_ownership) 8892 << QT << EltTy.getObjCLifetime(); 8893 return; 8894 } 8895 } 8896 } 8897 8898 llvm_unreachable("found no explanation for non-trivial member"); 8899} 8900 8901/// TranslateIvarVisibility - Translate visibility from a token ID to an 8902/// AST enum value. 8903static ObjCIvarDecl::AccessControl 8904TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 8905 switch (ivarVisibility) { 8906 default: llvm_unreachable("Unknown visitibility kind"); 8907 case tok::objc_private: return ObjCIvarDecl::Private; 8908 case tok::objc_public: return ObjCIvarDecl::Public; 8909 case tok::objc_protected: return ObjCIvarDecl::Protected; 8910 case tok::objc_package: return ObjCIvarDecl::Package; 8911 } 8912} 8913 8914/// ActOnIvar - Each ivar field of an objective-c class is passed into this 8915/// in order to create an IvarDecl object for it. 8916Decl *Sema::ActOnIvar(Scope *S, 8917 SourceLocation DeclStart, 8918 Declarator &D, Expr *BitfieldWidth, 8919 tok::ObjCKeywordKind Visibility) { 8920 8921 IdentifierInfo *II = D.getIdentifier(); 8922 Expr *BitWidth = (Expr*)BitfieldWidth; 8923 SourceLocation Loc = DeclStart; 8924 if (II) Loc = D.getIdentifierLoc(); 8925 8926 // FIXME: Unnamed fields can be handled in various different ways, for 8927 // example, unnamed unions inject all members into the struct namespace! 8928 8929 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 8930 QualType T = TInfo->getType(); 8931 8932 if (BitWidth) { 8933 // 6.7.2.1p3, 6.7.2.1p4 8934 if (VerifyBitField(Loc, II, T, BitWidth)) { 8935 D.setInvalidType(); 8936 BitWidth = 0; 8937 } 8938 } else { 8939 // Not a bitfield. 8940 8941 // validate II. 8942 8943 } 8944 if (T->isReferenceType()) { 8945 Diag(Loc, diag::err_ivar_reference_type); 8946 D.setInvalidType(); 8947 } 8948 // C99 6.7.2.1p8: A member of a structure or union may have any type other 8949 // than a variably modified type. 8950 else if (T->isVariablyModifiedType()) { 8951 Diag(Loc, diag::err_typecheck_ivar_variable_size); 8952 D.setInvalidType(); 8953 } 8954 8955 // Get the visibility (access control) for this ivar. 8956 ObjCIvarDecl::AccessControl ac = 8957 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 8958 : ObjCIvarDecl::None; 8959 // Must set ivar's DeclContext to its enclosing interface. 8960 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 8961 ObjCContainerDecl *EnclosingContext; 8962 if (ObjCImplementationDecl *IMPDecl = 8963 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 8964 if (!LangOpts.ObjCNonFragileABI2) { 8965 // Case of ivar declared in an implementation. Context is that of its class. 8966 EnclosingContext = IMPDecl->getClassInterface(); 8967 assert(EnclosingContext && "Implementation has no class interface!"); 8968 } 8969 else 8970 EnclosingContext = EnclosingDecl; 8971 } else { 8972 if (ObjCCategoryDecl *CDecl = 8973 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 8974 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) { 8975 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 8976 return 0; 8977 } 8978 } 8979 EnclosingContext = EnclosingDecl; 8980 } 8981 8982 // Construct the decl. 8983 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 8984 DeclStart, Loc, II, T, 8985 TInfo, ac, (Expr *)BitfieldWidth); 8986 8987 if (II) { 8988 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 8989 ForRedeclaration); 8990 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 8991 && !isa<TagDecl>(PrevDecl)) { 8992 Diag(Loc, diag::err_duplicate_member) << II; 8993 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 8994 NewID->setInvalidDecl(); 8995 } 8996 } 8997 8998 // Process attributes attached to the ivar. 8999 ProcessDeclAttributes(S, NewID, D); 9000 9001 if (D.isInvalidType()) 9002 NewID->setInvalidDecl(); 9003 9004 // In ARC, infer 'retaining' for ivars of retainable type. 9005 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 9006 NewID->setInvalidDecl(); 9007 9008 if (D.getDeclSpec().isModulePrivateSpecified()) 9009 NewID->setModulePrivate(); 9010 9011 if (II) { 9012 // FIXME: When interfaces are DeclContexts, we'll need to add 9013 // these to the interface. 9014 S->AddDecl(NewID); 9015 IdResolver.AddDecl(NewID); 9016 } 9017 9018 return NewID; 9019} 9020 9021/// ActOnLastBitfield - This routine handles synthesized bitfields rules for 9022/// class and class extensions. For every class @interface and class 9023/// extension @interface, if the last ivar is a bitfield of any type, 9024/// then add an implicit `char :0` ivar to the end of that interface. 9025void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 9026 SmallVectorImpl<Decl *> &AllIvarDecls) { 9027 if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty()) 9028 return; 9029 9030 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 9031 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 9032 9033 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 9034 return; 9035 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 9036 if (!ID) { 9037 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 9038 if (!CD->IsClassExtension()) 9039 return; 9040 } 9041 // No need to add this to end of @implementation. 9042 else 9043 return; 9044 } 9045 // All conditions are met. Add a new bitfield to the tail end of ivars. 9046 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 9047 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 9048 9049 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 9050 DeclLoc, DeclLoc, 0, 9051 Context.CharTy, 9052 Context.getTrivialTypeSourceInfo(Context.CharTy, 9053 DeclLoc), 9054 ObjCIvarDecl::Private, BW, 9055 true); 9056 AllIvarDecls.push_back(Ivar); 9057} 9058 9059void Sema::ActOnFields(Scope* S, 9060 SourceLocation RecLoc, Decl *EnclosingDecl, 9061 llvm::ArrayRef<Decl *> Fields, 9062 SourceLocation LBrac, SourceLocation RBrac, 9063 AttributeList *Attr) { 9064 assert(EnclosingDecl && "missing record or interface decl"); 9065 9066 // If the decl this is being inserted into is invalid, then it may be a 9067 // redeclaration or some other bogus case. Don't try to add fields to it. 9068 if (EnclosingDecl->isInvalidDecl()) 9069 return; 9070 9071 // Verify that all the fields are okay. 9072 unsigned NumNamedMembers = 0; 9073 SmallVector<FieldDecl*, 32> RecFields; 9074 9075 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 9076 bool ARCErrReported = false; 9077 for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 9078 i != end; ++i) { 9079 FieldDecl *FD = cast<FieldDecl>(*i); 9080 9081 // Get the type for the field. 9082 const Type *FDTy = FD->getType().getTypePtr(); 9083 9084 if (!FD->isAnonymousStructOrUnion()) { 9085 // Remember all fields written by the user. 9086 RecFields.push_back(FD); 9087 } 9088 9089 // If the field is already invalid for some reason, don't emit more 9090 // diagnostics about it. 9091 if (FD->isInvalidDecl()) { 9092 EnclosingDecl->setInvalidDecl(); 9093 continue; 9094 } 9095 9096 // C99 6.7.2.1p2: 9097 // A structure or union shall not contain a member with 9098 // incomplete or function type (hence, a structure shall not 9099 // contain an instance of itself, but may contain a pointer to 9100 // an instance of itself), except that the last member of a 9101 // structure with more than one named member may have incomplete 9102 // array type; such a structure (and any union containing, 9103 // possibly recursively, a member that is such a structure) 9104 // shall not be a member of a structure or an element of an 9105 // array. 9106 if (FDTy->isFunctionType()) { 9107 // Field declared as a function. 9108 Diag(FD->getLocation(), diag::err_field_declared_as_function) 9109 << FD->getDeclName(); 9110 FD->setInvalidDecl(); 9111 EnclosingDecl->setInvalidDecl(); 9112 continue; 9113 } else if (FDTy->isIncompleteArrayType() && Record && 9114 ((i + 1 == Fields.end() && !Record->isUnion()) || 9115 ((getLangOptions().MicrosoftExt || 9116 getLangOptions().CPlusPlus) && 9117 (i + 1 == Fields.end() || Record->isUnion())))) { 9118 // Flexible array member. 9119 // Microsoft and g++ is more permissive regarding flexible array. 9120 // It will accept flexible array in union and also 9121 // as the sole element of a struct/class. 9122 if (getLangOptions().MicrosoftExt) { 9123 if (Record->isUnion()) 9124 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms) 9125 << FD->getDeclName(); 9126 else if (Fields.size() == 1) 9127 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms) 9128 << FD->getDeclName() << Record->getTagKind(); 9129 } else if (getLangOptions().CPlusPlus) { 9130 if (Record->isUnion()) 9131 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 9132 << FD->getDeclName(); 9133 else if (Fields.size() == 1) 9134 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu) 9135 << FD->getDeclName() << Record->getTagKind(); 9136 } else if (NumNamedMembers < 1) { 9137 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 9138 << FD->getDeclName(); 9139 FD->setInvalidDecl(); 9140 EnclosingDecl->setInvalidDecl(); 9141 continue; 9142 } 9143 if (!FD->getType()->isDependentType() && 9144 !Context.getBaseElementType(FD->getType()).isPODType(Context)) { 9145 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type) 9146 << FD->getDeclName() << FD->getType(); 9147 FD->setInvalidDecl(); 9148 EnclosingDecl->setInvalidDecl(); 9149 continue; 9150 } 9151 // Okay, we have a legal flexible array member at the end of the struct. 9152 if (Record) 9153 Record->setHasFlexibleArrayMember(true); 9154 } else if (!FDTy->isDependentType() && 9155 RequireCompleteType(FD->getLocation(), FD->getType(), 9156 diag::err_field_incomplete)) { 9157 // Incomplete type 9158 FD->setInvalidDecl(); 9159 EnclosingDecl->setInvalidDecl(); 9160 continue; 9161 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 9162 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 9163 // If this is a member of a union, then entire union becomes "flexible". 9164 if (Record && Record->isUnion()) { 9165 Record->setHasFlexibleArrayMember(true); 9166 } else { 9167 // If this is a struct/class and this is not the last element, reject 9168 // it. Note that GCC supports variable sized arrays in the middle of 9169 // structures. 9170 if (i + 1 != Fields.end()) 9171 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 9172 << FD->getDeclName() << FD->getType(); 9173 else { 9174 // We support flexible arrays at the end of structs in 9175 // other structs as an extension. 9176 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 9177 << FD->getDeclName(); 9178 if (Record) 9179 Record->setHasFlexibleArrayMember(true); 9180 } 9181 } 9182 } 9183 if (Record && FDTTy->getDecl()->hasObjectMember()) 9184 Record->setHasObjectMember(true); 9185 } else if (FDTy->isObjCObjectType()) { 9186 /// A field cannot be an Objective-c object 9187 Diag(FD->getLocation(), diag::err_statically_allocated_object) 9188 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 9189 QualType T = Context.getObjCObjectPointerType(FD->getType()); 9190 FD->setType(T); 9191 } 9192 else if (!getLangOptions().CPlusPlus) { 9193 if (getLangOptions().ObjCAutoRefCount && Record && !ARCErrReported) { 9194 // It's an error in ARC if a field has lifetime. 9195 // We don't want to report this in a system header, though, 9196 // so we just make the field unavailable. 9197 // FIXME: that's really not sufficient; we need to make the type 9198 // itself invalid to, say, initialize or copy. 9199 QualType T = FD->getType(); 9200 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 9201 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 9202 SourceLocation loc = FD->getLocation(); 9203 if (getSourceManager().isInSystemHeader(loc)) { 9204 if (!FD->hasAttr<UnavailableAttr>()) { 9205 FD->addAttr(new (Context) UnavailableAttr(loc, Context, 9206 "this system field has retaining ownership")); 9207 } 9208 } else { 9209 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct); 9210 } 9211 ARCErrReported = true; 9212 } 9213 } 9214 else if (getLangOptions().ObjC1 && 9215 getLangOptions().getGC() != LangOptions::NonGC && 9216 Record && !Record->hasObjectMember()) { 9217 if (FD->getType()->isObjCObjectPointerType() || 9218 FD->getType().isObjCGCStrong()) 9219 Record->setHasObjectMember(true); 9220 else if (Context.getAsArrayType(FD->getType())) { 9221 QualType BaseType = Context.getBaseElementType(FD->getType()); 9222 if (BaseType->isRecordType() && 9223 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 9224 Record->setHasObjectMember(true); 9225 else if (BaseType->isObjCObjectPointerType() || 9226 BaseType.isObjCGCStrong()) 9227 Record->setHasObjectMember(true); 9228 } 9229 } 9230 } 9231 // Keep track of the number of named members. 9232 if (FD->getIdentifier()) 9233 ++NumNamedMembers; 9234 } 9235 9236 // Okay, we successfully defined 'Record'. 9237 if (Record) { 9238 bool Completed = false; 9239 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 9240 if (!CXXRecord->isInvalidDecl()) { 9241 // Set access bits correctly on the directly-declared conversions. 9242 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions(); 9243 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); 9244 I != E; ++I) 9245 Convs->setAccess(I, (*I)->getAccess()); 9246 9247 if (!CXXRecord->isDependentType()) { 9248 // Objective-C Automatic Reference Counting: 9249 // If a class has a non-static data member of Objective-C pointer 9250 // type (or array thereof), it is a non-POD type and its 9251 // default constructor (if any), copy constructor, copy assignment 9252 // operator, and destructor are non-trivial. 9253 // 9254 // This rule is also handled by CXXRecordDecl::completeDefinition(). 9255 // However, here we check whether this particular class is only 9256 // non-POD because of the presence of an Objective-C pointer member. 9257 // If so, objects of this type cannot be shared between code compiled 9258 // with instant objects and code compiled with manual retain/release. 9259 if (getLangOptions().ObjCAutoRefCount && 9260 CXXRecord->hasObjectMember() && 9261 CXXRecord->getLinkage() == ExternalLinkage) { 9262 if (CXXRecord->isPOD()) { 9263 Diag(CXXRecord->getLocation(), 9264 diag::warn_arc_non_pod_class_with_object_member) 9265 << CXXRecord; 9266 } else { 9267 // FIXME: Fix-Its would be nice here, but finding a good location 9268 // for them is going to be tricky. 9269 if (CXXRecord->hasTrivialCopyConstructor()) 9270 Diag(CXXRecord->getLocation(), 9271 diag::warn_arc_trivial_member_function_with_object_member) 9272 << CXXRecord << 0; 9273 if (CXXRecord->hasTrivialCopyAssignment()) 9274 Diag(CXXRecord->getLocation(), 9275 diag::warn_arc_trivial_member_function_with_object_member) 9276 << CXXRecord << 1; 9277 if (CXXRecord->hasTrivialDestructor()) 9278 Diag(CXXRecord->getLocation(), 9279 diag::warn_arc_trivial_member_function_with_object_member) 9280 << CXXRecord << 2; 9281 } 9282 } 9283 9284 // Adjust user-defined destructor exception spec. 9285 if (getLangOptions().CPlusPlus0x && 9286 CXXRecord->hasUserDeclaredDestructor()) 9287 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor()); 9288 9289 // Add any implicitly-declared members to this class. 9290 AddImplicitlyDeclaredMembersToClass(CXXRecord); 9291 9292 // If we have virtual base classes, we may end up finding multiple 9293 // final overriders for a given virtual function. Check for this 9294 // problem now. 9295 if (CXXRecord->getNumVBases()) { 9296 CXXFinalOverriderMap FinalOverriders; 9297 CXXRecord->getFinalOverriders(FinalOverriders); 9298 9299 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 9300 MEnd = FinalOverriders.end(); 9301 M != MEnd; ++M) { 9302 for (OverridingMethods::iterator SO = M->second.begin(), 9303 SOEnd = M->second.end(); 9304 SO != SOEnd; ++SO) { 9305 assert(SO->second.size() > 0 && 9306 "Virtual function without overridding functions?"); 9307 if (SO->second.size() == 1) 9308 continue; 9309 9310 // C++ [class.virtual]p2: 9311 // In a derived class, if a virtual member function of a base 9312 // class subobject has more than one final overrider the 9313 // program is ill-formed. 9314 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 9315 << (NamedDecl *)M->first << Record; 9316 Diag(M->first->getLocation(), 9317 diag::note_overridden_virtual_function); 9318 for (OverridingMethods::overriding_iterator 9319 OM = SO->second.begin(), 9320 OMEnd = SO->second.end(); 9321 OM != OMEnd; ++OM) 9322 Diag(OM->Method->getLocation(), diag::note_final_overrider) 9323 << (NamedDecl *)M->first << OM->Method->getParent(); 9324 9325 Record->setInvalidDecl(); 9326 } 9327 } 9328 CXXRecord->completeDefinition(&FinalOverriders); 9329 Completed = true; 9330 } 9331 } 9332 } 9333 } 9334 9335 if (!Completed) 9336 Record->completeDefinition(); 9337 9338 // Now that the record is complete, do any delayed exception spec checks 9339 // we were missing. 9340 while (!DelayedDestructorExceptionSpecChecks.empty()) { 9341 const CXXDestructorDecl *Dtor = 9342 DelayedDestructorExceptionSpecChecks.back().first; 9343 if (Dtor->getParent() != Record) 9344 break; 9345 9346 assert(!Dtor->getParent()->isDependentType() && 9347 "Should not ever add destructors of templates into the list."); 9348 CheckOverridingFunctionExceptionSpec(Dtor, 9349 DelayedDestructorExceptionSpecChecks.back().second); 9350 DelayedDestructorExceptionSpecChecks.pop_back(); 9351 } 9352 9353 } else { 9354 ObjCIvarDecl **ClsFields = 9355 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 9356 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 9357 ID->setLocEnd(RBrac); 9358 // Add ivar's to class's DeclContext. 9359 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 9360 ClsFields[i]->setLexicalDeclContext(ID); 9361 ID->addDecl(ClsFields[i]); 9362 } 9363 // Must enforce the rule that ivars in the base classes may not be 9364 // duplicates. 9365 if (ID->getSuperClass()) 9366 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 9367 } else if (ObjCImplementationDecl *IMPDecl = 9368 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 9369 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 9370 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 9371 // Ivar declared in @implementation never belongs to the implementation. 9372 // Only it is in implementation's lexical context. 9373 ClsFields[I]->setLexicalDeclContext(IMPDecl); 9374 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 9375 } else if (ObjCCategoryDecl *CDecl = 9376 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 9377 // case of ivars in class extension; all other cases have been 9378 // reported as errors elsewhere. 9379 // FIXME. Class extension does not have a LocEnd field. 9380 // CDecl->setLocEnd(RBrac); 9381 // Add ivar's to class extension's DeclContext. 9382 // Diagnose redeclaration of private ivars. 9383 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 9384 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 9385 if (IDecl) { 9386 if (const ObjCIvarDecl *ClsIvar = 9387 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 9388 Diag(ClsFields[i]->getLocation(), 9389 diag::err_duplicate_ivar_declaration); 9390 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 9391 continue; 9392 } 9393 for (const ObjCCategoryDecl *ClsExtDecl = 9394 IDecl->getFirstClassExtension(); 9395 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) { 9396 if (const ObjCIvarDecl *ClsExtIvar = 9397 ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 9398 Diag(ClsFields[i]->getLocation(), 9399 diag::err_duplicate_ivar_declaration); 9400 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 9401 continue; 9402 } 9403 } 9404 } 9405 ClsFields[i]->setLexicalDeclContext(CDecl); 9406 CDecl->addDecl(ClsFields[i]); 9407 } 9408 } 9409 } 9410 9411 if (Attr) 9412 ProcessDeclAttributeList(S, Record, Attr); 9413 9414 // If there's a #pragma GCC visibility in scope, and this isn't a subclass, 9415 // set the visibility of this record. 9416 if (Record && !Record->getDeclContext()->isRecord()) 9417 AddPushedVisibilityAttribute(Record); 9418} 9419 9420/// \brief Determine whether the given integral value is representable within 9421/// the given type T. 9422static bool isRepresentableIntegerValue(ASTContext &Context, 9423 llvm::APSInt &Value, 9424 QualType T) { 9425 assert(T->isIntegralType(Context) && "Integral type required!"); 9426 unsigned BitWidth = Context.getIntWidth(T); 9427 9428 if (Value.isUnsigned() || Value.isNonNegative()) { 9429 if (T->isSignedIntegerOrEnumerationType()) 9430 --BitWidth; 9431 return Value.getActiveBits() <= BitWidth; 9432 } 9433 return Value.getMinSignedBits() <= BitWidth; 9434} 9435 9436// \brief Given an integral type, return the next larger integral type 9437// (or a NULL type of no such type exists). 9438static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 9439 // FIXME: Int128/UInt128 support, which also needs to be introduced into 9440 // enum checking below. 9441 assert(T->isIntegralType(Context) && "Integral type required!"); 9442 const unsigned NumTypes = 4; 9443 QualType SignedIntegralTypes[NumTypes] = { 9444 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 9445 }; 9446 QualType UnsignedIntegralTypes[NumTypes] = { 9447 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 9448 Context.UnsignedLongLongTy 9449 }; 9450 9451 unsigned BitWidth = Context.getTypeSize(T); 9452 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 9453 : UnsignedIntegralTypes; 9454 for (unsigned I = 0; I != NumTypes; ++I) 9455 if (Context.getTypeSize(Types[I]) > BitWidth) 9456 return Types[I]; 9457 9458 return QualType(); 9459} 9460 9461EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 9462 EnumConstantDecl *LastEnumConst, 9463 SourceLocation IdLoc, 9464 IdentifierInfo *Id, 9465 Expr *Val) { 9466 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 9467 llvm::APSInt EnumVal(IntWidth); 9468 QualType EltTy; 9469 9470 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 9471 Val = 0; 9472 9473 if (Val) 9474 Val = DefaultLvalueConversion(Val).take(); 9475 9476 if (Val) { 9477 if (Enum->isDependentType() || Val->isTypeDependent()) 9478 EltTy = Context.DependentTy; 9479 else { 9480 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 9481 SourceLocation ExpLoc; 9482 if (!Val->isValueDependent() && 9483 VerifyIntegerConstantExpression(Val, &EnumVal)) { 9484 Val = 0; 9485 } else { 9486 if (!getLangOptions().CPlusPlus) { 9487 // C99 6.7.2.2p2: 9488 // The expression that defines the value of an enumeration constant 9489 // shall be an integer constant expression that has a value 9490 // representable as an int. 9491 9492 // Complain if the value is not representable in an int. 9493 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 9494 Diag(IdLoc, diag::ext_enum_value_not_int) 9495 << EnumVal.toString(10) << Val->getSourceRange() 9496 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 9497 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 9498 // Force the type of the expression to 'int'. 9499 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 9500 } 9501 } 9502 9503 if (Enum->isFixed()) { 9504 EltTy = Enum->getIntegerType(); 9505 9506 // C++0x [dcl.enum]p5: 9507 // ... if the initializing value of an enumerator cannot be 9508 // represented by the underlying type, the program is ill-formed. 9509 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 9510 if (getLangOptions().MicrosoftExt) { 9511 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 9512 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 9513 } else 9514 Diag(IdLoc, diag::err_enumerator_too_large) 9515 << EltTy; 9516 } else 9517 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 9518 } 9519 else { 9520 // C++0x [dcl.enum]p5: 9521 // If the underlying type is not fixed, the type of each enumerator 9522 // is the type of its initializing value: 9523 // - If an initializer is specified for an enumerator, the 9524 // initializing value has the same type as the expression. 9525 EltTy = Val->getType(); 9526 } 9527 } 9528 } 9529 } 9530 9531 if (!Val) { 9532 if (Enum->isDependentType()) 9533 EltTy = Context.DependentTy; 9534 else if (!LastEnumConst) { 9535 // C++0x [dcl.enum]p5: 9536 // If the underlying type is not fixed, the type of each enumerator 9537 // is the type of its initializing value: 9538 // - If no initializer is specified for the first enumerator, the 9539 // initializing value has an unspecified integral type. 9540 // 9541 // GCC uses 'int' for its unspecified integral type, as does 9542 // C99 6.7.2.2p3. 9543 if (Enum->isFixed()) { 9544 EltTy = Enum->getIntegerType(); 9545 } 9546 else { 9547 EltTy = Context.IntTy; 9548 } 9549 } else { 9550 // Assign the last value + 1. 9551 EnumVal = LastEnumConst->getInitVal(); 9552 ++EnumVal; 9553 EltTy = LastEnumConst->getType(); 9554 9555 // Check for overflow on increment. 9556 if (EnumVal < LastEnumConst->getInitVal()) { 9557 // C++0x [dcl.enum]p5: 9558 // If the underlying type is not fixed, the type of each enumerator 9559 // is the type of its initializing value: 9560 // 9561 // - Otherwise the type of the initializing value is the same as 9562 // the type of the initializing value of the preceding enumerator 9563 // unless the incremented value is not representable in that type, 9564 // in which case the type is an unspecified integral type 9565 // sufficient to contain the incremented value. If no such type 9566 // exists, the program is ill-formed. 9567 QualType T = getNextLargerIntegralType(Context, EltTy); 9568 if (T.isNull() || Enum->isFixed()) { 9569 // There is no integral type larger enough to represent this 9570 // value. Complain, then allow the value to wrap around. 9571 EnumVal = LastEnumConst->getInitVal(); 9572 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 9573 ++EnumVal; 9574 if (Enum->isFixed()) 9575 // When the underlying type is fixed, this is ill-formed. 9576 Diag(IdLoc, diag::err_enumerator_wrapped) 9577 << EnumVal.toString(10) 9578 << EltTy; 9579 else 9580 Diag(IdLoc, diag::warn_enumerator_too_large) 9581 << EnumVal.toString(10); 9582 } else { 9583 EltTy = T; 9584 } 9585 9586 // Retrieve the last enumerator's value, extent that type to the 9587 // type that is supposed to be large enough to represent the incremented 9588 // value, then increment. 9589 EnumVal = LastEnumConst->getInitVal(); 9590 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 9591 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 9592 ++EnumVal; 9593 9594 // If we're not in C++, diagnose the overflow of enumerator values, 9595 // which in C99 means that the enumerator value is not representable in 9596 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 9597 // permits enumerator values that are representable in some larger 9598 // integral type. 9599 if (!getLangOptions().CPlusPlus && !T.isNull()) 9600 Diag(IdLoc, diag::warn_enum_value_overflow); 9601 } else if (!getLangOptions().CPlusPlus && 9602 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 9603 // Enforce C99 6.7.2.2p2 even when we compute the next value. 9604 Diag(IdLoc, diag::ext_enum_value_not_int) 9605 << EnumVal.toString(10) << 1; 9606 } 9607 } 9608 } 9609 9610 if (!EltTy->isDependentType()) { 9611 // Make the enumerator value match the signedness and size of the 9612 // enumerator's type. 9613 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 9614 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 9615 } 9616 9617 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 9618 Val, EnumVal); 9619} 9620 9621 9622Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 9623 SourceLocation IdLoc, IdentifierInfo *Id, 9624 AttributeList *Attr, 9625 SourceLocation EqualLoc, Expr *val) { 9626 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 9627 EnumConstantDecl *LastEnumConst = 9628 cast_or_null<EnumConstantDecl>(lastEnumConst); 9629 Expr *Val = static_cast<Expr*>(val); 9630 9631 // The scope passed in may not be a decl scope. Zip up the scope tree until 9632 // we find one that is. 9633 S = getNonFieldDeclScope(S); 9634 9635 // Verify that there isn't already something declared with this name in this 9636 // scope. 9637 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 9638 ForRedeclaration); 9639 if (PrevDecl && PrevDecl->isTemplateParameter()) { 9640 // Maybe we will complain about the shadowed template parameter. 9641 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 9642 // Just pretend that we didn't see the previous declaration. 9643 PrevDecl = 0; 9644 } 9645 9646 if (PrevDecl) { 9647 // When in C++, we may get a TagDecl with the same name; in this case the 9648 // enum constant will 'hide' the tag. 9649 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 9650 "Received TagDecl when not in C++!"); 9651 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 9652 if (isa<EnumConstantDecl>(PrevDecl)) 9653 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 9654 else 9655 Diag(IdLoc, diag::err_redefinition) << Id; 9656 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 9657 return 0; 9658 } 9659 } 9660 9661 // C++ [class.mem]p13: 9662 // If T is the name of a class, then each of the following shall have a 9663 // name different from T: 9664 // - every enumerator of every member of class T that is an enumerated 9665 // type 9666 if (CXXRecordDecl *Record 9667 = dyn_cast<CXXRecordDecl>( 9668 TheEnumDecl->getDeclContext()->getRedeclContext())) 9669 if (Record->getIdentifier() && Record->getIdentifier() == Id) 9670 Diag(IdLoc, diag::err_member_name_of_class) << Id; 9671 9672 EnumConstantDecl *New = 9673 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 9674 9675 if (New) { 9676 // Process attributes. 9677 if (Attr) ProcessDeclAttributeList(S, New, Attr); 9678 9679 // Register this decl in the current scope stack. 9680 New->setAccess(TheEnumDecl->getAccess()); 9681 PushOnScopeChains(New, S); 9682 } 9683 9684 return New; 9685} 9686 9687void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 9688 SourceLocation RBraceLoc, Decl *EnumDeclX, 9689 Decl **Elements, unsigned NumElements, 9690 Scope *S, AttributeList *Attr) { 9691 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 9692 QualType EnumType = Context.getTypeDeclType(Enum); 9693 9694 if (Attr) 9695 ProcessDeclAttributeList(S, Enum, Attr); 9696 9697 if (Enum->isDependentType()) { 9698 for (unsigned i = 0; i != NumElements; ++i) { 9699 EnumConstantDecl *ECD = 9700 cast_or_null<EnumConstantDecl>(Elements[i]); 9701 if (!ECD) continue; 9702 9703 ECD->setType(EnumType); 9704 } 9705 9706 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 9707 return; 9708 } 9709 9710 // TODO: If the result value doesn't fit in an int, it must be a long or long 9711 // long value. ISO C does not support this, but GCC does as an extension, 9712 // emit a warning. 9713 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 9714 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 9715 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 9716 9717 // Verify that all the values are okay, compute the size of the values, and 9718 // reverse the list. 9719 unsigned NumNegativeBits = 0; 9720 unsigned NumPositiveBits = 0; 9721 9722 // Keep track of whether all elements have type int. 9723 bool AllElementsInt = true; 9724 9725 for (unsigned i = 0; i != NumElements; ++i) { 9726 EnumConstantDecl *ECD = 9727 cast_or_null<EnumConstantDecl>(Elements[i]); 9728 if (!ECD) continue; // Already issued a diagnostic. 9729 9730 const llvm::APSInt &InitVal = ECD->getInitVal(); 9731 9732 // Keep track of the size of positive and negative values. 9733 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 9734 NumPositiveBits = std::max(NumPositiveBits, 9735 (unsigned)InitVal.getActiveBits()); 9736 else 9737 NumNegativeBits = std::max(NumNegativeBits, 9738 (unsigned)InitVal.getMinSignedBits()); 9739 9740 // Keep track of whether every enum element has type int (very commmon). 9741 if (AllElementsInt) 9742 AllElementsInt = ECD->getType() == Context.IntTy; 9743 } 9744 9745 // Figure out the type that should be used for this enum. 9746 QualType BestType; 9747 unsigned BestWidth; 9748 9749 // C++0x N3000 [conv.prom]p3: 9750 // An rvalue of an unscoped enumeration type whose underlying 9751 // type is not fixed can be converted to an rvalue of the first 9752 // of the following types that can represent all the values of 9753 // the enumeration: int, unsigned int, long int, unsigned long 9754 // int, long long int, or unsigned long long int. 9755 // C99 6.4.4.3p2: 9756 // An identifier declared as an enumeration constant has type int. 9757 // The C99 rule is modified by a gcc extension 9758 QualType BestPromotionType; 9759 9760 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 9761 // -fshort-enums is the equivalent to specifying the packed attribute on all 9762 // enum definitions. 9763 if (LangOpts.ShortEnums) 9764 Packed = true; 9765 9766 if (Enum->isFixed()) { 9767 BestType = Enum->getIntegerType(); 9768 if (BestType->isPromotableIntegerType()) 9769 BestPromotionType = Context.getPromotedIntegerType(BestType); 9770 else 9771 BestPromotionType = BestType; 9772 // We don't need to set BestWidth, because BestType is going to be the type 9773 // of the enumerators, but we do anyway because otherwise some compilers 9774 // warn that it might be used uninitialized. 9775 BestWidth = CharWidth; 9776 } 9777 else if (NumNegativeBits) { 9778 // If there is a negative value, figure out the smallest integer type (of 9779 // int/long/longlong) that fits. 9780 // If it's packed, check also if it fits a char or a short. 9781 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 9782 BestType = Context.SignedCharTy; 9783 BestWidth = CharWidth; 9784 } else if (Packed && NumNegativeBits <= ShortWidth && 9785 NumPositiveBits < ShortWidth) { 9786 BestType = Context.ShortTy; 9787 BestWidth = ShortWidth; 9788 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 9789 BestType = Context.IntTy; 9790 BestWidth = IntWidth; 9791 } else { 9792 BestWidth = Context.getTargetInfo().getLongWidth(); 9793 9794 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 9795 BestType = Context.LongTy; 9796 } else { 9797 BestWidth = Context.getTargetInfo().getLongLongWidth(); 9798 9799 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 9800 Diag(Enum->getLocation(), diag::warn_enum_too_large); 9801 BestType = Context.LongLongTy; 9802 } 9803 } 9804 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 9805 } else { 9806 // If there is no negative value, figure out the smallest type that fits 9807 // all of the enumerator values. 9808 // If it's packed, check also if it fits a char or a short. 9809 if (Packed && NumPositiveBits <= CharWidth) { 9810 BestType = Context.UnsignedCharTy; 9811 BestPromotionType = Context.IntTy; 9812 BestWidth = CharWidth; 9813 } else if (Packed && NumPositiveBits <= ShortWidth) { 9814 BestType = Context.UnsignedShortTy; 9815 BestPromotionType = Context.IntTy; 9816 BestWidth = ShortWidth; 9817 } else if (NumPositiveBits <= IntWidth) { 9818 BestType = Context.UnsignedIntTy; 9819 BestWidth = IntWidth; 9820 BestPromotionType 9821 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 9822 ? Context.UnsignedIntTy : Context.IntTy; 9823 } else if (NumPositiveBits <= 9824 (BestWidth = Context.getTargetInfo().getLongWidth())) { 9825 BestType = Context.UnsignedLongTy; 9826 BestPromotionType 9827 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 9828 ? Context.UnsignedLongTy : Context.LongTy; 9829 } else { 9830 BestWidth = Context.getTargetInfo().getLongLongWidth(); 9831 assert(NumPositiveBits <= BestWidth && 9832 "How could an initializer get larger than ULL?"); 9833 BestType = Context.UnsignedLongLongTy; 9834 BestPromotionType 9835 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 9836 ? Context.UnsignedLongLongTy : Context.LongLongTy; 9837 } 9838 } 9839 9840 // Loop over all of the enumerator constants, changing their types to match 9841 // the type of the enum if needed. 9842 for (unsigned i = 0; i != NumElements; ++i) { 9843 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 9844 if (!ECD) continue; // Already issued a diagnostic. 9845 9846 // Standard C says the enumerators have int type, but we allow, as an 9847 // extension, the enumerators to be larger than int size. If each 9848 // enumerator value fits in an int, type it as an int, otherwise type it the 9849 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 9850 // that X has type 'int', not 'unsigned'. 9851 9852 // Determine whether the value fits into an int. 9853 llvm::APSInt InitVal = ECD->getInitVal(); 9854 9855 // If it fits into an integer type, force it. Otherwise force it to match 9856 // the enum decl type. 9857 QualType NewTy; 9858 unsigned NewWidth; 9859 bool NewSign; 9860 if (!getLangOptions().CPlusPlus && 9861 !Enum->isFixed() && 9862 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 9863 NewTy = Context.IntTy; 9864 NewWidth = IntWidth; 9865 NewSign = true; 9866 } else if (ECD->getType() == BestType) { 9867 // Already the right type! 9868 if (getLangOptions().CPlusPlus) 9869 // C++ [dcl.enum]p4: Following the closing brace of an 9870 // enum-specifier, each enumerator has the type of its 9871 // enumeration. 9872 ECD->setType(EnumType); 9873 continue; 9874 } else { 9875 NewTy = BestType; 9876 NewWidth = BestWidth; 9877 NewSign = BestType->isSignedIntegerOrEnumerationType(); 9878 } 9879 9880 // Adjust the APSInt value. 9881 InitVal = InitVal.extOrTrunc(NewWidth); 9882 InitVal.setIsSigned(NewSign); 9883 ECD->setInitVal(InitVal); 9884 9885 // Adjust the Expr initializer and type. 9886 if (ECD->getInitExpr() && 9887 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 9888 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 9889 CK_IntegralCast, 9890 ECD->getInitExpr(), 9891 /*base paths*/ 0, 9892 VK_RValue)); 9893 if (getLangOptions().CPlusPlus) 9894 // C++ [dcl.enum]p4: Following the closing brace of an 9895 // enum-specifier, each enumerator has the type of its 9896 // enumeration. 9897 ECD->setType(EnumType); 9898 else 9899 ECD->setType(NewTy); 9900 } 9901 9902 Enum->completeDefinition(BestType, BestPromotionType, 9903 NumPositiveBits, NumNegativeBits); 9904} 9905 9906Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 9907 SourceLocation StartLoc, 9908 SourceLocation EndLoc) { 9909 StringLiteral *AsmString = cast<StringLiteral>(expr); 9910 9911 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 9912 AsmString, StartLoc, 9913 EndLoc); 9914 CurContext->addDecl(New); 9915 return New; 9916} 9917 9918DeclResult Sema::ActOnModuleImport(SourceLocation ImportLoc, ModuleIdPath Path) { 9919 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 9920 Module::AllVisible, 9921 /*IsIncludeDirective=*/false); 9922 if (!Mod) 9923 return true; 9924 9925 llvm::SmallVector<SourceLocation, 2> IdentifierLocs; 9926 Module *ModCheck = Mod; 9927 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 9928 // If we've run out of module parents, just drop the remaining identifiers. 9929 // We need the length to be consistent. 9930 if (!ModCheck) 9931 break; 9932 ModCheck = ModCheck->Parent; 9933 9934 IdentifierLocs.push_back(Path[I].second); 9935 } 9936 9937 ImportDecl *Import = ImportDecl::Create(Context, 9938 Context.getTranslationUnitDecl(), 9939 ImportLoc, Mod, 9940 IdentifierLocs); 9941 Context.getTranslationUnitDecl()->addDecl(Import); 9942 return Import; 9943} 9944 9945void 9946Sema::diagnoseModulePrivateRedeclaration(NamedDecl *New, NamedDecl *Old, 9947 SourceLocation ModulePrivateKeyword) { 9948 assert(!Old->isModulePrivate() && "Old is module-private!"); 9949 9950 Diag(New->getLocation(), diag::err_module_private_follows_public) 9951 << New->getDeclName() << SourceRange(ModulePrivateKeyword); 9952 Diag(Old->getLocation(), diag::note_previous_declaration) 9953 << Old->getDeclName(); 9954 9955 // Drop the __module_private__ from the new declaration, since it's invalid. 9956 New->setModulePrivate(false); 9957} 9958 9959void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 9960 SourceLocation PragmaLoc, 9961 SourceLocation NameLoc) { 9962 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 9963 9964 if (PrevDecl) { 9965 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context)); 9966 } else { 9967 (void)WeakUndeclaredIdentifiers.insert( 9968 std::pair<IdentifierInfo*,WeakInfo> 9969 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 9970 } 9971} 9972 9973void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 9974 IdentifierInfo* AliasName, 9975 SourceLocation PragmaLoc, 9976 SourceLocation NameLoc, 9977 SourceLocation AliasNameLoc) { 9978 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 9979 LookupOrdinaryName); 9980 WeakInfo W = WeakInfo(Name, NameLoc); 9981 9982 if (PrevDecl) { 9983 if (!PrevDecl->hasAttr<AliasAttr>()) 9984 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 9985 DeclApplyPragmaWeak(TUScope, ND, W); 9986 } else { 9987 (void)WeakUndeclaredIdentifiers.insert( 9988 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 9989 } 9990} 9991 9992Decl *Sema::getObjCDeclContext() const { 9993 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 9994} 9995 9996AvailabilityResult Sema::getCurContextAvailability() const { 9997 const Decl *D = cast<Decl>(getCurLexicalContext()); 9998 // A category implicitly has the availability of the interface. 9999 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D)) 10000 D = CatD->getClassInterface(); 10001 10002 return D->getAvailability(); 10003} 10004