Newer
Older
//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for declarations.
//
//===----------------------------------------------------------------------===//
Chris Lattner
committed
#include "Sema.h"
Anders Carlsson
committed
#include "clang/AST/APValue.h"
#include "clang/AST/ASTConsumer.h"
Chris Lattner
committed
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/ExprCXX.h"
#include "clang/Parse/DeclSpec.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/SourceManager.h"
// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
#include "clang/Lex/Preprocessor.h"
#include "llvm/ADT/STLExtras.h"
#include <algorithm>
#include <functional>
using namespace clang;
Chris Lattner
committed
/// getDeclName - Return a pretty name for the specified decl if possible, or
/// an empty string if not. This is used for pretty crash reporting.
Chris Lattner
committed
std::string Sema::getDeclName(DeclPtrTy d) {
Decl *D = d.getAs<Decl>();
Chris Lattner
committed
if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
return DN->getQualifiedNameAsString();
return "";
}
Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
}
/// \brief If the identifier refers to a type name within this scope,
/// return the declaration of that type.
///
/// This routine performs ordinary name lookup of the identifier II
/// within the given scope, with optional C++ scope specifier SS, to
/// determine whether the name refers to a type. If so, returns an
/// opaque pointer (actually a QualType) corresponding to that
/// type. Otherwise, returns NULL.
///
/// If name lookup results in an ambiguity, this routine will complain
/// and then return NULL.
Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
Douglas Gregor
committed
Scope *S, const CXXScopeSpec *SS) {
// C++ [temp.res]p3:
// A qualified-id that refers to a type and in which the
// nested-name-specifier depends on a template-parameter (14.6.2)
// shall be prefixed by the keyword typename to indicate that the
// qualified-id denotes a type, forming an
// elaborated-type-specifier (7.1.5.3).
//
// We therefore do not perform any name lookup up SS is a dependent
// scope name. FIXME: we will need to perform a special kind of
// lookup if the scope specifier names a member of the current
// instantiation.
if (SS && isDependentScopeSpecifier(*SS))
return 0;
LookupResult Result = LookupParsedName(S, SS, &II, LookupOrdinaryName,
false, false);
switch (Result.getKind()) {
case LookupResult::NotFound:
case LookupResult::FoundOverloaded:
return 0;
Douglas Gregor
committed
case LookupResult::AmbiguousBaseSubobjectTypes:
case LookupResult::AmbiguousBaseSubobjects:
case LookupResult::AmbiguousReference: {
// Look to see if we have a type anywhere in the list of results.
for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
Res != ResEnd; ++Res) {
if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
if (!IIDecl ||
(*Res)->getLocation().getRawEncoding() <
IIDecl->getLocation().getRawEncoding())
IIDecl = *Res;
}
}
if (!IIDecl) {
// None of the entities we found is a type, so there is no way
// to even assume that the result is a type. In this case, don't
// complain about the ambiguity. The parser will either try to
// perform this lookup again (e.g., as an object name), which
// will produce the ambiguity, or will complain that it expected
// a type name.
Result.Destroy();
return 0;
}
// We found a type within the ambiguous lookup; diagnose the
// ambiguity and then return that type. This might be the right
// answer, or it might not be, but it suppresses any attempt to
// perform the name lookup again.
DiagnoseAmbiguousLookup(Result, DeclarationName(&II), NameLoc);
break;
}
Douglas Gregor
committed
case LookupResult::Found:
IIDecl = Result.getAsDecl();
break;
Steve Naroff
committed
if (IIDecl) {
QualType T;
if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
// Check whether we can use this type
(void)DiagnoseUseOfDecl(IIDecl, NameLoc);
T = Context.getTypeDeclType(TD);
} else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
// Check whether we can use this interface.
(void)DiagnoseUseOfDecl(IIDecl, NameLoc);
T = Context.getObjCInterfaceType(IDecl);
} else
return 0;
if (SS)
T = getQualifiedNameType(*SS, T);
return T.getAsOpaquePtr();
Steve Naroff
committed
}
Chris Lattner
committed
}
/// isTagName() - This method is called *for error recovery purposes only*
/// to determine if the specified name is a valid tag name ("struct foo"). If
/// so, this returns the TST for the tag corresponding to it (TST_enum,
/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
/// where the user forgot to specify the tag.
DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
// Do a tag name lookup in this scope.
LookupResult R = LookupName(S, &II, LookupTagName, false, false);
if (R.getKind() == LookupResult::Found)
if (const TagDecl *TD = dyn_cast<TagDecl>(R.getAsDecl())) {
switch (TD->getTagKind()) {
case TagDecl::TK_struct: return DeclSpec::TST_struct;
case TagDecl::TK_union: return DeclSpec::TST_union;
case TagDecl::TK_class: return DeclSpec::TST_class;
case TagDecl::TK_enum: return DeclSpec::TST_enum;
}
}
return DeclSpec::TST_unspecified;
}
DeclContext *Sema::getContainingDC(DeclContext *DC) {
if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
// A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis
committed
if (MD->isOutOfLineDefinition())
return MD->getLexicalDeclContext();
// A C++ inline method is parsed *after* the topmost class it was declared
// in is fully parsed (it's "complete").
// The parsing of a C++ inline method happens at the declaration context of
// the topmost (non-nested) class it is lexically declared in.
assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
DC = MD->getParent();
while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
DC = RD;
// Return the declaration context of the topmost class the inline method is
// declared in.
return DC;
}
Argyrios Kyrtzidis
committed
if (isa<ObjCMethodDecl>(DC))
return Context.getTranslationUnitDecl();
void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
assert(getContainingDC(DC) == CurContext &&
"The next DeclContext should be lexically contained in the current one.");
S->setEntity(DC);
void Sema::PopDeclContext() {
assert(CurContext && "DeclContext imbalance!");
CurContext = getContainingDC(CurContext);
/// \brief Determine whether we allow overloading of the function
/// PrevDecl with another declaration.
///
/// This routine determines whether overloading is possible, not
/// whether some new function is actually an overload. It will return
/// true in C++ (where we can always provide overloads) or, as an
/// extension, in C when the previous function is already an
/// overloaded function declaration or has the "overloadable"
/// attribute.
static bool AllowOverloadingOfFunction(Decl *PrevDecl, ASTContext &Context) {
if (Context.getLangOptions().CPlusPlus)
return true;
if (isa<OverloadedFunctionDecl>(PrevDecl))
return true;
return PrevDecl->getAttr<OverloadableAttr>() != 0;
}
Argyrios Kyrtzidis
committed
/// Add this decl to the scope shadowed decl chains.
void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
// Move up the scope chain until we find the nearest enclosing
// non-transparent context. The declaration will be introduced into this
// scope.
while (S->getEntity() &&
((DeclContext *)S->getEntity())->isTransparentContext())
S = S->getParent();
Chris Lattner
committed
S->AddDecl(DeclPtrTy::make(D));
// Add scoped declarations into their context, so that they can be
// found later. Declarations without a context won't be inserted
// into any context.
CurContext->addDecl(Context, D);
// C++ [basic.scope]p4:
// -- exactly one declaration shall declare a class name or
// enumeration name that is not a typedef name and the other
// declarations shall all refer to the same object or
// enumerator, or all refer to functions and function templates;
// in this case the class name or enumeration name is hidden.
if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
// We are pushing the name of a tag (enum or class).
Douglas Gregor
committed
if (CurContext->getLookupContext()
== TD->getDeclContext()->getLookupContext()) {
// We're pushing the tag into the current context, which might
// require some reshuffling in the identifier resolver.
IdentifierResolver::iterator
I = IdResolver.begin(TD->getDeclName()),
IEnd = IdResolver.end();
if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
NamedDecl *PrevDecl = *I;
for (; I != IEnd && isDeclInScope(*I, CurContext, S);
PrevDecl = *I, ++I) {
if (TD->declarationReplaces(*I)) {
// This is a redeclaration. Remove it from the chain and
// break out, so that we'll add in the shadowed
// declaration.
Chris Lattner
committed
S->RemoveDecl(DeclPtrTy::make(*I));
if (PrevDecl == *I) {
IdResolver.RemoveDecl(*I);
IdResolver.AddDecl(TD);
return;
} else {
IdResolver.RemoveDecl(*I);
break;
}
}
}
// There is already a declaration with the same name in the same
// scope, which is not a tag declaration. It must be found
// before we find the new declaration, so insert the new
// declaration at the end of the chain.
IdResolver.AddShadowedDecl(TD, PrevDecl);
return;
} else if (isa<FunctionDecl>(D) &&
AllowOverloadingOfFunction(D, Context)) {
// We are pushing the name of a function, which might be an
// overloaded name.
FunctionDecl *FD = cast<FunctionDecl>(D);
IdentifierResolver::iterator Redecl
= std::find_if(IdResolver.begin(FD->getDeclName()),
IdResolver.end(),
std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
FD));
Chris Lattner
committed
if (Redecl != IdResolver.end() &&
S->isDeclScope(DeclPtrTy::make(*Redecl))) {
// There is already a declaration of a function on our
// IdResolver chain. Replace it with this declaration.
Chris Lattner
committed
S->RemoveDecl(DeclPtrTy::make(*Redecl));
IdResolver.RemoveDecl(*Redecl);
IdResolver.AddDecl(D);
Argyrios Kyrtzidis
committed
}
if (S->decl_empty()) return;
assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
"Scope shouldn't contain decls!");
for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
I != E; ++I) {
Chris Lattner
committed
Decl *TmpD = (*I).getAs<Decl>();
assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
NamedDecl *D = cast<NamedDecl>(TmpD);
if (!D->getDeclName()) continue;
// Remove this name from our lexical scope.
IdResolver.RemoveDecl(D);
Steve Naroff
committed
/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
/// return 0 if one not found.
ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
// The third "scope" argument is 0 since we aren't enabling lazy built-in
// creation from this context.
NamedDecl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName);
Fariborz Jahanian
committed
Fariborz Jahanian
committed
}
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/// getNonFieldDeclScope - Retrieves the innermost scope, starting
/// from S, where a non-field would be declared. This routine copes
/// with the difference between C and C++ scoping rules in structs and
/// unions. For example, the following code is well-formed in C but
/// ill-formed in C++:
/// @code
/// struct S6 {
/// enum { BAR } e;
/// };
///
/// void test_S6() {
/// struct S6 a;
/// a.e = BAR;
/// }
/// @endcode
/// For the declaration of BAR, this routine will return a different
/// scope. The scope S will be the scope of the unnamed enumeration
/// within S6. In C++, this routine will return the scope associated
/// with S6, because the enumeration's scope is a transparent
/// context but structures can contain non-field names. In C, this
/// routine will return the translation unit scope, since the
/// enumeration's scope is a transparent context and structures cannot
/// contain non-field names.
Scope *Sema::getNonFieldDeclScope(Scope *S) {
while (((S->getFlags() & Scope::DeclScope) == 0) ||
(S->getEntity() &&
((DeclContext *)S->getEntity())->isTransparentContext()) ||
(S->isClassScope() && !getLangOptions().CPlusPlus))
S = S->getParent();
return S;
}
void Sema::InitBuiltinVaListType() {
if (!Context.getBuiltinVaListType().isNull())
return;
IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
NamedDecl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName);
Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
}
/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
/// file scope. lazily create a decl for it. ForRedeclaration is true
/// if we're creating this built-in in anticipation of redeclaring the
/// built-in.
NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Scope *S, bool ForRedeclaration,
SourceLocation Loc) {
Builtin::ID BID = (Builtin::ID)bid;
if (Context.BuiltinInfo.hasVAListUse(BID))
InitBuiltinVaListType();
Builtin::Context::GetBuiltinTypeError Error;
QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context, Error);
switch (Error) {
case Builtin::Context::GE_None:
// Okay
break;
case Builtin::Context::GE_Missing_FILE:
if (ForRedeclaration)
Diag(Loc, diag::err_implicit_decl_requires_stdio)
<< Context.BuiltinInfo.GetName(BID);
return 0;
}
if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
Diag(Loc, diag::ext_implicit_lib_function_decl)
<< Context.BuiltinInfo.GetName(BID)
<< R;
Douglas Gregor
committed
if (Context.BuiltinInfo.getHeaderName(BID) &&
Diags.getDiagnosticMapping(diag::ext_implicit_lib_function_decl)
!= diag::MAP_IGNORE)
Diag(Loc, diag::note_please_include_header)
<< Context.BuiltinInfo.getHeaderName(BID)
<< Context.BuiltinInfo.GetName(BID);
}
FunctionDecl *New = FunctionDecl::Create(Context,
Context.getTranslationUnitDecl(),
Loc, II, R,
FunctionDecl::Extern, false,
/*hasPrototype=*/true);
New->setImplicit();
// Create Decl objects for each parameter, adding them to the
// FunctionDecl.
if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
llvm::SmallVector<ParmVarDecl*, 16> Params;
for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
FT->getArgType(i), VarDecl::None, 0));
Ted Kremenek
committed
New->setParams(Context, &Params[0], Params.size());
AddKnownFunctionAttributes(New);
// TUScope is the translation-unit scope to insert this function into.
Douglas Gregor
committed
// FIXME: This is hideous. We need to teach PushOnScopeChains to
// relate Scopes to DeclContexts, and probably eliminate CurContext
// entirely, but we're not there yet.
DeclContext *SavedContext = CurContext;
CurContext = Context.getTranslationUnitDecl();
PushOnScopeChains(New, TUScope);
Douglas Gregor
committed
CurContext = SavedContext;
return New;
}
/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
/// everything from the standard library is defined.
NamespaceDecl *Sema::GetStdNamespace() {
if (!StdNamespace) {
IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
DeclContext *Global = Context.getTranslationUnitDecl();
Decl *Std = LookupQualifiedName(Global, StdIdent, LookupNamespaceName);
StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
}
return StdNamespace;
}
/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
/// same name and scope as a previous declaration 'Old'. Figure out
/// how to resolve this situation, merging decls or emitting
/// diagnostics as appropriate. Returns true if there was an error,
/// false otherwise.
bool Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
bool objc_types = false;
// Allow multiple definitions for ObjC built-in typedefs.
// FIXME: Verify the underlying types are equivalent!
if (getLangOptions().ObjC1) {
const IdentifierInfo *TypeID = New->getIdentifier();
switch (TypeID->getLength()) {
default: break;
case 2:
if (!TypeID->isStr("id"))
break;
Context.setObjCIdType(New);
objc_types = true;
break;
case 5:
if (!TypeID->isStr("Class"))
break;
Context.setObjCClassType(New);
objc_types = true;
return false;
case 3:
if (!TypeID->isStr("SEL"))
break;
Context.setObjCSelType(New);
objc_types = true;
return false;
case 8:
if (!TypeID->isStr("Protocol"))
break;
Context.setObjCProtoType(New->getUnderlyingType());
objc_types = true;
return false;
}
// Fall through - the typedef name was not a builtin type.
}
// Verify the old decl was also a type.
TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
Diag(New->getLocation(), diag::err_redefinition_different_kind)
<< New->getDeclName();
if (!objc_types)
Diag(OldD->getLocation(), diag::note_previous_definition);
// Determine the "old" type we'll use for checking and diagnostics.
QualType OldType;
if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
OldType = OldTypedef->getUnderlyingType();
else
OldType = Context.getTypeDeclType(Old);
// If the typedef types are not identical, reject them in all languages and
// with any extensions enabled.
if (OldType != New->getUnderlyingType() &&
Context.getCanonicalType(OldType) !=
Context.getCanonicalType(New->getUnderlyingType())) {
Diag(New->getLocation(), diag::err_redefinition_different_typedef)
<< New->getUnderlyingType() << OldType;
if (!objc_types)
Diag(Old->getLocation(), diag::note_previous_definition);
}
if (objc_types) return false;
if (getLangOptions().Microsoft) return false;
// C++ [dcl.typedef]p2:
// In a given non-class scope, a typedef specifier can be used to
// redefine the name of any type declared in that scope to refer
// to the type to which it already refers.
if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
return false;
// In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
// Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
// *either* declaration is in a system header. The code below implements
// this adhoc compatibility rule. FIXME: The following code will not
// work properly when compiling ".i" files (containing preprocessed output).
if (PP.getDiagnostics().getSuppressSystemWarnings()) {
SourceManager &SrcMgr = Context.getSourceManager();
if (SrcMgr.isInSystemHeader(Old->getLocation()))
return false;
if (SrcMgr.isInSystemHeader(New->getLocation()))
return false;
Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Diag(Old->getLocation(), diag::note_previous_definition);
/// DeclhasAttr - returns true if decl Declaration already has the target
/// attribute.
static bool DeclHasAttr(const Decl *decl, const Attr *target) {
for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
if (attr->getKind() == target->getKind())
return true;
return false;
}
/// MergeAttributes - append attributes from the Old decl to the New one.
Chris Lattner
committed
static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
Attr *attr = const_cast<Attr*>(Old->getAttrs());
Chris Lattner
committed
Attr *tmp = attr;
attr = attr->getNext();
if (!DeclHasAttr(New, tmp) && tmp->isMerged()) {
tmp->setInherited(true);
New->addAttr(tmp);
tmp->setNext(0);
Chris Lattner
committed
tmp->Destroy(C);
/// Used in MergeFunctionDecl to keep track of function parameters in
/// C.
struct GNUCompatibleParamWarning {
ParmVarDecl *OldParm;
ParmVarDecl *NewParm;
QualType PromotedType;
};
/// MergeFunctionDecl - We just parsed a function 'New' from
/// declarator D which has the same name and scope as a previous
/// declaration 'Old'. Figure out how to resolve this situation,
/// merging decls or emitting diagnostics as appropriate.
///
/// In C++, New and Old must be declarations that are not
/// overloaded. Use IsOverload to determine whether New and Old are
/// overloaded, and to select the Old declaration that New should be
/// merged with.
///
/// Returns true if there was an error, false otherwise.
bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
assert(!isa<OverloadedFunctionDecl>(OldD) &&
"Cannot merge with an overloaded function declaration");
// Verify the old decl was also a function.
FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
if (!Old) {
Diag(New->getLocation(), diag::err_redefinition_different_kind)
<< New->getDeclName();
Diag(OldD->getLocation(), diag::note_previous_definition);
// Determine whether the previous declaration was a definition,
// implicit declaration, or a declaration.
diag::kind PrevDiag;
if (Old->isThisDeclarationADefinition())
PrevDiag = diag::note_previous_definition;
else if (Old->isImplicit())
PrevDiag = diag::note_previous_implicit_declaration;
else
PrevDiag = diag::note_previous_declaration;
QualType OldQType = Context.getCanonicalType(Old->getType());
QualType NewQType = Context.getCanonicalType(New->getType());
if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
New->getStorageClass() == FunctionDecl::Static &&
Old->getStorageClass() != FunctionDecl::Static) {
Diag(New->getLocation(), diag::err_static_non_static)
<< New;
Diag(Old->getLocation(), PrevDiag);
return true;
}
if (getLangOptions().CPlusPlus) {
// (C++98 13.1p2):
// Certain function declarations cannot be overloaded:
// -- Function declarations that differ only in the return type
// cannot be overloaded.
QualType OldReturnType
= cast<FunctionType>(OldQType.getTypePtr())->getResultType();
QualType NewReturnType
= cast<FunctionType>(NewQType.getTypePtr())->getResultType();
if (OldReturnType != NewReturnType) {
Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
}
const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
if (OldMethod && NewMethod &&
OldMethod->getLexicalDeclContext() ==
NewMethod->getLexicalDeclContext()) {
// -- Member function declarations with the same name and the
// same parameter types cannot be overloaded if any of them
// is a static member function declaration.
if (OldMethod->isStatic() || NewMethod->isStatic()) {
Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
// C++ [class.mem]p1:
// [...] A member shall not be declared twice in the
// member-specification, except that a nested class or member
// class template can be declared and then later defined.
unsigned NewDiag;
if (isa<CXXConstructorDecl>(OldMethod))
NewDiag = diag::err_constructor_redeclared;
else if (isa<CXXDestructorDecl>(NewMethod))
NewDiag = diag::err_destructor_redeclared;
else if (isa<CXXConversionDecl>(NewMethod))
NewDiag = diag::err_conv_function_redeclared;
else
NewDiag = diag::err_member_redeclared;
Diag(New->getLocation(), NewDiag);
Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
}
// (C++98 8.3.5p3):
// All declarations for a function shall agree exactly in both the
// return type and the parameter-type-list.
if (OldQType == NewQType)
return MergeCompatibleFunctionDecls(New, Old);
// Fall through for conflicting redeclarations and redefinitions.
// C: Function types need to be compatible, not identical. This handles
// duplicate function decls like "void f(int); void f(enum X);" properly.
if (!getLangOptions().CPlusPlus &&
Context.typesAreCompatible(OldQType, NewQType)) {
const FunctionType *OldFuncType = OldQType->getAsFunctionType();
const FunctionType *NewFuncType = NewQType->getAsFunctionType();
const FunctionProtoType *OldProto = 0;
if (isa<FunctionNoProtoType>(NewFuncType) &&
(OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
// The old declaration provided a function prototype, but the
// new declaration does not. Merge in the prototype.
llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
OldProto->arg_type_end());
NewQType = Context.getFunctionType(NewFuncType->getResultType(),
&ParamTypes[0], ParamTypes.size(),
OldProto->isVariadic(),
OldProto->getTypeQuals());
New->setType(NewQType);
New->setInheritedPrototype();
// Synthesize a parameter for each argument type.
llvm::SmallVector<ParmVarDecl*, 16> Params;
for (FunctionProtoType::arg_type_iterator
ParamType = OldProto->arg_type_begin(),
ParamEnd = OldProto->arg_type_end();
ParamType != ParamEnd; ++ParamType) {
ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
SourceLocation(), 0,
*ParamType, VarDecl::None,
0);
Param->setImplicit();
Params.push_back(Param);
}
New->setParams(Context, &Params[0], Params.size());
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
}
return MergeCompatibleFunctionDecls(New, Old);
}
// GNU C permits a K&R definition to follow a prototype declaration
// if the declared types of the parameters in the K&R definition
// match the types in the prototype declaration, even when the
// promoted types of the parameters from the K&R definition differ
// from the types in the prototype. GCC then keeps the types from
// the prototype.
if (!getLangOptions().CPlusPlus &&
!getLangOptions().NoExtensions &&
Old->hasPrototype() && !New->hasPrototype() &&
New->getType()->getAsFunctionProtoType() &&
Old->getNumParams() == New->getNumParams()) {
llvm::SmallVector<QualType, 16> ArgTypes;
llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
const FunctionProtoType *OldProto
= Old->getType()->getAsFunctionProtoType();
const FunctionProtoType *NewProto
= New->getType()->getAsFunctionProtoType();
// Determine whether this is the GNU C extension.
bool GNUCompatible =
Context.typesAreCompatible(OldProto->getResultType(),
NewProto->getResultType()) &&
(OldProto->isVariadic() == NewProto->isVariadic());
for (unsigned Idx = 0, End = Old->getNumParams();
GNUCompatible && Idx != End; ++Idx) {
ParmVarDecl *OldParm = Old->getParamDecl(Idx);
ParmVarDecl *NewParm = New->getParamDecl(Idx);
if (Context.typesAreCompatible(OldParm->getType(),
NewProto->getArgType(Idx))) {
ArgTypes.push_back(NewParm->getType());
} else if (Context.typesAreCompatible(OldParm->getType(),
NewParm->getType())) {
GNUCompatibleParamWarning Warn
= { OldParm, NewParm, NewProto->getArgType(Idx) };
Warnings.push_back(Warn);
ArgTypes.push_back(NewParm->getType());
} else
GNUCompatible = false;
}
if (GNUCompatible) {
for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
Diag(Warnings[Warn].NewParm->getLocation(),
diag::ext_param_promoted_not_compatible_with_prototype)
<< Warnings[Warn].PromotedType
<< Warnings[Warn].OldParm->getType();
Diag(Warnings[Warn].OldParm->getLocation(),
diag::note_previous_declaration);
}
New->setType(Context.getFunctionType(NewProto->getResultType(),
&ArgTypes[0], ArgTypes.size(),
NewProto->isVariadic(),
NewProto->getTypeQuals()));
return MergeCompatibleFunctionDecls(New, Old);
}
// Fall through to diagnose conflicting types.
// A function that has already been declared has been redeclared or defined
// with a different type- show appropriate diagnostic
if (unsigned BuiltinID = Old->getBuiltinID(Context)) {
// The user has declared a builtin function with an incompatible
// signature.
if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
// The function the user is redeclaring is a library-defined
// function like 'malloc' or 'printf'. Warn about the
// redeclaration, then pretend that we don't know about this
// library built-in.
Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
<< Old << Old->getType();
New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
Old->setInvalidDecl();
return false;
}
PrevDiag = diag::note_previous_builtin_declaration;
}
Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
/// \brief Completes the merge of two function declarations that are
/// known to be compatible.
///
/// This routine handles the merging of attributes and other
/// properties of function declarations form the old declaration to
/// the new declaration, once we know that New is in fact a
/// redeclaration of Old.
///
/// \returns false
bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
// Merge the attributes
Chris Lattner
committed
MergeAttributes(New, Old, Context);
// Merge the storage class.
New->setStorageClass(Old->getStorageClass());
// FIXME: need to implement inline semantics
// Merge "pure" flag.
if (Old->isPure())
New->setPure();
// Merge the "deleted" flag.
if (Old->isDeleted())
New->setDeleted();
if (getLangOptions().CPlusPlus)
return MergeCXXFunctionDecl(New, Old);
return false;
}
/// MergeVarDecl - We just parsed a variable 'New' which has the same name
/// and scope as a previous declaration 'Old'. Figure out how to resolve this
/// situation, merging decls or emitting diagnostics as appropriate.
///
/// Tentative definition rules (C99 6.9.2p2) are checked by
/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
/// definitions here, since the initializer hasn't been attached.
bool Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
// Verify the old decl was also a variable.
VarDecl *Old = dyn_cast<VarDecl>(OldD);
if (!Old) {
Diag(New->getLocation(), diag::err_redefinition_different_kind)
<< New->getDeclName();
Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner
committed
MergeAttributes(New, Old, Context);
// Merge the types
QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
if (MergedT.isNull()) {
Diag(New->getLocation(), diag::err_redefinition_different_type)
<< New->getDeclName();
Diag(Old->getLocation(), diag::note_previous_definition);
// C99 6.2.2p4: Check if we have a static decl followed by a non-static.
if (New->getStorageClass() == VarDecl::Static &&
(Old->getStorageClass() == VarDecl::None ||
Old->getStorageClass() == VarDecl::Extern)) {
Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Diag(Old->getLocation(), diag::note_previous_definition);
// C99 6.2.2p4:
// For an identifier declared with the storage-class specifier
// extern in a scope in which a prior declaration of that
// identifier is visible,23) if the prior declaration specifies
// internal or external linkage, the linkage of the identifier at
// the later declaration is the same as the linkage specified at
// the prior declaration. If no prior declaration is visible, or
// if the prior declaration specifies no linkage, then the
// identifier has external linkage.
if (New->hasExternalStorage() && Old->hasLinkage())
/* Okay */;
else if (New->getStorageClass() != VarDecl::Static &&
Old->getStorageClass() == VarDecl::Static) {
Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Diag(Old->getLocation(), diag::note_previous_definition);
// Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl() &&
// Don't complain about out-of-line definitions of static members.
!(Old->getLexicalDeclContext()->isRecord() &&
!New->getLexicalDeclContext()->isRecord())) {
Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Diag(Old->getLocation(), diag::note_previous_definition);
// Keep a chain of previous declarations.
New->setPreviousDeclaration(Old);
return false;
/// CheckParmsForFunctionDef - Check that the parameters of the given
/// function are appropriate for the definition of a function. This
/// takes care of any checks that cannot be performed on the
/// declaration itself, e.g., that the types of each of the function
/// parameters are complete.
bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
bool HasInvalidParm = false;
for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
ParmVarDecl *Param = FD->getParamDecl(p);
// C99 6.7.5.3p4: the parameters in a parameter type list in a
// function declarator that is part of a function definition of
// that function shall not have incomplete type.
//
// This is also C++ [dcl.fct]p6.
if (!Param->isInvalidDecl() &&
RequireCompleteType(Param->getLocation(), Param->getType(),
diag::err_typecheck_decl_incomplete_type)) {
Param->setInvalidDecl();
HasInvalidParm = true;
}
// C99 6.9.1p5: If the declarator includes a parameter type list, the
// declaration of each parameter shall include an identifier.
if (Param->getIdentifier() == 0 &&
!Param->isImplicit() &&
!getLangOptions().CPlusPlus)
Diag(Param->getLocation(), diag::err_parameter_name_omitted);
}
return HasInvalidParm;
}
/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
/// no declarator (e.g. "struct foo;") is parsed.
Chris Lattner
committed
Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
// FIXME: Error on auto/register at file scope
// FIXME: Error on inline/virtual/explicit
// FIXME: Error on invalid restrict
// FIXME: Warn on useless const/volatile
// FIXME: Warn on useless static/extern/typedef/private_extern/mutable
// FIXME: Warn on useless attributes
TagDecl *Tag = 0;
if (DS.getTypeSpecType() == DeclSpec::TST_class ||
DS.getTypeSpecType() == DeclSpec::TST_struct ||
DS.getTypeSpecType() == DeclSpec::TST_union ||
DS.getTypeSpecType() == DeclSpec::TST_enum)
Tag = dyn_cast<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
if (!Record->getDeclName() && Record->isDefinition() &&
Douglas Gregor
committed
DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
if (getLangOptions().CPlusPlus ||
Record->getDeclContext()->isRecord())
return BuildAnonymousStructOrUnion(S, DS, Record);
Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
<< DS.getSourceRange();
}
// Microsoft allows unnamed struct/union fields. Don't complain
// about them.
// FIXME: Should we support Microsoft's extensions in this area?
if (Record->getDeclName() && getLangOptions().Microsoft)
Chris Lattner
committed
return DeclPtrTy::make(Tag);
}
if (!DS.isMissingDeclaratorOk() &&
DS.getTypeSpecType() != DeclSpec::TST_error) {
// Warn about typedefs of enums without names, since this is an
// extension in both Microsoft an GNU.
Douglas Gregor
committed
if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
Tag && isa<EnumDecl>(Tag)) {
Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)