Page MenuHomePhabricator

No OneTemporary

File Metadata

Fri, Jan 24, 3:55 PM
This file is larger than 256 KB, so syntax highlighting was skipped.
Index: cfe/trunk/lib/Sema/Sema.cpp
--- cfe/trunk/lib/Sema/Sema.cpp (revision 312466)
+++ cfe/trunk/lib/Sema/Sema.cpp (revision 312467)
@@ -1,1765 +1,1779 @@
//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
// The LLVM Compiler Infrastructure
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
// This file implements the actions class which performs semantic analysis and
// builds an AST out of a parse stream.
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTDiagnostic.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclFriend.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/StmtCXX.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/PartialDiagnostic.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/CXXFieldCollector.h"
#include "clang/Sema/DelayedDiagnostic.h"
#include "clang/Sema/ExternalSemaSource.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/MultiplexExternalSemaSource.h"
#include "clang/Sema/ObjCMethodList.h"
#include "clang/Sema/PrettyDeclStackTrace.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/SemaConsumer.h"
#include "clang/Sema/SemaInternal.h"
#include "clang/Sema/TemplateDeduction.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallSet.h"
using namespace clang;
using namespace sema;
SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
const Preprocessor &PP) {
PrintingPolicy Policy = Context.getPrintingPolicy();
// Our printing policy is copied over the ASTContext printing policy whenever
// a diagnostic is emitted, so recompute it.
Policy.Bool = Context.getLangOpts().Bool;
if (!Policy.Bool) {
if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
Policy.Bool = BoolMacro->isObjectLike() &&
BoolMacro->getNumTokens() == 1 &&
return Policy;
void Sema::ActOnTranslationUnitScope(Scope *S) {
TUScope = S;
PushDeclContext(S, Context.getTranslationUnitDecl());
namespace clang {
namespace sema {
class SemaPPCallbacks : public PPCallbacks {
Sema *S = nullptr;
llvm::SmallVector<SourceLocation, 8> IncludeStack;
void set(Sema &S) { this->S = &S; }
void reset() { S = nullptr; }
virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
SrcMgr::CharacteristicKind FileType,
FileID PrevFID) override {
if (!S)
switch (Reason) {
case EnterFile: {
SourceManager &SM = S->getSourceManager();
SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
if (IncludeLoc.isValid()) {
Sema::PragmaPackDiagnoseKind::NonDefaultStateAtInclude, IncludeLoc);
case ExitFile:
if (!IncludeStack.empty())
} // end namespace sema
} // end namespace clang
Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
: ExternalSource(nullptr), isMultiplexExternalSource(false),
FPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),
Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
SourceMgr(PP.getSourceManager()), CollectStats(false),
CodeCompleter(CodeCompleter), CurContext(nullptr),
OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
VtorDispStack(MSVtorDispAttr::Mode(LangOpts.VtorDispMode)), PackStack(0),
DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
CodeSegStack(nullptr), CurInitSeg(nullptr), VisContext(nullptr),
IsBuildingRecoveryCallExpr(false), Cleanup{}, LateTemplateParser(nullptr),
LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
CXXTypeInfoDecl(nullptr), MSVCGuidDecl(nullptr), NSNumberDecl(nullptr),
NSValueDecl(nullptr), NSStringDecl(nullptr),
ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
TUKind(TUKind), NumSFINAEErrors(0), AccessCheckingSFINAE(false),
InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
TUScope = nullptr;
LoadedExternalKnownNamespaces = false;
for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
NSNumberLiteralMethods[I] = nullptr;
if (getLangOpts().ObjC1)
NSAPIObj.reset(new NSAPI(Context));
if (getLangOpts().CPlusPlus)
FieldCollector.reset(new CXXFieldCollector());
// Tell diagnostics how to render things from the AST library.
Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
nullptr, false);
FunctionScopes.push_back(new FunctionScopeInfo(Diags));
// Initilization of data sharing attributes stack for OpenMP
std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
SemaPPCallbackHandler = Callbacks.get();
void Sema::addImplicitTypedef(StringRef Name, QualType T) {
DeclarationName DN = &Context.Idents.get(Name);
if (IdResolver.begin(DN) == IdResolver.end())
PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
void Sema::Initialize() {
if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
// Tell the external Sema source about this Sema object.
if (ExternalSemaSource *ExternalSema
= dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
// This needs to happen after ExternalSemaSource::InitializeSema(this) or we
// will not be able to merge any duplicate __va_list_tag decls correctly.
VAListTagName = PP.getIdentifierInfo("__va_list_tag");
if (!TUScope)
// Initialize predefined 128-bit integer types, if needed.
if (Context.getTargetInfo().hasInt128Type()) {
// If either of the 128-bit integer types are unavailable to name lookup,
// define them now.
DeclarationName Int128 = &Context.Idents.get("__int128_t");
if (IdResolver.begin(Int128) == IdResolver.end())
PushOnScopeChains(Context.getInt128Decl(), TUScope);
DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
if (IdResolver.begin(UInt128) == IdResolver.end())
PushOnScopeChains(Context.getUInt128Decl(), TUScope);
// Initialize predefined Objective-C types:
if (getLangOpts().ObjC1) {
// If 'SEL' does not yet refer to any declarations, make it refer to the
// predefined 'SEL'.
DeclarationName SEL = &Context.Idents.get("SEL");
if (IdResolver.begin(SEL) == IdResolver.end())
PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
// If 'id' does not yet refer to any declarations, make it refer to the
// predefined 'id'.
DeclarationName Id = &Context.Idents.get("id");
if (IdResolver.begin(Id) == IdResolver.end())
PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
// Create the built-in typedef for 'Class'.
DeclarationName Class = &Context.Idents.get("Class");
if (IdResolver.begin(Class) == IdResolver.end())
PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
// Create the built-in forward declaratino for 'Protocol'.
DeclarationName Protocol = &Context.Idents.get("Protocol");
if (IdResolver.begin(Protocol) == IdResolver.end())
PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
// Create the internal type for the *StringMakeConstantString builtins.
DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
if (IdResolver.begin(ConstantString) == IdResolver.end())
PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
// Initialize Microsoft "predefined C++ types".
if (getLangOpts().MSVCCompat) {
if (getLangOpts().CPlusPlus &&
IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
addImplicitTypedef("size_t", Context.getSizeType());
// Initialize predefined OpenCL types and supported extensions and (optional)
// core features.
if (getLangOpts().OpenCL) {
addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
addImplicitTypedef("event_t", Context.OCLEventTy);
if (getLangOpts().OpenCLVersion >= 200) {
addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
addImplicitTypedef("queue_t", Context.OCLQueueTy);
addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
auto AtomicLongT = Context.getAtomicType(Context.LongTy);
addImplicitTypedef("atomic_long", AtomicLongT);
auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
addImplicitTypedef("atomic_ulong", AtomicULongT);
auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
addImplicitTypedef("atomic_double", AtomicDoubleT);
// OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
// 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
addImplicitTypedef("atomic_size_t", AtomicSizeT);
auto AtomicPtrDiffT = Context.getAtomicType(Context.getPointerDiffType());
addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
// OpenCL v2.0 s6.13.11.6:
// - The atomic_long and atomic_ulong types are supported if the
// cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
// extensions are supported.
// - The atomic_double type is only supported if double precision
// is supported and the cl_khr_int64_base_atomics and
// cl_khr_int64_extended_atomics extensions are supported.
// - If the device address space is 64-bits, the data types
// atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
// atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
// cl_khr_int64_extended_atomics extensions are supported.
std::vector<QualType> Atomic64BitTypes;
if (Context.getTypeSize(AtomicSizeT) == 64) {
for (auto &I : Atomic64BitTypes)
"cl_khr_int64_base_atomics cl_khr_int64_extended_atomics");
setOpenCLExtensionForType(AtomicDoubleT, "cl_khr_fp64");
setOpenCLExtensionForType(Context.DoubleTy, "cl_khr_fp64");
#define GENERIC_IMAGE_TYPE_EXT(Type, Id, Ext) \
setOpenCLExtensionForType(Context.Id, Ext);
#include "clang/Basic/OpenCLImageTypes.def"
if (Context.getTargetInfo().hasBuiltinMSVaList()) {
DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
if (IdResolver.begin(MSVaList) == IdResolver.end())
PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
Sema::~Sema() {
if (VisContext) FreeVisContext();
// Kill all the active scopes.
for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
delete FunctionScopes[I];
if (FunctionScopes.size() == 1)
delete FunctionScopes[0];
// Tell the SemaConsumer to forget about us; we're going out of scope.
if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
// Detach from the external Sema source.
if (ExternalSemaSource *ExternalSema
= dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
// If Sema's ExternalSource is the multiplexer - we own it.
if (isMultiplexExternalSource)
delete ExternalSource;
// Destroys data sharing attributes stack for OpenMP
// Detach from the PP callback handler which outlives Sema since it's owned
// by the preprocessor.
assert(DelayedTypos.empty() && "Uncorrected typos!");
/// makeUnavailableInSystemHeader - There is an error in the current
/// context. If we're still in a system header, and we can plausibly
/// make the relevant declaration unavailable instead of erroring, do
/// so and return true.
bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
UnavailableAttr::ImplicitReason reason) {
// If we're not in a function, it's an error.
FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
if (!fn) return false;
// If we're in template instantiation, it's an error.
if (inTemplateInstantiation())
return false;
// If that function's not in a system header, it's an error.
if (!Context.getSourceManager().isInSystemHeader(loc))
return false;
// If the function is already unavailable, it's not an error.
if (fn->hasAttr<UnavailableAttr>()) return true;
fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
return true;
ASTMutationListener *Sema::getASTMutationListener() const {
return getASTConsumer().GetASTMutationListener();
///\brief Registers an external source. If an external source already exists,
/// creates a multiplex external source and appends to it.
///\param[in] E - A non-null external sema source.
void Sema::addExternalSource(ExternalSemaSource *E) {
assert(E && "Cannot use with NULL ptr");
if (!ExternalSource) {
ExternalSource = E;
if (isMultiplexExternalSource)
else {
ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
isMultiplexExternalSource = true;
/// \brief Print out statistics about the semantic analysis.
void Sema::PrintStats() const {
llvm::errs() << "\n*** Semantic Analysis Stats:\n";
llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
QualType SrcType,
SourceLocation Loc) {
Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context);
if (!ExprNullability || *ExprNullability != NullabilityKind::Nullable)
Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context);
if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr* E) {
if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
if (E->getType()->isNullPtrType())
// nullptr only exists from C++11 on, so don't warn on its absence earlier.
if (!getLangOpts().CPlusPlus11)
Diag(E->getLocStart(), diag::warn_zero_as_null_pointer_constant)
<< FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
/// If there is already an implicit cast, merge into the existing one.
/// The result is of the given category.
ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
CastKind Kind, ExprValueKind VK,
const CXXCastPath *BasePath,
CheckedConversionKind CCK) {
#ifndef NDEBUG
if (VK == VK_RValue && !E->isRValue()) {
switch (Kind) {
llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast "
case CK_LValueToRValue:
case CK_ArrayToPointerDecay:
case CK_FunctionToPointerDecay:
case CK_ToVoid:
assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue");
diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getLocStart());
diagnoseZeroToNullptrConversion(Kind, E);
QualType ExprTy = Context.getCanonicalType(E->getType());
QualType TypeTy = Context.getCanonicalType(Ty);
if (ExprTy == TypeTy)
return E;
// C++1z [conv.array]: The temporary materialization conversion is applied.
// We also use this to fuel C++ DR1213, which applies to C++11 onwards.
if (Kind == CK_ArrayToPointerDecay && getLangOpts().CPlusPlus &&
E->getValueKind() == VK_RValue) {
// The temporary is an lvalue in C++98 and an xvalue otherwise.
ExprResult Materialized = CreateMaterializeTemporaryExpr(
E->getType(), E, !getLangOpts().CPlusPlus11);
if (Materialized.isInvalid())
return ExprError();
E = Materialized.get();
if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
return E;
return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK);
/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
/// to the conversion from scalar type ScalarTy to the Boolean type.
CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
switch (ScalarTy->getScalarTypeKind()) {
case Type::STK_Bool: return CK_NoOp;
case Type::STK_CPointer: return CK_PointerToBoolean;
case Type::STK_BlockPointer: return CK_PointerToBoolean;
case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
case Type::STK_Integral: return CK_IntegralToBoolean;
case Type::STK_Floating: return CK_FloatingToBoolean;
case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
return CK_Invalid;
/// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
if (D->getMostRecentDecl()->isUsed())
return true;
if (D->isExternallyVisible())
return true;
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
// If this is a function template and none of its specializations is used,
// we should warn.
if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
for (const auto *Spec : Template->specializations())
if (ShouldRemoveFromUnused(SemaRef, Spec))
return true;
// UnusedFileScopedDecls stores the first declaration.
// The declaration may have become definition so check again.
const FunctionDecl *DeclToCheck;
if (FD->hasBody(DeclToCheck))
return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
// Later redecls may add new information resulting in not having to warn,
// so check again.
DeclToCheck = FD->getMostRecentDecl();
if (DeclToCheck != FD)
return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
// If a variable usable in constant expressions is referenced,
// don't warn if it isn't used: if the value of a variable is required
// for the computation of a constant expression, it doesn't make sense to
// warn even if the variable isn't odr-used. (isReferenced doesn't
// precisely reflect that, but it's a decent approximation.)
if (VD->isReferenced() &&
return true;
if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
// If this is a variable template and none of its specializations is used,
// we should warn.
for (const auto *Spec : Template->specializations())
if (ShouldRemoveFromUnused(SemaRef, Spec))
return true;
// UnusedFileScopedDecls stores the first declaration.
// The declaration may have become definition so check again.
const VarDecl *DeclToCheck = VD->getDefinition();
if (DeclToCheck)
return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
// Later redecls may add new information resulting in not having to warn,
// so check again.
DeclToCheck = VD->getMostRecentDecl();
if (DeclToCheck != VD)
return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
return false;
/// Obtains a sorted list of functions and variables that are undefined but
/// ODR-used.
void Sema::getUndefinedButUsed(
SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
for (const auto &UndefinedUse : UndefinedButUsed) {
NamedDecl *ND = UndefinedUse.first;
// Ignore attributes that have become invalid.
if (ND->isInvalidDecl()) continue;
// __attribute__((weakref)) is basically a definition.
if (ND->hasAttr<WeakRefAttr>()) continue;
if (isa<CXXDeductionGuideDecl>(ND))
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
if (FD->isDefined())
if (FD->isExternallyVisible() &&
} else {
auto *VD = cast<VarDecl>(ND);
if (VD->hasDefinition() != VarDecl::DeclarationOnly)
if (VD->isExternallyVisible() && !VD->getMostRecentDecl()->isInline())
Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
/// checkUndefinedButUsed - Check for undefined objects with internal linkage
/// or that are inline.
static void checkUndefinedButUsed(Sema &S) {
if (S.UndefinedButUsed.empty()) return;
// Collect all the still-undefined entities with internal linkage.
SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
if (Undefined.empty()) return;
for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
NamedDecl *ND = I->first;
if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
// An exported function will always be emitted when defined, so even if
// the function is inline, it doesn't have to be emitted in this TU. An
// imported function implies that it has been exported somewhere else.
if (!ND->isExternallyVisible()) {
S.Diag(ND->getLocation(), diag::warn_undefined_internal)
<< isa<VarDecl>(ND) << ND;
} else if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
assert(FD->getMostRecentDecl()->isInlined() &&
"used object requires definition but isn't inline or internal?");
// FIXME: This is ill-formed; we should reject.
S.Diag(ND->getLocation(), diag::warn_undefined_inline) << ND;
} else {
assert(cast<VarDecl>(ND)->getMostRecentDecl()->isInline() &&
"used var requires definition but isn't inline or internal?");
S.Diag(ND->getLocation(), diag::err_undefined_inline_var) << ND;
if (I->second.isValid())
S.Diag(I->second, diag::note_used_here);
void Sema::LoadExternalWeakUndeclaredIdentifiers() {
if (!ExternalSource)
SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
for (auto &WeakID : WeakIDs)
typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
/// \brief Returns true, if all methods and nested classes of the given
/// CXXRecordDecl are defined in this translation unit.
/// Should only be called from ActOnEndOfTranslationUnit so that all
/// definitions are actually read.
static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
RecordCompleteMap &MNCComplete) {
RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
if (Cache != MNCComplete.end())
return Cache->second;
if (!RD->isCompleteDefinition())
return false;
bool Complete = true;
for (DeclContext::decl_iterator I = RD->decls_begin(),
E = RD->decls_end();
I != E && Complete; ++I) {
if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M));
else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
// If the template function is marked as late template parsed at this
// point, it has not been instantiated and therefore we have not
// performed semantic analysis on it yet, so we cannot know if the type
// can be considered complete.
Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
if (R->isInjectedClassName())
if (R->hasDefinition())
Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
Complete = false;
MNCComplete[RD] = Complete;
return Complete;
/// \brief Returns true, if the given CXXRecordDecl is fully defined in this
/// translation unit, i.e. all methods are defined or pure virtual and all
/// friends, friend functions and nested classes are fully defined in this
/// translation unit.
/// Should only be called from ActOnEndOfTranslationUnit so that all
/// definitions are actually read.
static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
RecordCompleteMap &RecordsComplete,
RecordCompleteMap &MNCComplete) {
RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
if (Cache != RecordsComplete.end())
return Cache->second;
bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
E = RD->friend_end();
I != E && Complete; ++I) {
// Check if friend classes and methods are complete.
if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
// Friend classes are available as the TypeSourceInfo of the FriendDecl.
if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
Complete = false;
} else {
// Friend functions are available through the NamedDecl of FriendDecl.
if (const FunctionDecl *FD =
Complete = FD->isDefined();
// This is a template friend, give up.
Complete = false;
RecordsComplete[RD] = Complete;
return Complete;
void Sema::emitAndClearUnusedLocalTypedefWarnings() {
if (ExternalSource)
for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
if (TD->isReferenced())
Diag(TD->getLocation(), diag::warn_unused_local_typedef)
<< isa<TypeAliasDecl>(TD) << TD->getDeclName();
/// This is called before the very first declaration in the translation unit
/// is parsed. Note that the ASTContext may have already injected some
/// declarations.
void Sema::ActOnStartOfTranslationUnit() {
if (getLangOpts().ModulesTS) {
+ SourceLocation StartOfTU =
+ SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
// We start in the global module; all those declarations are implicitly
// module-private (though they do not have module linkage).
- Context.getTranslationUnitDecl()->setModuleOwnershipKind(
- Decl::ModuleOwnershipKind::ModulePrivate);
+ auto &Map = PP.getHeaderSearchInfo().getModuleMap();
+ auto *GlobalModule = Map.createGlobalModuleForInterfaceUnit(StartOfTU);
+ assert(GlobalModule && "module creation should not fail");
+ // Enter the scope of the global module.
+ ModuleScopes.push_back({});
+ ModuleScopes.back().Module = GlobalModule;
+ VisibleModules.setVisible(GlobalModule, StartOfTU);
+ // All declarations created from now on are owned by the global module.
+ auto *TU = Context.getTranslationUnitDecl();
+ TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible);
+ TU->setLocalOwningModule(GlobalModule);
/// ActOnEndOfTranslationUnit - This is called at the very end of the
/// translation unit when EOF is reached and all but the top-level scope is
/// popped.
void Sema::ActOnEndOfTranslationUnit() {
assert(DelayedDiagnostics.getCurrentPool() == nullptr
&& "reached end of translation unit with a pool attached?");
// If code completion is enabled, don't perform any end-of-translation-unit
// work.
if (PP.isCodeCompletionEnabled())
// Complete translation units and modules define vtables and perform implicit
// instantiations. PCH files do not.
if (TUKind != TU_Prefix) {
// If DefinedUsedVTables ends up marking any virtual member functions it
// might lead to more pending template instantiations, which we then need
// to instantiate.
// C++: Perform implicit template instantiations.
// FIXME: When we perform these implicit instantiations, we do not
// carefully keep track of the point of instantiation (C++ [temp.point]).
// This means that name lookup that occurs within the template
// instantiation will always happen at the end of the translation unit,
// so it will find some names that are not required to be found. This is
// valid, but we could do better by diagnosing if an instantiation uses a
// name that was not visible at its first point of instantiation.
if (ExternalSource) {
// Load pending instantiations from the external source.
SmallVector<PendingImplicitInstantiation, 4> Pending;
for (auto PII : Pending)
if (auto Func = dyn_cast<FunctionDecl>(PII.first))
Pending.begin(), Pending.end());
if (LateTemplateParserCleanup)
// All delayed member exception specs should be checked or we end up accepting
// incompatible declarations.
// FIXME: This is wrong for TUKind == TU_Prefix. In that case, we need to
// write out the lists to the AST file (if any).
// All dllexport classes should have been processed already.
// Remove file scoped decls that turned out to be used.
std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
[this](const DeclaratorDecl *DD) {
return ShouldRemoveFromUnused(this, DD);
if (TUKind == TU_Prefix) {
// Translation unit prefixes don't need any of the checking below.
if (!PP.isIncrementalProcessingEnabled())
TUScope = nullptr;
// Check for #pragma weak identifiers that were never declared
for (auto WeakID : WeakUndeclaredIdentifiers) {
if (WeakID.second.getUsed())
Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(),
if (PrevDecl != nullptr &&
!(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type)
<< "'weak'" << ExpectedVariableOrFunction;
Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
<< WeakID.first;
if (LangOpts.CPlusPlus11 &&
!Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
if (!Diags.hasErrorOccurred()) {
if (ExternalSource)
if (TUKind == TU_Module) {
// If we are building a module, resolve all of the exported declarations
// now.
if (Module *CurrentModule = PP.getCurrentModule()) {
ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
SmallVector<Module *, 2> Stack;
while (!Stack.empty()) {
Module *Mod = Stack.pop_back_val();
// Resolve the exported declarations and conflicts.
// FIXME: Actually complain, once we figure out how to teach the
// diagnostic client to deal with complaints in the module map at this
// point.
ModMap.resolveExports(Mod, /*Complain=*/false);
ModMap.resolveUses(Mod, /*Complain=*/false);
ModMap.resolveConflicts(Mod, /*Complain=*/false);
// Queue the submodules, so their exports will also be resolved.
Stack.append(Mod->submodule_begin(), Mod->submodule_end());
// Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
// modules when they are built, not every time they are used.
// Modules don't need any of the checking below.
if (!PP.isIncrementalProcessingEnabled())
TUScope = nullptr;
// C99 6.9.2p2:
// A declaration of an identifier for an object that has file
// scope without an initializer, and without a storage-class
// specifier or with the storage-class specifier static,
// constitutes a tentative definition. If a translation unit
// contains one or more tentative definitions for an identifier,
// and the translation unit contains no external definition for
// that identifier, then the behavior is exactly as if the
// translation unit contains a file scope declaration of that
// identifier, with the composite type as of the end of the
// translation unit, with an initializer equal to 0.
llvm::SmallSet<VarDecl *, 32> Seen;
for (TentativeDefinitionsType::iterator
T = TentativeDefinitions.begin(ExternalSource),
TEnd = TentativeDefinitions.end();
T != TEnd; ++T)
VarDecl *VD = (*T)->getActingDefinition();
// If the tentative definition was completed, getActingDefinition() returns
// null. If we've already seen this variable before, insert()'s second
// return value is false.
if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
if (const IncompleteArrayType *ArrayT
= Context.getAsIncompleteArrayType(VD->getType())) {
// Set the length of the array to 1 (C99 6.9.2p5).
Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
One, ArrayType::Normal, 0);
} else if (RequireCompleteType(VD->getLocation(), VD->getType(),
// No initialization is performed for a tentative definition.
// Notify the consumer that we've completed a tentative definition.
if (!VD->isInvalidDecl())
// If there were errors, disable 'unused' warnings since they will mostly be
// noise.
if (!Diags.hasErrorOccurred()) {
// Output warning for unused file scoped decls.
for (UnusedFileScopedDeclsType::iterator
I = UnusedFileScopedDecls.begin(ExternalSource),
E = UnusedFileScopedDecls.end(); I != E; ++I) {
if (ShouldRemoveFromUnused(this, *I))
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
const FunctionDecl *DiagD;
if (!FD->hasBody(DiagD))
DiagD = FD;
if (DiagD->isDeleted())
continue; // Deleted functions are supposed to be unused.
if (DiagD->isReferenced()) {
if (isa<CXXMethodDecl>(DiagD))
Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
<< DiagD->getDeclName();
else {
if (FD->getStorageClass() == SC_Static &&
!FD->isInlineSpecified() &&
<< DiagD->getDeclName();
Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
<< /*function*/0 << DiagD->getDeclName();
} else {
if (FD->getDescribedFunctionTemplate())
Diag(DiagD->getLocation(), diag::warn_unused_template)
<< /*function*/0 << DiagD->getDeclName();
isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
: diag::warn_unused_function)
<< DiagD->getDeclName();
} else {
const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
if (!DiagD)
DiagD = cast<VarDecl>(*I);
if (DiagD->isReferenced()) {
Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
<< /*variable*/1 << DiagD->getDeclName();
} else if (DiagD->getType().isConstQualified()) {
const SourceManager &SM = SourceMgr;
if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
<< DiagD->getDeclName();
} else {
if (DiagD->getDescribedVarTemplate())
Diag(DiagD->getLocation(), diag::warn_unused_template)
<< /*variable*/1 << DiagD->getDeclName();
Diag(DiagD->getLocation(), diag::warn_unused_variable)
<< DiagD->getDeclName();
if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
RecordCompleteMap RecordsComplete;
RecordCompleteMap MNCComplete;
for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
E = UnusedPrivateFields.end(); I != E; ++I) {
const NamedDecl *D = *I;
const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
if (RD && !RD->isUnion() &&
IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
Diag(D->getLocation(), diag::warn_unused_private_field)
<< D->getDeclName();
if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
if (ExternalSource)
for (const auto &DeletedFieldInfo : DeleteExprs) {
for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
// Check we've noticed that we're no longer parsing the initializer for every
// variable. If we miss cases, then at best we have a performance issue and
// at worst a rejects-valid bug.
assert(ParsingInitForAutoVars.empty() &&
"Didn't unmark var as having its initializer parsed");
if (!PP.isIncrementalProcessingEnabled())
TUScope = nullptr;
// Helper functions.
DeclContext *Sema::getFunctionLevelDeclContext() {
DeclContext *DC = CurContext;
while (true) {
if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) {
DC = DC->getParent();
} else if (isa<CXXMethodDecl>(DC) &&
cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
DC = DC->getParent()->getParent();
else break;
return DC;
/// getCurFunctionDecl - If inside of a function body, this returns a pointer
/// to the function decl for the function being parsed. If we're currently
/// in a 'block', this returns the containing context.
FunctionDecl *Sema::getCurFunctionDecl() {
DeclContext *DC = getFunctionLevelDeclContext();
return dyn_cast<FunctionDecl>(DC);
ObjCMethodDecl *Sema::getCurMethodDecl() {
DeclContext *DC = getFunctionLevelDeclContext();
while (isa<RecordDecl>(DC))
DC = DC->getParent();
return dyn_cast<ObjCMethodDecl>(DC);
NamedDecl *Sema::getCurFunctionOrMethodDecl() {
DeclContext *DC = getFunctionLevelDeclContext();
if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
return cast<NamedDecl>(DC);
return nullptr;
void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
// FIXME: It doesn't make sense to me that DiagID is an incoming argument here
// and yet we also use the current diag ID on the DiagnosticsEngine. This has
// been made more painfully obvious by the refactor that introduced this
// function, but it is possible that the incoming argument can be
// eliminated. If it truly cannot be (for example, there is some reentrancy
// issue I am not seeing yet), then there should at least be a clarifying
// comment somewhere.
if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
Diags.getCurrentDiagID())) {
case DiagnosticIDs::SFINAE_Report:
// We'll report the diagnostic below.
case DiagnosticIDs::SFINAE_SubstitutionFailure:
// Count this failure so that we know that template argument deduction
// has failed.
// Make a copy of this suppressed diagnostic and store it with the
// template-deduction information.
if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
Diagnostic DiagInfo(&Diags);
PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
case DiagnosticIDs::SFINAE_AccessControl: {
// Per C++ Core Issue 1170, access control is part of SFINAE.
// Additionally, the AccessCheckingSFINAE flag can be used to temporarily
// make access control a part of SFINAE for the purposes of checking
// type traits.
if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
SourceLocation Loc = Diags.getCurrentDiagLoc();
// Suppress this diagnostic.
// Make a copy of this suppressed diagnostic and store it with the
// template-deduction information.
if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
Diagnostic DiagInfo(&Diags);
PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
// Now the diagnostic state is clear, produce a C++98 compatibility
// warning.
Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
// The last diagnostic which Sema produced was ignored. Suppress any
// notes attached to it.
case DiagnosticIDs::SFINAE_Suppress:
// Make a copy of this suppressed diagnostic and store it with the
// template-deduction information;
if (*Info) {
Diagnostic DiagInfo(&Diags);
PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
// Suppress this diagnostic.
// Set up the context's printing policy based on our current state.
// Emit the diagnostic.
if (!Diags.EmitCurrentDiagnostic())
// If this is not a note, and we're in a template instantiation
// that is different from the last template instantiation where
// we emitted an error, print a template instantiation
// backtrace.
if (!DiagnosticIDs::isBuiltinNote(DiagID))
Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
return Builder;
/// \brief Looks through the macro-expansion chain for the given
/// location, looking for a macro expansion with the given name.
/// If one is found, returns true and sets the location to that
/// expansion loc.
bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
SourceLocation loc = locref;
if (!loc.isMacroID()) return false;
// There's no good way right now to look at the intermediate
// expansions, so just jump to the expansion location.
loc = getSourceManager().getExpansionLoc(loc);
// If that's written with the name, stop here.
SmallVector<char, 16> buffer;
if (getPreprocessor().getSpelling(loc, buffer) == name) {
locref = loc;
return true;
return false;
/// \brief Determines the active Scope associated with the given declaration
/// context.
/// This routine maps a declaration context to the active Scope object that
/// represents that declaration context in the parser. It is typically used
/// from "scope-less" code (e.g., template instantiation, lazy creation of
/// declarations) that injects a name for name-lookup purposes and, therefore,
/// must update the Scope.
/// \returns The scope corresponding to the given declaraion context, or NULL
/// if no such scope is open.
Scope *Sema::getScopeForContext(DeclContext *Ctx) {
if (!Ctx)
return nullptr;
Ctx = Ctx->getPrimaryContext();
for (Scope *S = getCurScope(); S; S = S->getParent()) {
// Ignore scopes that cannot have declarations. This is important for
// out-of-line definitions of static class members.
if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
if (DeclContext *Entity = S->getEntity())
if (Ctx == Entity->getPrimaryContext())
return S;
return nullptr;
/// \brief Enter a new function scope
void Sema::PushFunctionScope() {
if (FunctionScopes.size() == 1) {
// Use the "top" function scope rather than having to allocate
// memory for a new scope.
if (LangOpts.OpenMP)
FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
if (LangOpts.OpenMP)
void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
BlockScope, Block));
LambdaScopeInfo *Sema::PushLambdaScope() {
LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
return LSI;
void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
if (LambdaScopeInfo *const LSI = getCurLambda()) {
LSI->AutoTemplateParameterDepth = Depth;
"Remove assertion if intentionally called in a non-lambda context.");
void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
const Decl *D, const BlockExpr *blkExpr) {
FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
assert(!FunctionScopes.empty() && "mismatched push/pop!");
if (LangOpts.OpenMP)
// Issue any analysis-based warnings.
if (WP && D)
AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
for (const auto &PUD : Scope->PossiblyUnreachableDiags)
Diag(PUD.Loc, PUD.PD);
if (FunctionScopes.back() != Scope)
delete Scope;
void Sema::PushCompoundScope() {
void Sema::PopCompoundScope() {
FunctionScopeInfo *CurFunction = getCurFunction();
assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
/// \brief Determine whether any errors occurred within this function/method/
/// block.
bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
BlockScopeInfo *Sema::getCurBlock() {
if (FunctionScopes.empty())
return nullptr;
auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
if (CurBSI && CurBSI->TheDecl &&
!CurBSI->TheDecl->Encloses(CurContext)) {
// We have switched contexts due to template instantiation.
return nullptr;
return CurBSI;
LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
if (FunctionScopes.empty())
return nullptr;
auto I = FunctionScopes.rbegin();
if (IgnoreNonLambdaCapturingScope) {
auto E = FunctionScopes.rend();
while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
if (I == E)
return nullptr;
auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
if (CurLSI && CurLSI->Lambda &&
!CurLSI->Lambda->Encloses(CurContext)) {
// We have switched contexts due to template instantiation.
return nullptr;
return CurLSI;
// We have a generic lambda if we parsed auto parameters, or we have
// an associated template parameter list.
LambdaScopeInfo *Sema::getCurGenericLambda() {
if (LambdaScopeInfo *LSI = getCurLambda()) {
return (LSI->AutoTemplateParams.size() ||
LSI->GLTemplateParameterList) ? LSI : nullptr;
return nullptr;
void Sema::ActOnComment(SourceRange Comment) {
if (!LangOpts.RetainCommentsFromSystemHeaders &&
RawComment RC(SourceMgr, Comment, false,
if (RC.isAlmostTrailingComment()) {
SourceRange MagicMarkerRange(Comment.getBegin(),
StringRef MagicMarkerText;
switch (RC.getKind()) {
case RawComment::RCK_OrdinaryBCPL:
MagicMarkerText = "///<";
case RawComment::RCK_OrdinaryC:
MagicMarkerText = "/**<";
llvm_unreachable("if this is an almost Doxygen comment, "
"it should be ordinary");
Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
// Pin this vtable to this file.
ExternalSemaSource::~ExternalSemaSource() {}
void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
void ExternalSemaSource::ReadKnownNamespaces(
SmallVectorImpl<NamespaceDecl *> &Namespaces) {
void ExternalSemaSource::ReadUndefinedButUsed(
llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
SourceLocation Loc = this->Loc;
if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
if (Loc.isValid()) {
Loc.print(OS, S.getSourceManager());
OS << ": ";
OS << Message;
if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
OS << " '";
ND->getNameForDiagnostic(OS, ND->getASTContext().getPrintingPolicy(), true);
OS << "'";
OS << '\n';
/// \brief Figure out if an expression could be turned into a call.
/// Use this when trying to recover from an error where the programmer may have
/// written just the name of a function instead of actually calling it.
/// \param E - The expression to examine.
/// \param ZeroArgCallReturnTy - If the expression can be turned into a call
/// with no arguments, this parameter is set to the type returned by such a
/// call; otherwise, it is set to an empty QualType.
/// \param OverloadSet - If the expression is an overloaded function
/// name, this parameter is populated with the decls of the various overloads.
bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
UnresolvedSetImpl &OverloadSet) {
ZeroArgCallReturnTy = QualType();
const OverloadExpr *Overloads = nullptr;
bool IsMemExpr = false;
if (E.getType() == Context.OverloadTy) {
OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
// Ignore overloads that are pointer-to-member constants.
if (FR.HasFormOfMemberPointer)
return false;
Overloads = FR.Expression;
} else if (E.getType() == Context.BoundMemberTy) {
Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
IsMemExpr = true;
bool Ambiguous = false;
if (Overloads) {
for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
// Check whether the function is a non-template, non-member which takes no
// arguments.
if (IsMemExpr)
if (const FunctionDecl *OverloadDecl
= dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
if (OverloadDecl->getMinRequiredArguments() == 0) {
if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) {
ZeroArgCallReturnTy = QualType();
Ambiguous = true;
} else
ZeroArgCallReturnTy = OverloadDecl->getReturnType();
// If it's not a member, use better machinery to try to resolve the call
if (!IsMemExpr)
return !ZeroArgCallReturnTy.isNull();
// Attempt to call the member with no arguments - this will correctly handle
// member templates with defaults/deduction of template arguments, overloads
// with default arguments, etc.
if (IsMemExpr && !E.isTypeDependent()) {
bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
None, SourceLocation());
if (R.isUsable()) {
ZeroArgCallReturnTy = R.get()->getType();
return true;
return false;
if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
if (Fun->getMinRequiredArguments() == 0)
ZeroArgCallReturnTy = Fun->getReturnType();
return true;
// We don't have an expression that's convenient to get a FunctionDecl from,
// but we can at least check if the type is "function of 0 arguments".
QualType ExprTy = E.getType();
const FunctionType *FunTy = nullptr;
QualType PointeeTy = ExprTy->getPointeeType();
if (!PointeeTy.isNull())
FunTy = PointeeTy->getAs<FunctionType>();
if (!FunTy)
FunTy = ExprTy->getAs<FunctionType>();
if (const FunctionProtoType *FPT =
dyn_cast_or_null<FunctionProtoType>(FunTy)) {
if (FPT->getNumParams() == 0)
ZeroArgCallReturnTy = FunTy->getReturnType();
return true;
return false;
/// \brief Give notes for a set of overloads.
/// A companion to tryExprAsCall. In cases when the name that the programmer
/// wrote was an overloaded function, we may be able to make some guesses about
/// plausible overloads based on their return types; such guesses can be handed
/// off to this method to be emitted as notes.
/// \param Overloads - The overloads to note.
/// \param FinalNoteLoc - If we've suppressed printing some overloads due to
/// -fshow-overloads=best, this is the location to attach to the note about too
/// many candidates. Typically this will be the location of the original
/// ill-formed expression.
static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
const SourceLocation FinalNoteLoc) {
int ShownOverloads = 0;
int SuppressedOverloads = 0;
for (UnresolvedSetImpl::iterator It = Overloads.begin(),
DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
// FIXME: Magic number for max shown overloads stolen from
// OverloadCandidateSet::NoteCandidates.
if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
NamedDecl *Fn = (*It)->getUnderlyingDecl();
S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
if (SuppressedOverloads)
S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
<< SuppressedOverloads;
static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
const UnresolvedSetImpl &Overloads,
bool (*IsPlausibleResult)(QualType)) {
if (!IsPlausibleResult)
return noteOverloads(S, Overloads, Loc);
UnresolvedSet<2> PlausibleOverloads;
for (OverloadExpr::decls_iterator It = Overloads.begin(),
DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
QualType OverloadResultTy = OverloadDecl->getReturnType();
if (IsPlausibleResult(OverloadResultTy))
noteOverloads(S, PlausibleOverloads, Loc);
/// Determine whether the given expression can be called by just
/// putting parentheses after it. Notably, expressions with unary
/// operators can't be because the unary operator will start parsing
/// outside the call.
static bool IsCallableWithAppend(Expr *E) {
E = E->IgnoreImplicit();
return (!isa<CStyleCastExpr>(E) &&
!isa<UnaryOperator>(E) &&
!isa<BinaryOperator>(E) &&
bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
bool ForceComplain,
bool (*IsPlausibleResult)(QualType)) {
SourceLocation Loc = E.get()->getExprLoc();
SourceRange Range = E.get()->getSourceRange();
QualType ZeroArgCallTy;
UnresolvedSet<4> Overloads;
if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
!ZeroArgCallTy.isNull() &&
(!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
// At this point, we know E is potentially callable with 0
// arguments and that it returns something of a reasonable type,
// so we can emit a fixit and carry on pretending that E was
// actually a CallExpr.
SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
Diag(Loc, PD)
<< /*zero-arg*/ 1 << Range
<< (IsCallableWithAppend(E.get())
? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
: FixItHint());
notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
// FIXME: Try this before emitting the fixit, and suppress diagnostics
// while doing so.
E = ActOnCallExpr(nullptr, E.get(), Range.getEnd(), None,
return true;
if (!ForceComplain) return false;
Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
E = ExprError();
return true;
IdentifierInfo *Sema::getSuperIdentifier() const {
if (!Ident_super)
Ident_super = &Context.Idents.get("super");
return Ident_super;
IdentifierInfo *Sema::getFloat128Identifier() const {
if (!Ident___float128)
Ident___float128 = &Context.Idents.get("__float128");
return Ident___float128;
void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
CapturedRegionKind K) {
CapturingScopeInfo *CSI = new CapturedRegionScopeInfo(
getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
(getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0);
CSI->ReturnType = Context.VoidTy;
CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
if (FunctionScopes.empty())
return nullptr;
return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
Sema::getMismatchingDeleteExpressions() const {
return DeleteExprs;
void Sema::setOpenCLExtensionForType(QualType T, llvm::StringRef ExtStr) {
if (ExtStr.empty())
llvm::SmallVector<StringRef, 1> Exts;
ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
auto CanT = T.getCanonicalType().getTypePtr();
for (auto &I : Exts)
void Sema::setOpenCLExtensionForDecl(Decl *FD, StringRef ExtStr) {
llvm::SmallVector<StringRef, 1> Exts;
ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
if (Exts.empty())
for (auto &I : Exts)
void Sema::setCurrentOpenCLExtensionForType(QualType T) {
if (CurrOpenCLExtension.empty())
setOpenCLExtensionForType(T, CurrOpenCLExtension);
void Sema::setCurrentOpenCLExtensionForDecl(Decl *D) {
if (CurrOpenCLExtension.empty())
setOpenCLExtensionForDecl(D, CurrOpenCLExtension);
bool Sema::isOpenCLDisabledDecl(Decl *FD) {
auto Loc = OpenCLDeclExtMap.find(FD);
if (Loc == OpenCLDeclExtMap.end())
return false;
for (auto &I : Loc->second) {
if (!getOpenCLOptions().isEnabled(I))
return true;
return false;
template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
bool Sema::checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc,
DiagInfoT DiagInfo, MapT &Map,
unsigned Selector,
SourceRange SrcRange) {
auto Loc = Map.find(D);
if (Loc == Map.end())
return false;
bool Disabled = false;
for (auto &I : Loc->second) {
if (I != CurrOpenCLExtension && !getOpenCLOptions().isEnabled(I)) {
Diag(DiagLoc, diag::err_opencl_requires_extension) << Selector << DiagInfo
<< I << SrcRange;
Disabled = true;
return Disabled;
bool Sema::checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType QT) {
// Check extensions for declared types.
Decl *Decl = nullptr;
if (auto TypedefT = dyn_cast<TypedefType>(QT.getTypePtr()))
Decl = TypedefT->getDecl();
if (auto TagT = dyn_cast<TagType>(QT.getCanonicalType().getTypePtr()))
Decl = TagT->getDecl();
auto Loc = DS.getTypeSpecTypeLoc();
if (checkOpenCLDisabledTypeOrDecl(Decl, Loc, QT, OpenCLDeclExtMap))
return true;
// Check extensions for builtin types.
return checkOpenCLDisabledTypeOrDecl(QT.getCanonicalType().getTypePtr(), Loc,
QT, OpenCLTypeExtMap);
bool Sema::checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E) {
IdentifierInfo *FnName = D.getIdentifier();
return checkOpenCLDisabledTypeOrDecl(&D, E.getLocStart(), FnName,
OpenCLDeclExtMap, 1, D.getSourceRange());
Index: cfe/trunk/lib/Sema/SemaDecl.cpp
--- cfe/trunk/lib/Sema/SemaDecl.cpp (revision 312466)
+++ cfe/trunk/lib/Sema/SemaDecl.cpp (revision 312467)
@@ -1,16421 +1,16425 @@
//===--- 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.
#include "TypeLocBuilder.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTLambda.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/CharUnits.h"
#include "clang/AST/CommentDiagnostic.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/EvaluatedExprVisitor.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/StmtCXX.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/PartialDiagnostic.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
#include "clang/Sema/CXXFieldCollector.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/DelayedDiagnostic.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/ParsedTemplate.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/SemaInternal.h"
#include "clang/Sema/Template.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Triple.h"
#include <algorithm>
#include <cstring>
#include <functional>
using namespace clang;
using namespace sema;
Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
if (OwnedType) {
Decl *Group[2] = { OwnedType, Ptr };
return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
namespace {
class TypeNameValidatorCCC : public CorrectionCandidateCallback {
TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
bool AllowTemplates = false,
bool AllowNonTemplates = true)
: AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
WantExpressionKeywords = false;
WantCXXNamedCasts = false;
WantRemainingKeywords = false;
bool ValidateCandidate(const TypoCorrection &candidate) override {
if (NamedDecl *ND = candidate.getCorrectionDecl()) {
if (!AllowInvalidDecl && ND->isInvalidDecl())
return false;
if (getAsTypeTemplateDecl(ND))
return AllowTemplates;
bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
if (!IsType)
return false;
if (AllowNonTemplates)
return true;
// An injected-class-name of a class template (specialization) is valid
// as a template or as a non-template.
if (AllowTemplates) {
auto *RD = dyn_cast<CXXRecordDecl>(ND);
if (!RD || !RD->isInjectedClassName())
return false;
RD = cast<CXXRecordDecl>(RD->getDeclContext());
return RD->getDescribedClassTemplate() ||
return false;
return !WantClassName && candidate.isKeyword();
bool AllowInvalidDecl;
bool WantClassName;
bool AllowTemplates;
bool AllowNonTemplates;
} // end anonymous namespace
/// \brief Determine whether the token kind starts a simple-type-specifier.
bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
switch (Kind) {
// FIXME: Take into account the current language when deciding whether a
// token kind is a valid type specifier
case tok::kw_short:
case tok::kw_long:
case tok::kw___int64:
case tok::kw___int128:
case tok::kw_signed:
case tok::kw_unsigned:
case tok::kw_void:
case tok::kw_char:
case tok::kw_int:
case tok::kw_half:
case tok::kw_float:
case tok::kw_double:
case tok::kw___float128:
case tok::kw_wchar_t:
case tok::kw_bool:
case tok::kw___underlying_type:
case tok::kw___auto_type:
return true;
case tok::annot_typename:
case tok::kw_char16_t:
case tok::kw_char32_t:
case tok::kw_typeof:
case tok::annot_decltype:
case tok::kw_decltype:
return getLangOpts().CPlusPlus;
return false;
namespace {
enum class UnqualifiedTypeNameLookupResult {
} // end anonymous namespace
/// \brief Tries to perform unqualified lookup of the type decls in bases for
/// dependent class.
/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
/// type decl, \a FoundType if only type decls are found.
static UnqualifiedTypeNameLookupResult
lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
SourceLocation NameLoc,
const CXXRecordDecl *RD) {
if (!RD->hasDefinition())
return UnqualifiedTypeNameLookupResult::NotFound;
// Look for type decls in base classes.
UnqualifiedTypeNameLookupResult FoundTypeDecl =
for (const auto &Base : RD->bases()) {
const CXXRecordDecl *BaseRD = nullptr;
if (auto *BaseTT = Base.getType()->getAs<TagType>())
BaseRD = BaseTT->getAsCXXRecordDecl();
else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
// Look for type decls in dependent base classes that have known primary
// templates.
if (!TST || !TST->isDependentType())
auto *TD = TST->getTemplateName().getAsTemplateDecl();
if (!TD)
if (auto *BasePrimaryTemplate =
dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
BaseRD = BasePrimaryTemplate;
else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
if (const ClassTemplatePartialSpecializationDecl *PS =
if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
BaseRD = PS;
if (BaseRD) {
for (NamedDecl *ND : BaseRD->lookup(&II)) {
if (!isa<TypeDecl>(ND))
return UnqualifiedTypeNameLookupResult::FoundNonType;
FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
case UnqualifiedTypeNameLookupResult::FoundNonType:
return UnqualifiedTypeNameLookupResult::FoundNonType;
case UnqualifiedTypeNameLookupResult::FoundType:
FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
case UnqualifiedTypeNameLookupResult::NotFound:
return FoundTypeDecl;
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
const IdentifierInfo &II,
SourceLocation NameLoc) {
// Lookup in the parent class template context, if any.
const CXXRecordDecl *RD = nullptr;
UnqualifiedTypeNameLookupResult FoundTypeDecl =
for (DeclContext *DC = S.CurContext;
DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
DC = DC->getParent()) {
// Look for type decls in dependent base classes that have known primary
// templates.
RD = dyn_cast<CXXRecordDecl>(DC);
if (RD && RD->getDescribedClassTemplate())
FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
return nullptr;
// We found some types in dependent base classes. Recover as if the user
// wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
// lookup during template instantiation.
S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
ASTContext &Context = S.Context;
auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
CXXScopeSpec SS;
SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
TypeLocBuilder Builder;
DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
/// \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.
ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec *SS,
bool isClassName, bool HasTrailingDot,
ParsedType ObjectTypePtr,
bool IsCtorOrDtorName,
bool WantNontrivialTypeSourceInfo,
bool IsClassTemplateDeductionContext,
IdentifierInfo **CorrectedII) {
// FIXME: Consider allowing this outside C++1z mode as an extension.
bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
!isClassName && !HasTrailingDot;
// Determine where we will perform name lookup.
DeclContext *LookupCtx = nullptr;
if (ObjectTypePtr) {
QualType ObjectType = ObjectTypePtr.get();
if (ObjectType->isRecordType())
LookupCtx = computeDeclContext(ObjectType);
} else if (SS && SS->isNotEmpty()) {
LookupCtx = computeDeclContext(*SS, false);
if (!LookupCtx) {
if (isDependentScopeSpecifier(*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 (
// We therefore do not perform any name lookup if the result would
// refer to a member of an unknown specialization.
if (!isClassName && !IsCtorOrDtorName)
return nullptr;
// We know from the grammar that this name refers to a type,
// so build a dependent node to describe the type.
if (WantNontrivialTypeSourceInfo)
return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
II, NameLoc);
return ParsedType::make(T);
return nullptr;
if (!LookupCtx->isDependentContext() &&
RequireCompleteDeclContext(*SS, LookupCtx))
return nullptr;
// FIXME: LookupNestedNameSpecifierName isn't the right kind of
// lookup for class-names.
LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
LookupResult Result(*this, &II, NameLoc, Kind);
if (LookupCtx) {
// Perform "qualified" name lookup into the declaration context we
// computed, which is either the type of the base of a member access
// expression or the declaration context associated with a prior
// nested-name-specifier.
LookupQualifiedName(Result, LookupCtx);
if (ObjectTypePtr && Result.empty()) {
// C++ [basic.lookup.classref]p3:
// If the unqualified-id is ~type-name, the type-name is looked up
// in the context of the entire postfix-expression. If the type T of
// the object expression is of a class type C, the type-name is also
// looked up in the scope of class C. At least one of the lookups shall
// find a name that refers to (possibly cv-qualified) T.
LookupName(Result, S);
} else {
// Perform unqualified name lookup.
LookupName(Result, S);
// For unqualified lookup in a class template in MSVC mode, look into
// dependent base classes where the primary class template is known.
if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
if (ParsedType TypeInBase =
recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
return TypeInBase;
NamedDecl *IIDecl = nullptr;
switch (Result.getResultKind()) {
case LookupResult::NotFound:
case LookupResult::NotFoundInCurrentInstantiation:
if (CorrectedII) {
TypoCorrection Correction =
CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
true, isClassName, AllowDeducedTemplate),
IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
TemplateTy Template;
bool MemberOfUnknownSpecialization;
UnqualifiedId TemplateName;
TemplateName.setIdentifier(NewII, NameLoc);
NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
CXXScopeSpec NewSS, *NewSSPtr = SS;
if (SS && NNS) {
NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
NewSSPtr = &NewSS;
if (Correction && (NNS || NewII != &II) &&
// Ignore a correction to a template type as the to-be-corrected
// identifier is not a template (typo correction for template names
// is handled elsewhere).
!(getLangOpts().CPlusPlus && NewSSPtr &&
isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
Template, MemberOfUnknownSpecialization))) {
ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
isClassName, HasTrailingDot, ObjectTypePtr,
if (Ty) {
<< Result.getLookupName() << isClassName);
if (SS && NNS)
SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
*CorrectedII = NewII;
return Ty;
// If typo correction failed or was not performed, fall through
case LookupResult::FoundOverloaded:
case LookupResult::FoundUnresolvedValue:
return nullptr;
case LookupResult::Ambiguous:
// Recover from type-hiding ambiguities by hiding the type. We'll
// do the lookup again when looking for an object, and we can
// diagnose the error then. If we don't do this, then the error
// about hiding the type will be immediately followed by an error
// that only makes sense if the identifier was treated like a type.
if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
return nullptr;
// 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) ||
(AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
if (!IIDecl ||
(*Res)->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.
return nullptr;
// 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.
case LookupResult::Found:
IIDecl = Result.getFoundDecl();
assert(IIDecl && "Didn't find decl");
QualType T;
if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
// C++ [class.qual]p2: A lookup that would find the injected-class-name
// instead names the constructors of the class, except when naming a class.
// This is ill-formed when we're not actually forming a ctor or dtor name.
auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
FoundRD->isInjectedClassName() &&
declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
<< &II << /*Type*/1;
DiagnoseUseOfDecl(IIDecl, NameLoc);
T = Context.getTypeDeclType(TD);
MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
} else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
(void)DiagnoseUseOfDecl(IDecl, NameLoc);
if (!HasTrailingDot)
T = Context.getObjCInterfaceType(IDecl);
} else if (AllowDeducedTemplate) {
if (auto *TD = getAsTypeTemplateDecl(IIDecl))
T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
QualType(), false);
if (T.isNull()) {
// If it's not plausibly a type, suppress diagnostics.
return nullptr;
// NOTE: avoid constructing an ElaboratedType(Loc) if this is a
// constructor or destructor name (in such a case, the scope specifier
// will be attached to the enclosing Expr or Decl node).
if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
!isa<ObjCInterfaceDecl>(IIDecl)) {
if (WantNontrivialTypeSourceInfo) {
// Construct a type with type-source information.
TypeLocBuilder Builder;
T = getElaboratedType(ETK_None, *SS, T);
ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
} else {
T = getElaboratedType(ETK_None, *SS, T);
return ParsedType::make(T);
// Builds a fake NNS for the given decl context.
static NestedNameSpecifier *
synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
for (;; DC = DC->getLookupParent()) {
DC = DC->getPrimaryContext();
auto *ND = dyn_cast<NamespaceDecl>(DC);
if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
return NestedNameSpecifier::Create(Context, nullptr, ND);
else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
else if (isa<TranslationUnitDecl>(DC))
return NestedNameSpecifier::GlobalSpecifier(Context);
llvm_unreachable("something isn't in TU scope?");
/// Find the parent class with dependent bases of the innermost enclosing method
/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
/// up allowing unqualified dependent type names at class-level, which MSVC
/// correctly rejects.
static const CXXRecordDecl *
findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
DC = DC->getPrimaryContext();
if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
if (MD->getParent()->hasAnyDependentBases())
return MD->getParent();
return nullptr;
ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
SourceLocation NameLoc,
bool IsTemplateTypeArg) {
assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
NestedNameSpecifier *NNS = nullptr;
if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
// If we weren't able to parse a default template argument, delay lookup
// until instantiation time by making a non-dependent DependentTypeName. We
// pretend we saw a NestedNameSpecifier referring to the current scope, and
// lookup is retried.
// FIXME: This hurts our diagnostic quality, since we get errors like "no
// type named 'Foo' in 'current_namespace'" when the user didn't write any
// name specifiers.
NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
} else if (const CXXRecordDecl *RD =
findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
// Build a DependentNameType that will perform lookup into RD at
// instantiation time.
NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
// Diagnose that this identifier was undeclared, and retry the lookup during
// template instantiation.
Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
<< RD;
} else {
// This is not a situation that we should recover from.
return ParsedType();
QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
// Build type location information. We synthesized the qualifier, so we have
// to build a fake NestedNameSpecifierLoc.
NestedNameSpecifierLocBuilder NNSLocBuilder;
NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
TypeLocBuilder Builder;
DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
/// 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_interface, 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(*this, &II, SourceLocation(), LookupTagName);
LookupName(R, S, false);
if (R.getResultKind() == LookupResult::Found)
if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
switch (TD->getTagKind()) {
case TTK_Struct: return DeclSpec::TST_struct;
case TTK_Interface: return DeclSpec::TST_interface;
case TTK_Union: return DeclSpec::TST_union;
case TTK_Class: return DeclSpec::TST_class;
case TTK_Enum: return DeclSpec::TST_enum;
return DeclSpec::TST_unspecified;
/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
/// if a CXXScopeSpec's type is equal to the type of one of the base classes
/// then downgrade the missing typename error to a warning.
/// This is needed for MSVC compatibility; Example:
/// @code
/// template<class T> class A {
/// public:
/// typedef int TYPE;
/// };
/// template<class T> class B : public A<T> {
/// public:
/// A<T>::TYPE a; // no typename required because A<T> is a base class.
/// };
/// @endcode
bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
if (CurContext->isRecord()) {
if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
return true;
const Type *Ty = SS->getScopeRep()->getAsType();
CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
for (const auto &Base : RD->bases())
if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
return true;
return S->isFunctionPrototypeScope();
return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
SourceLocation IILoc,
Scope *S,
CXXScopeSpec *SS,
ParsedType &SuggestedType,
bool IsTemplateName) {
// Don't report typename errors for editor placeholders.
if (II->isEditorPlaceholder())
// We don't have anything to suggest (yet).
SuggestedType = nullptr;
// There may have been a typo in the name of the type. Look up typo
// results, in case we have something that we can suggest.
if (TypoCorrection Corrected =
CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
false, false, IsTemplateName, !IsTemplateName),
CTK_ErrorRecovery)) {
// FIXME: Support error recovery for the template-name case.
bool CanRecover = !IsTemplateName;
if (Corrected.isKeyword()) {
// We corrected to a keyword.
PDiag(IsTemplateName ? diag::err_no_template_suggest
: diag::err_unknown_typename_suggest)
<< II);
II = Corrected.getCorrectionAsIdentifierInfo();
} else {
// We found a similarly-named type or interface; suggest that.
if (!SS || !SS->isSet()) {
PDiag(IsTemplateName ? diag::err_no_template_suggest
: diag::err_unknown_typename_suggest)
<< II, CanRecover);
} else if (DeclContext *DC = computeDeclContext(*SS, false)) {
std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
? diag::err_no_member_template_suggest
: diag::err_unknown_nested_typename_suggest)
<< II << DC << DroppedSpecifier << SS->getRange(),
} else {
llvm_unreachable("could not have corrected a typo here");
if (!CanRecover)
CXXScopeSpec tmpSS;
if (Corrected.getCorrectionSpecifier())
tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
// FIXME: Support class template argument deduction here.
SuggestedType =
getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
if (getLangOpts().CPlusPlus && !IsTemplateName) {
// See if II is a class template that the user forgot to pass arguments to.
UnqualifiedId Name;
Name.setIdentifier(II, IILoc);
CXXScopeSpec EmptySS;
TemplateTy TemplateResult;
bool MemberOfUnknownSpecialization;
if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
Name, nullptr, true, TemplateResult,
MemberOfUnknownSpecialization) == TNK_Type_template) {
TemplateName TplName = TemplateResult.get();
Diag(IILoc, diag::err_template_missing_args)
<< (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
Diag(TplDecl->getLocation(), diag::note_template_decl_here)
<< TplDecl->getTemplateParameters()->getSourceRange();
// FIXME: Should we move the logic that tries to recover from a missing tag
// (struct, union, enum) from Parser::ParseImplicitInt here, instead?
if (!SS || (!SS->isSet() && !SS->isInvalid()))
Diag(IILoc, IsTemplateName ? diag::err_no_template
: diag::err_unknown_typename)
<< II;
else if (DeclContext *DC = computeDeclContext(*SS, false))
Diag(IILoc, IsTemplateName ? diag::err_no_member_template
: diag::err_typename_nested_not_found)
<< II << DC << SS->getRange();
else if (isDependentScopeSpecifier(*SS)) {
unsigned DiagID = diag::err_typename_missing;
if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
DiagID = diag::ext_typename_missing;
Diag(SS->getRange().getBegin(), DiagID)
<< SS->getScopeRep() << II->getName()
<< SourceRange(SS->getRange().getBegin(), IILoc)
<< FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
SuggestedType = ActOnTypenameType(S, SourceLocation(),
*SS, *II, IILoc).get();
} else {
assert(SS && SS->isInvalid() &&
"Invalid scope specifier has already been diagnosed");
/// \brief Determine whether the given result set contains either a type name
/// or
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&;
for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
return true;
if (CheckTemplate && isa<TemplateDecl>(*I))
return true;
return false;
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
Scope *S, CXXScopeSpec &SS,
IdentifierInfo *&Name,
SourceLocation NameLoc) {
LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
SemaRef.LookupParsedName(R, S, &SS);
if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
StringRef FixItTagName;
switch (Tag->getTagKind()) {
case TTK_Class:
FixItTagName = "class ";
case TTK_Enum:
FixItTagName = "enum ";
case TTK_Struct:
FixItTagName = "struct ";
case TTK_Interface:
FixItTagName = "__interface ";
case TTK_Union:
FixItTagName = "union ";
StringRef TagName = FixItTagName.drop_back();
SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
<< Name << TagName << SemaRef.getLangOpts().CPlusPlus
<< FixItHint::CreateInsertion(NameLoc, FixItTagName);
for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
I != IEnd; ++I)
SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
<< Name << TagName;
// Replace lookup results with just the tag decl.
SemaRef.LookupParsedName(Result, S, &SS);
return true;
return false;
/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
QualType T, SourceLocation NameLoc) {
ASTContext &Context = S.Context;
TypeLocBuilder Builder;
T = S.getElaboratedType(ETK_None, SS, T);
ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
SourceLocation NameLoc, const Token &NextToken,
bool IsAddressOfOperand,
std::unique_ptr<CorrectionCandidateCallback> CCC) {
DeclarationNameInfo NameInfo(Name, NameLoc);
ObjCMethodDecl *CurMethod = getCurMethodDecl();
if ( {
NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
} else if (getLangOpts().CPlusPlus && SS.isSet() &&
isCurrentClassName(*Name, S, &SS)) {
// Per [class.qual]p2, this names the constructors of SS, not the
// injected-class-name. We don't have a classification for that.
// There's not much point caching this result, since the parser
// will reject it later.
return NameClassification::Unknown();
LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
LookupParsedName(Result, S, &SS, !CurMethod);
// For unqualified lookup in a class template in MSVC mode, look into
// dependent base classes where the primary class template is known.
if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
if (ParsedType TypeInBase =
recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
return TypeInBase;
// Perform lookup for Objective-C instance variables (including automatically
// synthesized instance variables), if we're in an Objective-C method.
// FIXME: This lookup really, really needs to be folded in to the normal
// unqualified lookup mechanism.
if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
ExprResult E = LookupInObjCMethod(Result, S, Name, true);
if (E.get() || E.isInvalid())
return E;
bool SecondTry = false;
bool IsFilteredTemplateName = false;
switch (Result.getResultKind()) {
case LookupResult::NotFound:
// If an unqualified-id is followed by a '(', then we have a function
// call.
if (!SS.isSet() && {
// In C++, this is an ADL-only call.
// FIXME: Reference?
if (getLangOpts().CPlusPlus)
return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
// C90
// If the expression that precedes the parenthesized argument list in a
// function call consists solely of an identifier, and if no
// declaration is visible for this identifier, the identifier is
// implicitly declared exactly as if, in the innermost block containing
// the function call, the declaration
// extern int identifier ();
// appeared.
// We also allow this in C99 as an extension.
if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
// In C, we first see whether there is a tag type by the same name, in
// which case it's likely that the user just forgot to write "enum",
// "struct", or "union".
if (!getLangOpts().CPlusPlus && !SecondTry &&
isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
// Perform typo correction to determine if there is another name that is
// close to this name.
if (!SecondTry && CCC) {
SecondTry = true;
if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
Result.getLookupKind(), S,
&SS, std::move(CCC),
CTK_ErrorRecovery)) {
unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
unsigned QualifiedDiag = diag::err_no_member_suggest;
NamedDecl *FirstDecl = Corrected.getFoundDecl();
NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
if (getLangOpts().CPlusPlus && &&
UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
UnqualifiedDiag = diag::err_no_template_suggest;
QualifiedDiag = diag::err_no_member_template_suggest;
} else if (UnderlyingFirstDecl &&
(isa<TypeDecl>(UnderlyingFirstDecl) ||
isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
UnqualifiedDiag = diag::err_unknown_typename_suggest;
QualifiedDiag = diag::err_unknown_nested_typename_suggest;
if (SS.isEmpty()) {
diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
} else {// FIXME: is this even reachable? Test it.
std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
diagnoseTypo(Corrected, PDiag(QualifiedDiag)
<< Name << computeDeclContext(SS, false)
<< DroppedSpecifier << SS.getRange());
// Update the name, so that the caller has the new name.
Name = Corrected.getCorrectionAsIdentifierInfo();
// Typo correction corrected to a keyword.
if (Corrected.isKeyword())
return Name;
// Also update the LookupResult...
// FIXME: This should probably go away at some point
if (FirstDecl)
// If we found an Objective-C instance variable, let
// LookupInObjCMethod build the appropriate expression to
// reference the ivar.
// FIXME: This is a gross hack.
if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
return E;
goto Corrected;
// We failed to correct; just fall through and let the parser deal with it.
return NameClassification::Unknown();
case LookupResult::NotFoundInCurrentInstantiation: {
// We performed name lookup into the current instantiation, and there were
// dependent bases, so we treat this result the same way as any other
// dependent nested-name-specifier.
// C++ [temp.res]p2:
// A name used in a template declaration or definition and that is
// dependent on a template-parameter is assumed not to name a type
// unless the applicable name lookup finds a type name or the name is
// qualified by the keyword typename.
// FIXME: If the next token is '<', we might want to ask the parser to
// perform some heroics to see if we actually have a
// template-argument-list, which would indicate a missing 'template'
// keyword here.
return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
NameInfo, IsAddressOfOperand,
case LookupResult::Found:
case LookupResult::FoundOverloaded:
case LookupResult::FoundUnresolvedValue:
case LookupResult::Ambiguous:
if (getLangOpts().CPlusPlus && &&
hasAnyAcceptableTemplateNames(Result)) {
// C++ [temp.local]p3:
// A lookup that finds an injected-class-name (10.2) can result in an
// ambiguity in certain cases (for example, if it is found in more than
// one base class). If all of the injected-class-names that are found
// refer to specializations of the same class template, and if the name
// is followed by a template-argument-list, the reference refers to the
// class template itself and not a specialization thereof, and is not
// ambiguous.
// This filtering can make an ambiguous result into an unambiguous one,
// so try again after filtering out template names.
if (!Result.isAmbiguous()) {
IsFilteredTemplateName = true;
// Diagnose the ambiguity and return an error.
return NameClassification::Error();
if (getLangOpts().CPlusPlus && &&
(IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
// C++ [temp.names]p3:
// After name lookup (3.4) finds that a name is a template-name or that
// an operator-function-id or a literal- operator-id refers to a set of
// overloaded functions any member of which is a function template if
// this is followed by a <, the < is always taken as the delimiter of a
// template-argument-list and never as the less-than operator.
if (!IsFilteredTemplateName)
if (!Result.empty()) {
bool IsFunctionTemplate;
bool IsVarTemplate;
TemplateName Template;
if (Result.end() - Result.begin() > 1) {
IsFunctionTemplate = true;
Template = Context.getOverloadedTemplateName(Result.begin(),
} else {
TemplateDecl *TD
= cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
IsVarTemplate = isa<VarTemplateDecl>(TD);
if (SS.isSet() && !SS.isInvalid())
Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Template = TemplateName(TD);
if (IsFunctionTemplate) {
// Function templates always go through overload resolution, at which
// point we'll perform the various checks (e.g., accessibility) we need
// to based on which function we selected.
return NameClassification::FunctionTemplate(Template);
return IsVarTemplate ? NameClassification::VarTemplate(Template)
: NameClassification::TypeTemplate(Template);
NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
DiagnoseUseOfDecl(Type, NameLoc);
MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
QualType T = Context.getTypeDeclType(Type);
if (SS.isNotEmpty())
return buildNestedType(*this, SS, T, NameLoc);
return ParsedType::make(T);
ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
if (!Class) {
// FIXME: It's unfortunate that we don't have a Type node for handling this.
if (ObjCCompatibleAliasDecl *Alias =
Class = Alias->getClassInterface();
if (Class) {
DiagnoseUseOfDecl(Class, NameLoc);
if ( {
// Interface. <something> is parsed as a property reference expression.
// Just return "unknown" as a fall-through for now.
return NameClassification::Unknown();
QualType T = Context.getObjCInterfaceType(Class);
return ParsedType::make(T);
// We can have a type template here if we're classifying a template argument.
if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
return NameClassification::TypeTemplate(
// Check for a tag type hidden by a non-type decl in a few cases where it
// seems likely a type is wanted instead of the non-type that was found.
bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
if (( ||
(NextIsOp &&
FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
TypeDecl *Type = Result.getAsSingle<TypeDecl>();
DiagnoseUseOfDecl(Type, NameLoc);
QualType T = Context.getTypeDeclType(Type);
if (SS.isNotEmpty())
return buildNestedType(*this, SS, T, NameLoc);
return ParsedType::make(T);
if (FirstDecl->isCXXClassMember())
return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
nullptr, S);
bool ADL = UseArgumentDependentLookup(SS, Result,;
return BuildDeclarationNameExpr(SS, Result, ADL);
Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
auto *TD = Name.getAsTemplateDecl();
if (!TD)
return TemplateNameKindForDiagnostics::DependentTemplate;
if (isa<ClassTemplateDecl>(TD))
return TemplateNameKindForDiagnostics::ClassTemplate;
if (isa<FunctionTemplateDecl>(TD))
return TemplateNameKindForDiagnostics::FunctionTemplate;
if (isa<VarTemplateDecl>(TD))
return TemplateNameKindForDiagnostics::VarTemplate;
if (isa<TypeAliasTemplateDecl>(TD))
return TemplateNameKindForDiagnostics::AliasTemplate;
if (isa<TemplateTemplateParmDecl>(TD))
return TemplateNameKindForDiagnostics::TemplateTemplateParam;
return TemplateNameKindForDiagnostics::DependentTemplate;
// Determines the context to return to after temporarily entering a
// context. This depends in an unnecessarily complicated way on the
// exact ordering of callbacks from the parser.
DeclContext *Sema::getContainingDC(DeclContext *DC) {
// Functions defined inline within classes aren't parsed until we've
// finished parsing the top-level class, so the top-level class is
// the context we'll need to return to.
// A Lambda call operator whose parent is a class must not be treated
// as an inline member function. A Lambda can be used legally
// either as an in-class member initializer or a default argument. These
// are parsed once the class has been marked complete and so the containing
// context would be the nested class (when the lambda is defined in one);
// If the class is not complete, then the lambda is being used in an
// ill-formed fashion (such as to specify the width of a bit-field, or
// in an array-bound) - in which case we still want to return the
// lexically containing DC (which could be a nested class).
if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
DC = DC->getLexicalParent();
// A function not defined within a class will always return to its
// lexical context.
if (!isa<CXXRecordDecl>(DC))
return DC;
// A C++ inline method/friend is parsed *after* the topmost class
// it was declared in is fully parsed ("complete"); the topmost
// class is the context we need to return to.
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;
return DC->getLexicalParent();
void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
assert(getContainingDC(DC) == CurContext &&
"The next DeclContext should be lexically contained in the current one.");
CurContext = DC;
void Sema::PopDeclContext() {
assert(CurContext && "DeclContext imbalance!");
CurContext = getContainingDC(CurContext);
assert(CurContext && "Popped translation unit!");
Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
Decl *D) {
// Unlike PushDeclContext, the context to which we return is not necessarily
// the containing DC of TD, because the new context will be some pre-existing
// TagDecl definition instead of a fresh one.
auto Result = static_cast<SkippedDefinitionContext>(CurContext);
CurContext = cast<TagDecl>(D)->getDefinition();
assert(CurContext && "skipping definition of undefined tag");
// Start lookups from the parent of the current context; we don't want to look
// into the pre-existing complete definition.
return Result;
void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
CurContext = static_cast<decltype(CurContext)>(Context);
/// EnterDeclaratorContext - Used when we must lookup names in the context
/// of a declarator's nested name specifier.
void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
// C++0x [basic.lookup.unqual]p13:
// A name used in the definition of a static data member of class
// X (after the qualified-id of the static member) is looked up as
// if the name was used in a member function of X.
// C++0x [basic.lookup.unqual]p14:
// If a variable member of a namespace is defined outside of the
// scope of its namespace then any name used in the definition of
// the variable member (after the declarator-id) is looked up as
// if the definition of the variable member occurred in its
// namespace.
// Both of these imply that we should push a scope whose context
// is the semantic context of the declaration. We can't use
// PushDeclContext here because that context is not necessarily
// lexically contained in the current context. Fortunately,
// the containing scope should have the appropriate information.
assert(!S->getEntity() && "scope already has entity");
#ifndef NDEBUG
Scope *Ancestor = S->getParent();
while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
CurContext = DC;
void Sema::ExitDeclaratorContext(Scope *S) {
assert(S->getEntity() == CurContext && "Context imbalance!");
// Switch back to the lexical context. The safety of this is
// enforced by an assert in EnterDeclaratorContext.
Scope *Ancestor = S->getParent();
while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
CurContext = Ancestor->getEntity();
// We don't need to do anything with the scope, which is going to
// disappear.
void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
// We assume that the caller has already called
// ActOnReenterTemplateScope so getTemplatedDecl() works.
FunctionDecl *FD = D->getAsFunction();
if (!FD)
// Same implementation as PushDeclContext, but enters the context
// from the lexical parent, rather than the top-level class.
assert(CurContext == FD->getLexicalParent() &&
"The next DeclContext should be lexically contained in the current one.");
CurContext = FD;
for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
ParmVarDecl *Param = FD->getParamDecl(P);
// If the parameter has an identifier, then add it to the scope
if (Param->getIdentifier()) {
void Sema::ActOnExitFunctionContext() {
// Same implementation as PopDeclContext, but returns to the lexical parent,
// rather than the top-level class.
assert(CurContext && "DeclContext imbalance!");
CurContext = CurContext->getLexicalParent();
assert(CurContext && "Popped translation unit!");
/// \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(LookupResult &Previous,
ASTContext &Context,
const FunctionDecl *New) {
if (Context.getLangOpts().CPlusPlus)
return true;
if (Previous.getResultKind() == LookupResult::FoundOverloaded)
return true;
return Previous.getResultKind() == LookupResult::Found &&
(Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
/// Add this decl to the scope shadowed decl chains.
void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
// 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() && S->getEntity()->isTransparentContext())
S = S->getParent();
// Add scoped declarations into their context, so that they can be
// found later. Declarations without a context won't be inserted
// into any context.
if (AddToContext)
// Out-of-line definitions shouldn't be pushed into scope in C++, unless they
// are function-local declarations.
if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
D->getLexicalDeclContext()->getRedeclContext()) &&
// Template instantiations should also not be pushed into scope.
if (isa<FunctionDecl>(D) &&
// If this replaces anything in the current scope,
IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
IEnd = IdResolver.end();
for (; I != IEnd; ++I) {
if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
// Should only need to replace one decl.
if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
// Implicitly-generated labels may end up getting generated in an order that
// isn't strictly lexical, which breaks name lookup. Be careful to insert
// the label at the appropriate place in the identifier chain.
for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
if (IDC == CurContext) {
if (!S->isDeclScope(*I))
} else if (IDC->Encloses(CurContext))
IdResolver.InsertDeclAfter(I, D);
} else {
void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
bool AllowInlineNamespace) {
return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
DeclContext *TargetDC = DC->getPrimaryContext();
do {
if (DeclContext *ScopeDC = S->getEntity())
if (ScopeDC->getPrimaryContext() == TargetDC)
return S;
} while ((S = S->getParent()));
return nullptr;
static bool isOutOfScopePreviousDeclaration(NamedDecl *,
/// Filters out lookup results that don't fall within the given scope
/// as determined by isDeclInScope.
void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
bool ConsiderLinkage,
bool AllowInlineNamespace) {
LookupResult::Filter F = R.makeFilter();
while (F.hasNext()) {
NamedDecl *D =;
if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
static bool isUsingDecl(NamedDecl *D) {
return isa<UsingShadowDecl>(D) ||
isa<UnresolvedUsingTypenameDecl>(D) ||
/// Removes using shadow declarations from the lookup results.
static void RemoveUsingDecls(LookupResult &R) {
LookupResult::Filter F = R.makeFilter();
while (F.hasNext())
if (isUsingDecl(
/// \brief Check for this common pattern:
/// @code
/// class S {
/// S(const S&); // DO NOT IMPLEMENT
/// void operator=(const S&); // DO NOT IMPLEMENT
/// };
/// @endcode
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
// FIXME: Should check for private access too but access is set after we get
// the decl here.
if (D->doesThisDeclarationHaveABody())
return false;
if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
return CD->isCopyConstructor();
if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
return Method->isCopyAssignmentOperator();
return false;
// We need this to handle
// typedef struct {
// void *foo() { return 0; }
// } A;
// When we see foo we don't know if after the typedef we will get 'A' or '*A'
// for example. If 'A', foo will have external linkage. If we have '*A',
// foo will have no linkage. Since we can't know until we get to the end
// of the typedef, this function finds out if D might have non-external linkage.
// Callers should verify at the end of the TU if it D has external linkage or
// not.
bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
const DeclContext *DC = D->getDeclContext();
while (!DC->isTranslationUnit()) {
if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
if (!RD->hasNameForLinkage())
return true;
DC = DC->getParent();
return !D->isExternallyVisible();
// FIXME: This needs to be refactored; some other isInMainFile users want
// these semantics.
static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
if (S.TUKind != TU_Complete)
return false;
return S.SourceMgr.isInMainFile(Loc);
bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
return false;
// Ignore all entities declared within templates, and out-of-line definitions
// of members of class templates.
if (D->getDeclContext()->isDependentContext() ||
return false;
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
return false;
// A non-out-of-line declaration of a member specialization was implicitly
// instantiated; it's the out-of-line declaration that we're interested in.
if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
return false;
if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
return false;
} else {
// 'static inline' functions are defined in headers; don't warn.
if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
return false;
if (FD->doesThisDeclarationHaveABody() &&
return false;
} else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
// Constants and utility variables are defined in headers with internal
// linkage; don't warn. (Unlike functions, there isn't a convenient marker
// like "inline".)
if (!isMainFileLoc(*this, VD->getLocation()))
return false;
if (Context.DeclMustBeEmitted(VD))
return false;
if (VD->isStaticDataMember() &&
VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
return false;
if (VD->isStaticDataMember() &&
VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
return false;
if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
return false;
} else {
return false;
// Only warn for unused decls internal to the translation unit.
// FIXME: This seems like a bogus check; it suppresses -Wunused-function
// for inline functions defined in the main source file, for instance.
return mightHaveNonExternalLinkage(D);
void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
if (!D)
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
const FunctionDecl *First = FD->getFirstDecl();
if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
return; // First should already be in the vector.
if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
const VarDecl *First = VD->getFirstDecl();
if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
return; // First should already be in the vector.
if (ShouldWarnIfUnusedFileScopedDecl(D))
static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
if (D->isInvalidDecl())
return false;
if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
return false;
if (isa<LabelDecl>(D))
return true;
// Except for labels, we only care about unused decls that are local to
// functions.
bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
// For dependent types, the diagnostic is deferred.
WithinFunction =
WithinFunction || (R->isLocalClass() && !R->isDependentType());
if (!WithinFunction)
return false;
if (isa<TypedefNameDecl>(D))
return true;
// White-list anything that isn't a local variable.
if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
return false;
// Types of valid local variables should be complete, so this should succeed.
if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
// White-list anything with an __attribute__((unused)) type.
const auto *Ty = VD->getType().getTypePtr();
// Only look at the outermost level of typedef.
if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
if (TT->getDecl()->hasAttr<UnusedAttr>())
return false;
// If we failed to complete the type for some reason, or if the type is
// dependent, don't diagnose the variable.
if (Ty->isIncompleteType() || Ty->isDependentType())
return false;
// Look at the element type to ensure that the warning behaviour is
// consistent for both scalars and arrays.
Ty = Ty->getBaseElementTypeUnsafe();
if (const TagType *TT = Ty->getAs<TagType>()) {
const TagDecl *Tag = TT->getDecl();
if (Tag->hasAttr<UnusedAttr>())
return false;
if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
return false;
if (const Expr *Init = VD->getInit()) {
if (const ExprWithCleanups *Cleanups =
Init = Cleanups->getSubExpr();
const CXXConstructExpr *Construct =
if (Construct && !Construct->isElidable()) {
CXXConstructorDecl *CD = Construct->getConstructor();
if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
return false;
// TODO: __attribute__((unused)) templates?
return true;
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
FixItHint &Hint) {
if (isa<LabelDecl>(D)) {
SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
if (AfterColon.isInvalid())
Hint = FixItHint::CreateRemoval(CharSourceRange::
getCharRange(D->getLocStart(), AfterColon));
void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
if (D->getTypeForDecl()->isDependentType())
for (auto *TmpD : D->decls()) {
if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
/// unless they are marked attr(unused).
void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
if (!ShouldDiagnoseUnusedDecl(D))
if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
// typedefs can be referenced later on, so the diagnostics are emitted
// at end-of-translation-unit.
FixItHint Hint;
GenerateFixForUnusedDecl(D, Context, Hint);
unsigned DiagID;
if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
DiagID = diag::warn_unused_exception_param;
else if (isa<LabelDecl>(D))
DiagID = diag::warn_unused_label;
DiagID = diag::warn_unused_variable;
Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
// Verify that we have no forward references left. If so, there was a goto
// or address of a label taken, but no definition of it. Label fwd
// definitions are indicated with a null substmt which is also not a resolved
// MS inline assembly label name.
bool Diagnose = false;
if (L->isMSAsmLabel())
Diagnose = !L->isResolvedMSAsmLabel();
Diagnose = L->getStmt() == nullptr;
if (Diagnose)
S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
if (S->decl_empty()) return;
assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
"Scope shouldn't contain decls!");
for (auto *TmpD : S->decls()) {
assert(TmpD && "This decl didn't get pushed??");
assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
NamedDecl *D = cast<NamedDecl>(TmpD);
if (!D->getDeclName()) continue;
// Diagnose unused variables in this scope.
if (!S->hasUnrecoverableErrorOccurred()) {
if (const auto *RD = dyn_cast<RecordDecl>(D))
// If this was a forward reference to a label, verify it was defined.
if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
CheckPoppedLabel(LD, *this);
// Remove this name from our lexical scope, and warn on it if we haven't
// already.
auto ShadowI = ShadowingDecls.find(D);
if (ShadowI != ShadowingDecls.end()) {
if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
<< D << FD << FD->getParent();
Diag(FD->getLocation(), diag::note_previous_declaration);
/// \brief Look for an Objective-C class in the translation unit.
/// \param Id The name of the Objective-C class we're looking for. If
/// typo-correction fixes this name, the Id will be updated
/// to the fixed name.
/// \param IdLoc The location of the name in the translation unit.
/// \param DoTypoCorrection If true, this routine will attempt typo correction
/// if there is no class with the given name.
/// \returns The declaration of the named Objective-C class, or NULL if the
/// class could not be found.
ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
SourceLocation IdLoc,
bool DoTypoCorrection) {
// The third "scope" argument is 0 since we aren't enabling lazy built-in
// creation from this context.
NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
if (!IDecl && DoTypoCorrection) {
// Perform typo correction at the given location, but only if we
// find an Objective-C class name.
if (TypoCorrection C = CorrectTypo(
DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
CTK_ErrorRecovery)) {
diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Id = IDecl->getIdentifier();
ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
// This routine must always return a class definition, if any.
if (Def && Def->getDefinition())
Def = Def->getDefinition();
return Def;
/// 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() && S->getEntity()->isTransparentContext()) ||
(S->isClassScope() && !getLangOpts().CPlusPlus))
S = S->getParent();
return S;
/// \brief Looks up the declaration of "struct objc_super" and
/// saves it for later use in building builtin declaration of
/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
/// pre-existing declaration exists no action takes place.
static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
IdentifierInfo *II) {
if (!II->isStr("objc_msgSendSuper"))
ASTContext &Context = ThisSema.Context;
LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
SourceLocation(), Sema::LookupTagName);
ThisSema.LookupName(Result, S);
if (Result.getResultKind() == LookupResult::Found)
if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
switch (Error) {
case ASTContext::GE_None:
return "";
case ASTContext::GE_Missing_stdio:
return "stdio.h";
case ASTContext::GE_Missing_setjmp:
return "setjmp.h";
case ASTContext::GE_Missing_ucontext:
return "ucontext.h";
llvm_unreachable("unhandled error kind");
/// 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 ID,
Scope *S, bool ForRedeclaration,
SourceLocation Loc) {
LookupPredefedObjCSuperType(*this, S, II);
ASTContext::GetBuiltinTypeError Error;
QualType R = Context.GetBuiltinType(ID, Error);
if (Error) {
if (ForRedeclaration)
Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
<< getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
return nullptr;
if (!ForRedeclaration &&
(Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
Diag(Loc, diag::ext_implicit_lib_function_decl)
<< Context.BuiltinInfo.getName(ID) << R;
if (Context.BuiltinInfo.getHeaderName(ID) &&
!Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
Diag(Loc, diag::note_include_header_or_declare)
<< Context.BuiltinInfo.getHeaderName(ID)
<< Context.BuiltinInfo.getName(ID);
if (R.isNull())
return nullptr;
DeclContext *Parent = Context.getTranslationUnitDecl();
if (getLangOpts().CPlusPlus) {
LinkageSpecDecl *CLinkageDecl =
LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
LinkageSpecDecl::lang_c, false);
Parent = CLinkageDecl;
FunctionDecl *New = FunctionDecl::Create(Context,
Loc, Loc, II, R, /*TInfo=*/nullptr,
// Create Decl objects for each parameter, adding them to the
// FunctionDecl.
if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
SmallVector<ParmVarDecl*, 16> Params;
for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
ParmVarDecl *parm =
ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
SC_None, nullptr);
parm->setScopeInfo(0, i);
RegisterLocallyScopedExternCDecl(New, S);
// TUScope is the translation-unit scope to insert this function into.
// 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 = Parent;
PushOnScopeChains(New, TUScope);
CurContext = SavedContext;
return New;
/// Typedef declarations don't have linkage, but they still denote the same
/// entity if their types are the same.
/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
/// isSameEntity.
static void filterNonConflictingPreviousTypedefDecls(Sema &S,
TypedefNameDecl *Decl,
LookupResult &Previous) {
// This is only interesting when modules are enabled.
if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
// Empty sets are uninteresting.
if (Previous.empty())
LookupResult::Filter Filter = Previous.makeFilter();
while (Filter.hasNext()) {
NamedDecl *Old =;
// Non-hidden declarations are never ignored.
if (S.isVisible(Old))
// Declarations of the same entity are not ignored, even if they have
// different linkages.
if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
if (S.Context.hasSameType(OldTD->getUnderlyingType(),
// If both declarations give a tag declaration a typedef name for linkage
// purposes, then they declare the same entity.
if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
QualType OldType;
if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
OldType = OldTypedef->getUnderlyingType();
OldType = Context.getTypeDeclType(Old);
QualType NewType = New->getUnderlyingType();
if (NewType->isVariablyModifiedType()) {
// Must not redefine a typedef with a variably-modified type.
int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
<< Kind << NewType;
if (Old->getLocation().isValid())
notePreviousDefinition(Old, New->getLocation());
return true;
if (OldType != NewType &&
!OldType->isDependentType() &&
!NewType->isDependentType() &&
!Context.hasSameType(OldType, NewType)) {
int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
Diag(New->getLocation(), diag::err_redefinition_different_typedef)
<< Kind << NewType << OldType;
if (Old->getLocation().isValid())
notePreviousDefinition(Old, New->getLocation());
return true;
return false;
/// MergeTypedefNameDecl - 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. If there was an error, set New to be invalid.
void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
LookupResult &OldDecls) {
// If the new decl is known invalid already, don't bother doing any
// merging checks.
if (New->isInvalidDecl()) return;
// Allow multiple definitions for ObjC built-in typedefs.
// FIXME: Verify the underlying types are equivalent!
if (getLangOpts().ObjC1) {
const IdentifierInfo *TypeID = New->getIdentifier();
switch (TypeID->getLength()) {
default: break;
case 2:
if (!TypeID->isStr("id"))
QualType T = New->getUnderlyingType();
if (!T->isPointerType())
if (!T->isVoidPointerType()) {
QualType PT = T->getAs<PointerType>()->getPointeeType();
if (!PT->isStructureType())
// Install the built-in type for 'id', ignoring the current definition.
case 5:
if (!TypeID->isStr("Class"))
// Install the built-in type for 'Class', ignoring the current definition.
case 3:
if (!TypeID->isStr("SEL"))
// Install the built-in type for 'SEL', ignoring the current definition.
// Fall through - the typedef name was not a builtin type.
// Verify the old decl was also a type.
TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
if (!Old) {
Diag(New->getLocation(), diag::err_redefinition_different_kind)
<< New->getDeclName();
NamedDecl *OldD = OldDecls.getRepresentativeDecl();
if (OldD->getLocation().isValid())
notePreviousDefinition(OldD, New->getLocation());
return New->setInvalidDecl();
// If the old declaration is invalid, just give up here.
if (Old->isInvalidDecl())
return New->setInvalidDecl();
if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
auto *NewTag = New->getAnonDeclWithTypedefName();
NamedDecl *Hidden = nullptr;
if (OldTag && NewTag &&
OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
!hasVisibleDefinition(OldTag, &Hidden)) {
// There is a definition of this tag, but it is not visible. Use it
// instead of our tag.
if (OldTD->isModed())
// Make the old tag definition visible.
// If this was an unscoped enumeration, yank all of its enumerators
// out of the scope.
if (isa<EnumDecl>(NewTag)) {
Scope *EnumScope = getNonFieldDeclScope(S);
for (auto *D : NewTag->decls()) {
auto *ED = cast<EnumConstantDecl>(D);
// If the typedef types are not identical, reject them in all languages and
// with any extensions enabled.
if (isIncompatibleTypedef(Old, New))
// The types match. Link up the redeclaration chain and merge attributes if
// the old declaration was a typedef.
if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
mergeDeclAttributes(New, Old);
if (getLangOpts().MicrosoftExt)
if (getLangOpts().CPlusPlus) {
// 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 (!isa<CXXRecordDecl>(CurContext))
// C++0x [dcl.typedef]p4:
// In a given class scope, a typedef specifier can be used to redefine
// any class-name declared in that scope that is not also a typedef-name
// to refer to the type to which it already refers.
// This wording came in via DR424, which was a correction to the
// wording in DR56, which accidentally banned code like:
// struct S {
// typedef struct A { } A;
// };
// in the C++03 standard. We implement the C++0x semantics, which
// allow the above but disallow
// struct S {
// typedef int I;
// typedef int I;
// };
// since that was the intent of DR56.
if (!isa<TypedefNameDecl>(Old))
Diag(New->getLocation(), diag::err_redefinition)
<< New->getDeclName();
notePreviousDefinition(Old, New->getLocation());
return New->setInvalidDecl();
// Modules always permit redefinition of typedefs, as does C11.
if (getLangOpts().Modules || getLangOpts().C11)
// If we have a redefinition of a typedef in C, emit a warning. This warning
// is normally mapped to an error, but can be controlled with
// -Wtypedef-redefinition. If either the original or the redefinition is
// in a system header, don't emit this for compatibility with GCC.
if (getDiagnostics().getSuppressSystemWarnings() &&
// Some standard types are defined implicitly in Clang (e.g. OpenCL).
(Old->isImplicit() ||
Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
<< New->getDeclName();
notePreviousDefinition(Old, New->getLocation());
/// DeclhasAttr - returns true if decl Declaration already has the target
/// attribute.
static bool DeclHasAttr(const Decl *D, const Attr *A) {
const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
for (const auto *i : D->attrs())
if (i->getKind() == A->getKind()) {
if (Ann) {
if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
return true;
// FIXME: Don't hardcode this check
if (OA && isa<OwnershipAttr>(i))
return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
return true;
return false;
static bool isAttributeTargetADefinition(Decl *D) {
if (VarDecl *VD = dyn_cast<VarDecl>(D))
return VD->isThisDeclarationADefinition();
if (TagDecl *TD = dyn_cast<TagDecl>(D))
return TD->isCompleteDefinition() || TD->isBeingDefined();
return true;
/// Merge alignment attributes from \p Old to \p New, taking into account the
/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
/// \return \c true if any attributes were added to \p New.
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
// Look for alignas attributes on Old, and pick out whichever attribute
// specifies the strictest alignment requirement.
AlignedAttr *OldAlignasAttr = nullptr;
AlignedAttr *OldStrictestAlignAttr = nullptr;
unsigned OldAlign = 0;
for (auto *I : Old->specific_attrs<AlignedAttr>()) {
// FIXME: We have no way of representing inherited dependent alignments
// in a case like:
// template<int A, int B> struct alignas(A) X;
// template<int A, int B> struct alignas(B) X {};
// For now, we just ignore any alignas attributes which are not on the
// definition in such a case.
if (I->isAlignmentDependent())
return false;
if (I->isAlignas())
OldAlignasAttr = I;
unsigned Align = I->getAlignment(S.Context);
if (Align > OldAlign) {
OldAlign = Align;
OldStrictestAlignAttr = I;
// Look for alignas attributes on New.
AlignedAttr *NewAlignasAttr = nullptr;
unsigned NewAlign = 0;
for (auto *I : New->specific_attrs<AlignedAttr>()) {
if (I->isAlignmentDependent())
return false;
if (I->isAlignas())
NewAlignasAttr = I;
unsigned Align = I->getAlignment(S.Context);
if (Align > NewAlign)
NewAlign = Align;
if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
// Both declarations have 'alignas' attributes. We require them to match.
// C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
// fall short. (If two declarations both have alignas, they must both match
// every definition, and so must match each other if there is a definition.)
// If either declaration only contains 'alignas(0)' specifiers, then it
// specifies the natural alignment for the type.
if (OldAlign == 0 || NewAlign == 0) {
QualType Ty;
if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
Ty = VD->getType();
Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
if (OldAlign == 0)
OldAlign = S.Context.getTypeAlign(Ty);
if (NewAlign == 0)
NewAlign = S.Context.getTypeAlign(Ty);
if (OldAlign != NewAlign) {
S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
<< (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
<< (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
// C++11 [dcl.align]p6:
// if any declaration of an entity has an alignment-specifier,
// every defining declaration of that entity shall specify an
// equivalent alignment.
// C11 6.7.5/7:
// If the definition of an object does not have an alignment
// specifier, any other declaration of that object shall also
// have no alignment specifier.
S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
<< OldAlignasAttr;
S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
<< OldAlignasAttr;
bool AnyAdded = false;
// Ensure we have an attribute representing the strictest alignment.
if (OldAlign > NewAlign) {
AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
AnyAdded = true;
// Ensure we have an alignas attribute if the old declaration had one.
if (OldAlignasAttr && !NewAlignasAttr &&
!(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
AnyAdded = true;
return AnyAdded;
static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
const InheritableAttr *Attr,
Sema::AvailabilityMergeKind AMK) {
// This function copies an attribute Attr from a previous declaration to the
// new declaration D if the new declaration doesn't itself have that attribute
// yet or if that attribute allows duplicates.
// If you're adding a new attribute that requires logic different from
// "use explicit attribute on decl if present, else use attribute from
// previous decl", for example if the attribute needs to be consistent
// between redeclarations, you need to call a custom merge function here.
InheritableAttr *NewAttr = nullptr;
unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
AA->isImplicit(), AA->getIntroduced(),
AA->getObsoleted(), AA->getUnavailable(),
AA->getMessage(), AA->getStrict(),
AA->getReplacement(), AMK,
else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
FA->getFormatIdx(), FA->getFirstArg(),
else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
(isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
isa<CUDAGlobalAttr>(Attr))) {
// CUDA target attributes are part of function signature for
// overloading purposes and must not be merged.
return false;
} else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
NewAttr = S.mergeInternalLinkageAttr(
D, InternalLinkageA->getRange(),
else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
else if (isa<AlignedAttr>(Attr))
// AlignedAttrs are handled separately, because we need to handle all
// such attributes on a declaration at the same time.
NewAttr = nullptr;
else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
(AMK == Sema::AMK_Override ||
AMK == Sema::AMK_ProtocolImplementation))
NewAttr = nullptr;
else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
if (NewAttr) {
if (isa<MSInheritanceAttr>(NewAttr))
return true;
return false;
static const NamedDecl *getDefinition(const Decl *D) {
if (const TagDecl *TD = dyn_cast<TagDecl>(D))
return TD->getDefinition();
if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
const VarDecl *Def = VD->getDefinition();
if (Def)
return Def;
return VD->getActingDefinition();
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
return FD->getDefinition();
return nullptr;
static bool hasAttribute(const Decl *D, attr::Kind Kind) {
for (const auto *Attribute : D->attrs())
if (Attribute->getKind() == Kind)
return true;
return false;
/// checkNewAttributesAfterDef - If we already have a definition, check that
/// there are no new attributes in this declaration.
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
if (!New->hasAttrs())
const NamedDecl *Def = getDefinition(Old);
if (!Def || Def == New)
AttrVec &NewAttributes = New->getAttrs();
for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
const Attr *NewAttribute = NewAttributes[I];
if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
Sema::SkipBodyInfo SkipBody;
S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
// If we're skipping this definition, drop the "alias" attribute.
if (SkipBody.ShouldSkip) {
NewAttributes.erase(NewAttributes.begin() + I);
} else {
VarDecl *VD = cast<VarDecl>(New);
unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
? diag::err_alias_after_tentative
: diag::err_redefinition;
S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
if (Diag == diag::err_redefinition)
S.notePreviousDefinition(Def, VD->getLocation());
S.Diag(Def->getLocation(), diag::note_previous_definition);
if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
// Tentative definitions are only interesting for the alias check above.
if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
if (hasAttribute(Def, NewAttribute->getKind())) {
continue; // regular attr merging will take care of validating this.
if (isa<C11NoReturnAttr>(NewAttribute)) {
// C's _Noreturn is allowed to be added to a function after it is defined.
} else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
if (AA->isAlignas()) {
// C++11 [dcl.align]p6:
// if any declaration of an entity has an alignment-specifier,
// every defining declaration of that entity shall specify an
// equivalent alignment.
// C11 6.7.5/7:
// If the definition of an object does not have an alignment
// specifier, any other declaration of that object shall also
// have no alignment specifier.
S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
<< AA;
S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
<< AA;
NewAttributes.erase(NewAttributes.begin() + I);
S.Diag(Def->getLocation(), diag::note_previous_definition);
NewAttributes.erase(NewAttributes.begin() + I);
/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
AvailabilityMergeKind AMK) {
if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
UsedAttr *NewAttr = OldAttr->clone(Context);
if (!Old->hasAttrs() && !New->hasAttrs())
// Attributes declared post-definition are currently ignored.
checkNewAttributesAfterDef(*this, New, Old);
if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
if (OldA->getLabel() != NewA->getLabel()) {
// This redeclaration changes __asm__ label.
Diag(New->getLocation(), diag::err_different_asm_label);
Diag(OldA->getLocation(), diag::note_previous_declaration);
} else if (Old->isUsed()) {
// This redeclaration adds an __asm__ label to a declaration that has
// already been ODR-used.
Diag(New->getLocation(), diag::err_late_asm_label_name)
<< isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
// Re-declaration cannot add abi_tag's.
if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
for (const auto &NewTag : NewAbiTagAttr->tags()) {
if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
NewTag) == OldAbiTagAttr->tags_end()) {
<< NewTag;
Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
} else {
Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
Diag(Old->getLocation(), diag::note_previous_declaration);
if (!Old->hasAttrs())
bool foundAny = New->hasAttrs();
// Ensure that any moving of objects within the allocated map is done before
// we process them.
if (!foundAny) New->setAttrs(AttrVec());
for (auto *I : Old->specific_attrs<InheritableAttr>()) {
// Ignore deprecated/unavailable/availability attributes if requested.
AvailabilityMergeKind LocalAMK = AMK_None;
if (isa<DeprecatedAttr>(I) ||
isa<UnavailableAttr>(I) ||
isa<AvailabilityAttr>(I)) {
switch (AMK) {
case AMK_None:
case AMK_Redeclaration:
case AMK_Override:
case AMK_ProtocolImplementation:
LocalAMK = AMK;
// Already handled.
if (isa<UsedAttr>(I))
if (mergeDeclAttribute(*this, New, I, LocalAMK))
foundAny = true;
if (mergeAlignedAttrs(*this, New, Old))
foundAny = true;
if (!foundAny) New->dropAttrs();
/// mergeParamDeclAttributes - Copy attributes from the old parameter
/// to the new one.
static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
const ParmVarDecl *oldDecl,
Sema &S) {
// C++11 [dcl.attr.depend]p2:
// The first declaration of a function shall specify the
// carries_dependency attribute for its declarator-id if any declaration
// of the function specifies the carries_dependency attribute.
const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
// Find the first declaration of the parameter.
// FIXME: Should we build redeclaration chains for function parameters?
const FunctionDecl *FirstFD =
const ParmVarDecl *FirstVD =
diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
if (!oldDecl->hasAttrs())
bool foundAny = newDecl->hasAttrs();
// Ensure that any moving of objects within the allocated map is
// done before we process them.
if (!foundAny) newDecl->setAttrs(AttrVec());
for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
if (!DeclHasAttr(newDecl, I)) {
InheritableAttr *newAttr =
foundAny = true;
if (!foundAny) newDecl->dropAttrs();
static void mergeParamDeclTypes(ParmVarDecl *NewParam,
const ParmVarDecl *OldParam,
Sema &S) {
if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
if (*Oldnullability != *Newnullability) {
S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
<< DiagNullabilityKind(
((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
!= 0))
<< DiagNullabilityKind(
((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
!= 0));
S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
} else {
QualType NewT = NewParam->getType();
NewT = S.Context.getAttributedType(
NewT, NewT);
namespace {
/// Used in MergeFunctionDecl to keep track of function parameters in
/// C.
struct GNUCompatibleParamWarning {
ParmVarDecl *OldParm;
ParmVarDecl *NewParm;
QualType PromotedType;
} // end anonymous namespace
/// getSpecialMember - get the special member enum for a method.
Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
if (Ctor->isDefaultConstructor())
return Sema::CXXDefaultConstructor;
if (Ctor->isCopyConstructor())
return Sema::CXXCopyConstructor;
if (Ctor->isMoveConstructor())
return Sema::CXXMoveConstructor;
} else if (isa<CXXDestructorDecl>(MD)) {
return Sema::CXXDestructor;
} else if (MD->isCopyAssignmentOperator()) {
return Sema::CXXCopyAssignment;
} else if (MD->isMoveAssignmentOperator()) {
return Sema::CXXMoveAssignment;
return Sema::CXXInvalid;
// Determine whether the previous declaration was a definition, implicit
// declaration, or a declaration.
template <typename T>
static std::pair<diag::kind, SourceLocation>
getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
diag::kind PrevDiag;
SourceLocation OldLocation = Old->getLocation();
if (Old->isThisDeclarationADefinition())
PrevDiag = diag::note_previous_definition;
else if (Old->isImplicit()) {
PrevDiag = diag::note_previous_implicit_declaration;
if (OldLocation.isInvalid())
OldLocation = New->getLocation();
} else
PrevDiag = diag::note_previous_declaration;
return std::make_pair(PrevDiag, OldLocation);
/// canRedefineFunction - checks if a function can be redefined. Currently,
/// only extern inline functions can be redefined, and even then only in
/// GNU89 mode.
static bool canRedefineFunction(const FunctionDecl *FD,
const LangOptions& LangOpts) {
return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
!LangOpts.CPlusPlus &&
FD->isInlineSpecified() &&
FD->getStorageClass() == SC_Extern);
const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
const AttributedType *AT = T->getAs<AttributedType>();
while (AT && !AT->isCallingConv())
AT = AT->getModifiedType()->getAs<AttributedType>();
return AT;
template <typename T>
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
const DeclContext *DC = Old->getDeclContext();
if (DC->isRecord())
return false;
LanguageLinkage OldLinkage = Old->getLanguageLinkage();
if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
return true;
if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
return true;
return false;
template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
static bool isExternC(VarTemplateDecl *) { return false; }
/// \brief Check whether a redeclaration of an entity introduced by a
/// using-declaration is valid, given that we know it's not an overload
/// (nor a hidden tag declaration).
template<typename ExpectedDecl>
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
ExpectedDecl *New) {
// C++11 [basic.scope.declarative]p4:
// Given a set of declarations in a single declarative region, each of
// which specifies the same unqualified name,
// -- they shall all refer to the same entity, or all refer to functions
// and function templates; or
// -- 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 variable or enumerator, or all refer to functions
// and function templates; in this case the class name or enumeration
// name is hidden (3.3.10).
// C++11 [namespace.udecl]p14:
// If a function declaration in namespace scope or block scope has the
// same name and the same parameter-type-list as a function introduced
// by a using-declaration, and the declarations do not declare the same
// function, the program is ill-formed.
auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
if (Old &&
New->getDeclContext()->getRedeclContext()) &&
!(isExternC(Old) && isExternC(New)))
Old = nullptr;
if (!Old) {
S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
return true;
return false;
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
const FunctionDecl *B) {
assert(A->getNumParams() == B->getNumParams());
auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
if (AttrA == AttrB)
return true;
return AttrA && AttrB && AttrA->getType() == AttrB->getType();
return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
/// 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, NamedDecl *&OldD,
Scope *S, bool MergeTypeWithOld) {
// Verify the old decl was also a function.
FunctionDecl *Old = OldD->getAsFunction();
if (!Old) {
if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
if (New->getFriendObjectKind()) {
Diag(New->getLocation(), diag::err_using_decl_friend);
diag::note_using_decl) << 0;
return true;
// Check whether the two declarations might declare the same function.
if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
return true;
OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
} else {
Diag(New->getLocation(), diag::err_redefinition_different_kind)
<< New->getDeclName();
notePreviousDefinition(OldD, New->getLocation());
return true;
// If the old declaration is invalid, just give up here.
if (Old->isInvalidDecl())
return true;
diag::kind PrevDiag;
SourceLocation OldLocation;
std::tie(PrevDiag, OldLocation) =
getNoteDiagForInvalidRedeclaration(Old, New);
// Don't complain about this if we're in GNU89 mode and the old function
// is an extern inline function.
// Don't complain about specializations. They are not supposed to have
// storage classes.
if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
New->getStorageClass() == SC_Static &&
Old->hasExternalFormalLinkage() &&
!New->getTemplateSpecializationInfo() &&
!canRedefineFunction(Old, getLangOpts())) {
if (getLangOpts().MicrosoftExt) {
Diag(New->getLocation(), diag::ext_static_non_static) << New;
Diag(OldLocation, PrevDiag);
} else {
Diag(New->getLocation(), diag::err_static_non_static) << New;
Diag(OldLocation, PrevDiag);
return true;
if (New->hasAttr<InternalLinkageAttr>() &&
!Old->hasAttr<InternalLinkageAttr>()) {
Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
<< New->getDeclName();
notePreviousDefinition(Old, New->getLocation());
if (!getLangOpts().CPlusPlus) {
bool OldOvl = Old->hasAttr<OverloadableAttr>();
if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
<< New << OldOvl;
// Try our best to find a decl that actually has the overloadable
// attribute for the note. In most cases (e.g. programs with only one
// broken declaration/definition), this won't matter.
// FIXME: We could do this if we juggled some extra state in
// OverloadableAttr, rather than just removing it.
const Decl *DiagOld = Old;
if (OldOvl) {
auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
const auto *A = D->getAttr<OverloadableAttr>();
return A && !A->isImplicit();
// If we've implicitly added *all* of the overloadable attrs to this
// chain, emitting a "previous redecl" note is pointless.
DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
if (DiagOld)
<< OldOvl;
if (OldOvl)
// If a function is first declared with a calling convention, but is later
// declared or defined without one, all following decls assume the calling
// convention of the first.
// It's OK if a function is first declared without a calling convention,
// but is later declared or defined with the default calling convention.
// To test if either decl has an explicit calling convention, we look for
// AttributedType sugar nodes on the type as written. If they are missing or
// were canonicalized away, we assume the calling convention was implicit.
// Note also that we DO NOT return at this point, because we still have
// other tests to run.
QualType OldQType = Context.getCanonicalType(Old->getType());
QualType NewQType = Context.getCanonicalType(New->getType());
const FunctionType *OldType = cast<FunctionType>(OldQType);
const FunctionType *NewType = cast<FunctionType>(NewQType);
FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
bool RequiresAdjustment = false;
if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
FunctionDecl *First = Old->getFirstDecl();
const FunctionType *FT =
FunctionType::ExtInfo FI = FT->getExtInfo();
bool NewCCExplicit = getCallingConvAttributedType(New->getType());
if (!NewCCExplicit) {
// Inherit the CC from the previous declaration if it was specified
// there but not here.
NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
RequiresAdjustment = true;
} else {
// Calling conventions aren't compatible, so complain.
bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
Diag(New->getLocation(), diag::err_cconv_change)
<< FunctionType::getNameForCallConv(NewTypeInfo.getCC())
<< !FirstCCExplicit
<< (!FirstCCExplicit ? "" :
// Put the note on the first decl, since it is the one that matters.
Diag(First->getLocation(), diag::note_previous_declaration);
return true;
// FIXME: diagnose the other way around?
if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
NewTypeInfo = NewTypeInfo.withNoReturn(true);
RequiresAdjustment = true;
// Merge regparm attribute.
if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
if (NewTypeInfo.getHasRegParm()) {
Diag(New->getLocation(), diag::err_regparm_mismatch)
<< NewType->getRegParmType()
<< OldType->getRegParmType();
Diag(OldLocation, diag::note_previous_declaration);
return true;
NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
RequiresAdjustment = true;
// Merge ns_returns_retained attribute.
if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
if (NewTypeInfo.getProducesResult()) {
Diag(New->getLocation(), diag::err_function_attribute_mismatch)
<< "'ns_returns_retained'";
Diag(OldLocation, diag::note_previous_declaration);
return true;
NewTypeInfo = NewTypeInfo.withProducesResult(true);
RequiresAdjustment = true;
if (OldTypeInfo.getNoCallerSavedRegs() !=
NewTypeInfo.getNoCallerSavedRegs()) {
if (NewTypeInfo.getNoCallerSavedRegs()) {
AnyX86NoCallerSavedRegistersAttr *Attr =
Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
Diag(OldLocation, diag::note_previous_declaration);
return true;
NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
RequiresAdjustment = true;
if (RequiresAdjustment) {
const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
New->setType(QualType(AdjustedType, 0));
NewQType = Context.getCanonicalType(New->getType());
NewType = cast<FunctionType>(NewQType);
// If this redeclaration makes the function inline, we may need to add it to
// UndefinedButUsed.
if (!Old->isInlined() && New->isInlined() &&
!New->hasAttr<GNUInlineAttr>() &&
!getLangOpts().GNUInline &&
Old->isUsed(false) &&
!Old->isDefined() && !New->isThisDeclarationADefinition())
// If this redeclaration makes it newly gnu_inline, we don't want to warn
// about it.
if (New->hasAttr<GNUInlineAttr>() &&
Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
// If pass_object_size params don't match up perfectly, this isn't a valid
// redeclaration.
if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
!hasIdenticalPassObjectSizeAttrs(Old, New)) {
Diag(New->getLocation(), diag::err_different_pass_object_size_params)
<< New->getDeclName();
Diag(OldLocation, PrevDiag) << Old << Old->getType();
return true;
if (getLangOpts().CPlusPlus) {
// C++1z [over.load]p2
// Certain function declarations cannot be overloaded:
// -- Function declarations that differ only in the return type,
// the exception specification, or both cannot be overloaded.
// Check the exception specifications match. This may recompute the type of
// both Old and New if it resolved exception specifications, so grab the
// types again after this. Because this updates the type, we do this before
// any of the other checks below, which may update the "de facto" NewQType
// but do not necessarily update the type of New.
if (CheckEquivalentExceptionSpec(Old, New))
return true;
OldQType = Context.getCanonicalType(Old->getType());
NewQType = Context.getCanonicalType(New->getType());
// Go back to the type source info to compare the declared return types,
// per C++1y []p13:
// Redeclarations or specializations of a function or function template
// with a declared return type that uses a placeholder type shall also
// use that placeholder, not a deduced type.
QualType OldDeclaredReturnType =
? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
: OldType)->getReturnType();
QualType NewDeclaredReturnType =
? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
: NewType)->getReturnType();
if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
!((NewQType->isDependentType() || OldQType->isDependentType()) &&
New->isLocalExternDecl())) {
QualType ResQT;
if (NewDeclaredReturnType->isObjCObjectPointerType() &&
ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
if (ResQT.isNull()) {
if (New->isCXXClassMember() && New->isOutOfLine())
Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
<< New << New->getReturnTypeSourceRange();
Diag(New->getLocation(), diag::err_ovl_diff_return_type)
<< New->getReturnTypeSourceRange();
Diag(OldLocation, PrevDiag) << Old << Old->getType()
<< Old->getReturnTypeSourceRange();
return true;
NewQType = ResQT;
QualType OldReturnType = OldType->getReturnType();
QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
if (OldReturnType != NewReturnType) {
// If this function has a deduced return type and has already been
// defined, copy the deduced value from the old declaration.
AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
if (OldAT && OldAT->isDeduced()) {
OldAT->isDependentType() ? Context.DependentTy
: OldAT->getDeducedType()));
NewQType = Context.getCanonicalType(
OldAT->isDependentType() ? Context.DependentTy
: OldAT->getDeducedType()));
const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
if (OldMethod && NewMethod) {
// Preserve triviality.
// MSVC allows explicit template specialization at class scope:
// 2 CXXMethodDecls referring to the same function will be injected.
// We don't want a redeclaration error.
bool IsClassScopeExplicitSpecialization =
OldMethod->isFunctionTemplateSpecialization() &&
bool isFriend = NewMethod->getFriendObjectKind();
if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
!IsClassScopeExplicitSpecialization) {
// -- 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(OldLocation, PrevDiag) << Old << Old->getType();
return true;
// 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.
if (!inTemplateInstantiation()) {
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;
NewDiag = diag::err_member_redeclared;
Diag(New->getLocation(), NewDiag);
} else {
Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
<< New << New->getType();
Diag(OldLocation, PrevDiag) << Old << Old->getType();
return true;
// Complain if this is an explicit declaration of a special
// member that was initially declared implicitly.
// As an exception, it's okay to befriend such methods in order
// to permit the implicit constructor/destructor/operator calls.
} else if (OldMethod->isImplicit()) {
if (isFriend) {
} else {
<< New << getSpecialMember(OldMethod);
return true;
} else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
<< getSpecialMember(OldMethod);
return true;
// C++11 [dcl.attr.noreturn]p1:
// The first declaration of a function shall specify the noreturn
// attribute if any declaration of that function specifies the noreturn
// attribute.
const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
// C++11 [dcl.attr.depend]p2:
// The first declaration of a function shall specify the
// carries_dependency attribute for its declarator-id if any declaration
// of the function specifies the carries_dependency attribute.
const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
// (C++98 8.3.5p3):
// All declarations for a function shall agree exactly in both the
// return type and the parameter-type-list.
// We also want to respect all the extended bits except noreturn.
// noreturn should now match unless the old type info didn't have it.
QualType OldQTypeForComparison = OldQType;
if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
auto *OldType = OldQType->castAs<FunctionProtoType>();
const FunctionType *OldTypeForComparison
= Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
OldQTypeForComparison = QualType(OldTypeForComparison, 0);
if (haveIncompatibleLanguageLinkages(Old, New)) {
// As a special case, retain the language linkage from previous
// declarations of a friend function as an extension.
// This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
// and is useful because there's otherwise no way to specify language
// linkage within class scope.
// Check cautiously as the friend object kind isn't yet complete.
if (New->getFriendObjectKind() != Decl::FOK_None) {
Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
Diag(OldLocation, PrevDiag);
} else {
Diag(New->getLocation(), diag::err_different_language_linkage) << New;
Diag(OldLocation, PrevDiag);
return true;
if (OldQTypeForComparison == NewQType)
return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
New->isLocalExternDecl()) {
// It's OK if we couldn't merge types for a local function declaraton
// if either the old or new type is dependent. We'll merge the types
// when we instantiate the function.
return false;
// 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 (!getLangOpts().CPlusPlus &&
Context.typesAreCompatible(OldQType, NewQType)) {
const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
const FunctionProtoType *OldProto = nullptr;
if (MergeTypeWithOld && 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.
assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
NewQType =
Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
// Synthesize parameters with the same types.
SmallVector<ParmVarDecl*, 16> Params;
for (const auto &ParamType : OldProto->param_types()) {
ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
SourceLocation(), nullptr,
ParamType, /*TInfo=*/nullptr,
SC_None, nullptr);
Param->setScopeInfo(0, Params.size());
return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
// 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 a variadic prototype is followed by a non-variadic K&R definition,
// the K&R definition becomes variadic. This is sort of an edge case, but
// it's legal per the standard depending on how you read C99 and
// C99 6.9.1p8.
if (!getLangOpts().CPlusPlus &&
Old->hasPrototype() && !New->hasPrototype() &&
New->getType()->getAs<FunctionProtoType>() &&
Old->getNumParams() == New->getNumParams()) {
SmallVector<QualType, 16> ArgTypes;
SmallVector<GNUCompatibleParamWarning, 16> Warnings;
const FunctionProtoType *OldProto
= Old->getType()->getAs<FunctionProtoType>();
const FunctionProtoType *NewProto
= New->getType()->getAs<FunctionProtoType>();
// Determine whether this is the GNU C extension.
QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
bool LooseCompatible = !MergedReturn.isNull();
for (unsigned Idx = 0, End = Old->getNumParams();
LooseCompatible && Idx != End; ++Idx) {
ParmVarDecl *OldParm = Old->getParamDecl(Idx);
ParmVarDecl *NewParm = New->getParamDecl(Idx);
if (Context.typesAreCompatible(OldParm->getType(),
NewProto->getParamType(Idx))) {
} else if (Context.typesAreCompatible(OldParm->getType(),
/*CompareUnqualified=*/true)) {
GNUCompatibleParamWarning Warn = { OldParm, NewParm,
NewProto->getParamType(Idx) };
} else
LooseCompatible = false;
if (LooseCompatible) {
for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
<< Warnings[Warn].PromotedType
<< Warnings[Warn].OldParm->getType();
if (Warnings[Warn].OldParm->getLocation().isValid())
if (MergeTypeWithOld)
New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
// Fall through to diagnose conflicting types.
// A function that has already been declared has been redeclared or
// defined with a different type; show an appropriate diagnostic.
// If the previous declaration was an implicitly-generated builtin
// declaration, then at the very least we should use a specialized note.
unsigned BuiltinID;
if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
// If it's actually a library-defined builtin function like 'malloc'
// or 'printf', just warn about the incompatible redeclaration.
if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
Diag(OldLocation, diag::note_previous_builtin_declaration)
<< Old << Old->getType();
// If this is a global redeclaration, just forget hereafter
// about the "builtin-ness" of the function.
// Doing this for local extern declarations is problematic. If
// the builtin declaration remains visible, a second invalid
// local declaration will produce a hard error; if it doesn't
// remain visible, a single bogus local redeclaration (which is
// actually only a warning) could break all the downstream code.
if (!New->getLexicalDeclContext()->isFunctionOrMethod())
return false;
PrevDiag = diag::note_previous_builtin_declaration;
Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Diag(OldLocation, PrevDiag) << Old << Old->getType();
return true;
/// \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 from 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,
Scope *S, bool MergeTypeWithOld) {
// Merge the attributes
mergeDeclAttributes(New, Old);
// Merge "pure" flag.
if (Old->isPure())
// Merge "used" flag.
if (Old->getMostRecentDecl()->isUsed(false))
// Merge attributes from the parameters. These can mismatch with K&R
// declarations.
if (New->getNumParams() == Old->getNumParams())
for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
ParmVarDecl *NewParam = New->getParamDecl(i);
ParmVarDecl *OldParam = Old->getParamDecl(i);
mergeParamDeclAttributes(NewParam, OldParam, *this);
mergeParamDeclTypes(NewParam, OldParam, *this);
if (getLangOpts().CPlusPlus)
return MergeCXXFunctionDecl(New, Old, S);
// Merge the function types so the we get the composite types for the return
// and argument types. Per C11 6.2.7/4, only update the type if the old decl
// was visible.
QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
if (!Merged.isNull() && MergeTypeWithOld)
return false;
void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
ObjCMethodDecl *oldMethod) {
// Merge the attributes, including deprecated/unavailable
AvailabilityMergeKind MergeKind =
? AMK_ProtocolImplementation
: isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
: AMK_Override;
mergeDeclAttributes(newMethod, oldMethod, MergeKind);
// Merge attributes from the parameters.
ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
oe = oldMethod->param_end();
for (ObjCMethodDecl::param_iterator
ni = newMethod->param_begin(), ne = newMethod->param_end();
ni != ne && oi != oe; ++ni, ++oi)
mergeParamDeclAttributes(*ni, *oi, *this);
CheckObjCMethodOverride(newMethod, oldMethod);
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
assert(!S.Context.hasSameType(New->getType(), Old->getType()));
S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
? diag::err_redefinition_different_type
: diag::err_redeclaration_different_type)
<< New->getDeclName() << New->getType() << Old->getType();
diag::kind PrevDiag;
SourceLocation OldLocation;
std::tie(PrevDiag, OldLocation)
= getNoteDiagForInvalidRedeclaration(Old, New);
S.Diag(OldLocation, PrevDiag);
/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
/// scope as a previous declaration 'Old'. Figure out how to merge their types,
/// emitting diagnostics as appropriate.
/// Declarations using the auto type specifier (C++ []) call back
/// to here in AddInitializerToDecl. We can't check them before the initializer
/// is attached.
void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
bool MergeTypeWithOld) {
if (New->isInvalidDecl() || Old->isInvalidDecl())
QualType MergedT;
if (getLangOpts().CPlusPlus) {
if (New->getType()->isUndeducedType()) {
// We don't know what the new type is until the initializer is attached.
} else if (Context.hasSameType(New->getType(), Old->getType())) {
// These could still be something that needs exception specs checked.
return MergeVarDeclExceptionSpecs(New, Old);
// C++ []p10:
// [...] the types specified by all declarations referring to a given
// object or function shall be identical, except that declarations for an
// array object can specify array types that differ by the presence or
// absence of a major array bound (8.3.4).
else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
const ArrayType *NewArray = Context.getAsArrayType(New->getType());
// We are merging a variable declaration New into Old. If it has an array
// bound, and that bound differs from Old's bound, we should diagnose the
// mismatch.
if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
PrevVD = PrevVD->getPreviousDecl()) {
const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
if (!Context.hasSameType(NewArray, PrevVDTy))
return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
if (Context.hasSameType(OldArray->getElementType(),
MergedT = New->getType();
// FIXME: Check visibility. New is hidden but has a complete type. If New
// has no array bound, it should not inherit one from Old, if Old is not
// visible.
else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
if (Context.hasSameType(OldArray->getElementType(),
MergedT = Old->getType();
else if (New->getType()->isObjCObjectPointerType() &&
Old->getType()->isObjCObjectPointerType()) {
MergedT = Context.mergeObjCGCQualifiers(New->getType(),
} else {
// C 6.2.7p2:
// All declarations that refer to the same object or function shall have
// compatible type.
MergedT = Context.mergeTypes(New->getType(), Old->getType());
if (MergedT.isNull()) {
// It's OK if we couldn't merge types if either type is dependent, for a
// block-scope variable. In other cases (static data members of class
// templates, variable templates, ...), we require the types to be
// equivalent.
// FIXME: The C++ standard doesn't say anything about this.
if ((New->getType()->isDependentType() ||
Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
// If the old type was dependent, we can't merge with it, so the new type
// becomes dependent for now. We'll reproduce the original type when we
// instantiate the TypeSourceInfo for the variable.
if (!New->getType()->isDependentType() && MergeTypeWithOld)
return diagnoseVarDeclTypeMismatch(*this, New, Old);
// Don't actually update the type on the new declaration if the old
// declaration was an extern declaration in a different scope.
if (MergeTypeWithOld)
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
LookupResult &Previous) {
// C11 6.2.7p4:
// For an identifier with internal or external linkage declared
// in a scope in which a prior declaration of that identifier is
// visible, if the prior declaration specifies internal or
// external linkage, the type of the identifier at the later
// declaration becomes the composite type.
// If the variable isn't visible, we do not merge with its type.
if (Previous.isShadowed())
return false;
if (S.getLangOpts().CPlusPlus) {
// C++11 [dcl.array]p3:
// If there is a preceding declaration of the entity in the same
// scope in which the bound was specified, an omitted array bound
// is taken to be the same as in that earlier declaration.
return NewVD->isPreviousDeclInSameBlockScope() ||
(!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
} else {
// If the old declaration was function-local, don't merge with its
// type unless we're in the same function.
return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
/// 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.
void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
// If the new decl is already invalid, don't do any other checking.
if (New->isInvalidDecl())
if (!shouldLinkPossiblyHiddenDecl(Previous, New))
VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
// Verify the old decl was also a variable or variable template.
VarDecl *Old = nullptr;
VarTemplateDecl *OldTemplate = nullptr;
if (Previous.isSingleResult()) {
if (NewTemplate) {
OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
if (auto *Shadow =
if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
return New->setInvalidDecl();
} else {
Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
if (auto *Shadow =
if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
return New->setInvalidDecl();
if (!Old) {
Diag(New->getLocation(), diag::err_redefinition_different_kind)
<< New->getDeclName();
return New->setInvalidDecl();
// Ensure the template parameters are compatible.
if (NewTemplate &&
/*Complain=*/true, TPL_TemplateMatch))
return New->setInvalidDecl();
// C++ [class.mem]p1:
// A member shall not be declared twice in the member-specification [...]
// Here, we need only consider static data members.
if (Old->isStaticDataMember() && !New->isOutOfLine()) {
Diag(New->getLocation(), diag::err_duplicate_member)
<< New->getIdentifier();
Diag(Old->getLocation(), diag::note_previous_declaration);
mergeDeclAttributes(New, Old);
// Warn if an already-declared variable is made a weak_import in a subsequent
// declaration
if (New->hasAttr<WeakImportAttr>() &&
Old->getStorageClass() == SC_None &&
!Old->hasAttr<WeakImportAttr>()) {
Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
notePreviousDefinition(Old, New->getLocation());
// Remove weak_import attribute on new declaration.
if (New->hasAttr<InternalLinkageAttr>() &&
!Old->hasAttr<InternalLinkageAttr>()) {
Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
<< New->getDeclName();
notePreviousDefinition(Old, New->getLocation());
// Merge the types.
VarDecl *MostRecent = Old->getMostRecentDecl();
if (MostRecent != Old) {
MergeVarDeclTypes(New, MostRecent,
mergeTypeWithPrevious(*this, New, MostRecent, Previous));
if (New->isInvalidDecl())
MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
if (New->isInvalidDecl())
diag::kind PrevDiag;
SourceLocation OldLocation;
std::tie(PrevDiag, OldLocation) =
getNoteDiagForInvalidRedeclaration(Old, New);
// []p8: Check if we have a non-static decl followed by a static.
if (New->getStorageClass() == SC_Static &&
!New->isStaticDataMember() &&
Old->hasExternalFormalLinkage()) {
if (getLangOpts().MicrosoftExt) {
Diag(New->getLocation(), diag::ext_static_non_static)
<< New->getDeclName();
Diag(OldLocation, PrevDiag);
} else {
Diag(New->getLocation(), diag::err_static_non_static)
<< New->getDeclName();
Diag(OldLocation, PrevDiag);
return New->setInvalidDecl();
// 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->getCanonicalDecl()->getStorageClass() != SC_Static &&
!New->isStaticDataMember() &&
Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Diag(OldLocation, PrevDiag);
return New->setInvalidDecl();
// Check if extern is followed by non-extern and vice-versa.
if (New->hasExternalStorage() &&
!Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
Diag(OldLocation, PrevDiag);
return New->setInvalidDecl();
if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
!New->hasExternalStorage()) {
Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
Diag(OldLocation, PrevDiag);
return New->setInvalidDecl();
// Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
// FIXME: The test for external storage here seems wrong? We still
// need to check for mismatches.
if (!New->hasExternalStorage() && !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(OldLocation, PrevDiag);
return New->setInvalidDecl();
if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
if (VarDecl *Def = Old->getDefinition()) {
// C++1z [dcl.fcn.spec]p4:
// If the definition of a variable appears in a translation unit before
// its first declaration as inline, the program is ill-formed.
Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
Diag(Def->getLocation(), diag::note_previous_definition);
// If this redeclaration makes the function inline, we may need to add it to
// UndefinedButUsed.
if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
!Old->getDefinition() && !New->isThisDeclarationADefinition())
if (New->getTLSKind() != Old->getTLSKind()) {
if (!Old->getTLSKind()) {
Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
Diag(OldLocation, PrevDiag);
} else if (!New->getTLSKind()) {
Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
Diag(OldLocation, PrevDiag);
} else {
// Do not allow redeclaration to change the variable between requiring
// static and dynamic initialization.
// FIXME: GCC allows this, but uses the TLS keyword on the first
// declaration to determine the kind. Do we need to be compatible here?
Diag(New->getLocation(), diag::err_thread_thread_different_kind)
<< New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
Diag(OldLocation, PrevDiag);
// C++ doesn't have tentative definitions, so go right ahead and check here.
if (getLangOpts().CPlusPlus &&
New->isThisDeclarationADefinition() == VarDecl::Definition) {
if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
Old->getCanonicalDecl()->isConstexpr()) {
// This definition won't be a definition any more once it's been merged.
} else if (VarDecl *Def = Old->getDefinition()) {
if (checkVarDeclRedefinition(Def, New))
if (haveIncompatibleLanguageLinkages(Old, New)) {
Diag(New->getLocation(), diag::err_different_language_linkage) << New;
Diag(OldLocation, PrevDiag);
// Merge "used" flag.
if (Old->getMostRecentDecl()->isUsed(false))
// Keep a chain of previous declarations.
if (NewTemplate)
// Inherit access appropriately.
if (NewTemplate)
if (Old->isInline())
void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
SourceManager &SrcMgr = getSourceManager();
auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
auto &HSI = PP.getHeaderSearchInfo();
StringRef HdrFilename =
auto noteFromModuleOrInclude = [&](Module *Mod,
SourceLocation IncLoc) -> bool {
// Redefinition errors with modules are common with non modular mapped
// headers, example: a non-modular header H in module A that also gets
// included directly in a TU. Pointing twice to the same header/definition
// is confusing, try to get better diagnostics when modules is on.
if (IncLoc.isValid()) {
if (Mod) {
Diag(IncLoc, diag::note_redefinition_modules_same_file)
<< HdrFilename.str() << Mod->getFullModuleName();
if (!Mod->DefinitionLoc.isInvalid())
Diag(Mod->DefinitionLoc, diag::note_defined_here)
<< Mod->getFullModuleName();
} else {
Diag(IncLoc, diag::note_redefinition_include_same_file)
<< HdrFilename.str();
return true;
return false;
// Is it the same file and same offset? Provide more information on why
// this leads to a redefinition error.
bool EmittedDiag = false;
if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
// If the header has no guards, emit a note suggesting one.
if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
Diag(Old->getLocation(), diag::note_use_ifdef_guards);
if (EmittedDiag)
// Redefinition coming from different files or couldn't do better above.
Diag(Old->getLocation(), diag::note_previous_definition);
/// We've just determined that \p Old and \p New both appear to be definitions
/// of the same variable. Either diagnose or fix the problem.
bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
if (!hasVisibleDefinition(Old) &&
(New->getFormalLinkage() == InternalLinkage ||
New->isInline() ||
New->getDescribedVarTemplate() ||
New->getNumTemplateParameterLists() ||
New->getDeclContext()->isDependentContext())) {
// The previous definition is hidden, and multiple definitions are
// permitted (in separate TUs). Demote this to a declaration.
// Make the canonical definition visible.
if (auto *OldTD = Old->getDescribedVarTemplate())
return false;
} else {
Diag(New->getLocation(), diag::err_redefinition) << New;
notePreviousDefinition(Old, New->getLocation());
return true;
/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
/// no declarator (e.g. "struct foo;") is parsed.
Decl *
Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
RecordDecl *&AnonRecord) {
return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
// disambiguate entities defined in different scopes.
// While the VS2015 ABI fixes potential miscompiles, it is also breaks
// compatibility.
// We will pick our mangling number depending on which version of MSVC is being
// targeted.
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
? S->getMSCurManglingNumber()
: S->getMSLastManglingNumber();
void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
if (!Context.getLangOpts().CPlusPlus)
if (isa<CXXRecordDecl>(Tag->getParent())) {
// If this tag is the direct child of a class, number it if
// it is anonymous.
if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
MangleNumberingContext &MCtx =
Tag, MCtx.getManglingNumber(
Tag, getMSManglingNumber(getLangOpts(), TagScope)));
// If this tag isn't a direct child of a class, number it if it is local.
Decl *ManglingContextDecl;
if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
Tag->getDeclContext(), ManglingContextDecl)) {
Tag, MCtx->getManglingNumber(
Tag, getMSManglingNumber(getLangOpts(), TagScope)));
void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
TypedefNameDecl *NewTD) {
if (TagFromDeclSpec->isInvalidDecl())
// Do nothing if the tag already has a name for linkage purposes.
if (TagFromDeclSpec->hasNameForLinkage())
// A well-formed anonymous tag must always be a TUK_Definition.
// The type must match the tag exactly; no qualifiers allowed.
if (!Context.hasSameType(NewTD->getUnderlyingType(),
Context.getTagDeclType(TagFromDeclSpec))) {
if (getLangOpts().CPlusPlus)
Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
// If we've already computed linkage for the anonymous tag, then
// adding a typedef name for the anonymous decl can change that
// linkage, which might be a serious problem. Diagnose this as
// unsupported and ignore the typedef name. TODO: we should
// pursue this as a language defect and establish a formal rule
// for how to handle it.
if (TagFromDeclSpec->hasLinkageBeenComputed()) {
Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
tagLoc = getLocForEndOfToken(tagLoc);
llvm::SmallString<40> textToInsert;
textToInsert += ' ';
textToInsert += NewTD->getIdentifier()->getName();
Diag(tagLoc, diag::note_typedef_changes_linkage)
<< FixItHint::CreateInsertion(tagLoc, textToInsert);
// Otherwise, set this is the anon-decl typedef for the tag.
static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
switch (T) {
case DeclSpec::TST_class:
return 0;
case DeclSpec::TST_struct:
return 1;
case DeclSpec::TST_interface:
return 2;
case DeclSpec::TST_union:
return 3;
case DeclSpec::TST_enum:
return 4;
llvm_unreachable("unexpected type specifier");
/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
/// parameters to cope with template friend declarations.
Decl *
Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
MultiTemplateParamsArg TemplateParams,
bool IsExplicitInstantiation,
RecordDecl *&AnonRecord) {
Decl *TagD = nullptr;
TagDecl *Tag = nullptr;
if (DS.getTypeSpecType() == DeclSpec::TST_class ||
DS.getTypeSpecType() == DeclSpec::TST_struct ||
DS.getTypeSpecType() == DeclSpec::TST_interface ||
DS.getTypeSpecType() == DeclSpec::TST_union ||
DS.getTypeSpecType() == DeclSpec::TST_enum) {
TagD = DS.getRepAsDecl();
if (!TagD) // We probably had an error
return nullptr;
// Note that the above type specs guarantee that the
// type rep is a Decl, whereas in many of the others
// it's a Type.
if (isa<TagDecl>(TagD))
Tag = cast<TagDecl>(TagD);
else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
Tag = CTD->getTemplatedDecl();
if (Tag) {
handleTagNumbering(Tag, S);
if (Tag->isInvalidDecl())
return Tag;
if (unsigned TypeQuals = DS.getTypeQualifiers()) {
// Enforce C99 6.7.3p2: "Types other than pointer types derived from object
// or incomplete types shall not be restrict-qualified."
if (TypeQuals & DeclSpec::TQ_restrict)
<< DS.getSourceRange();
if (DS.isInlineSpecified())
Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
<< getLangOpts().CPlusPlus1z;
if (DS.isConstexprSpecified()) {
// C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
// and definitions of functions and variables.
if (Tag)
Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
<< GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
// Don't emit warnings after this error.
return TagD;
if (DS.isConceptSpecified()) {
// C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
// either a function concept and its definition or a variable concept and
// its initializer.
Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
return TagD;
if (DS.isFriendSpecified()) {
// If we're dealing with a decl but not a TagDecl, assume that
// whatever routines created it handled the friendship aspect.
if (TagD && !Tag)
return nullptr;
return ActOnFriendTypeDecl(S, DS, TemplateParams);
const CXXScopeSpec &SS = DS.getTypeSpecScope();
bool IsExplicitSpecialization =
!TemplateParams.empty() && TemplateParams.back()->size() == 0;
if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
!IsExplicitInstantiation && !IsExplicitSpecialization &&
!isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
// Per C++ [dcl.type.elab]p1, a class declaration cannot have a
// nested-name-specifier unless it is an explicit instantiation
// or an explicit specialization.
// FIXME: We allow class template partial specializations here too, per the
// obvious intent of DR1819.
// Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
<< GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
return nullptr;
// Track whether this decl-specifier declares anything.
bool DeclaresAnything = true;
// Handle anonymous struct definitions.
if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
if (!Record->getDeclName() && Record->isCompleteDefinition() &&
DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
if (getLangOpts().CPlusPlus ||
Record->getDeclContext()->isRecord()) {
// If CurContext is a DeclContext that can contain statements,
// RecursiveASTVisitor won't visit the decls that
// BuildAnonymousStructOrUnion() will put into CurContext.
// Also store them here so that they can be part of the
// DeclStmt that gets created in this case.
// FIXME: Also return the IndirectFieldDecls created by
// BuildAnonymousStructOr union, for the same reason?
if (CurContext->isFunctionOrMethod())
AnonRecord = Record;
return BuildAnonymousStructOrUnion(S, DS, AS, Record,
DeclaresAnything = false;
// C11
// A struct-declaration that does not declare an anonymous structure or
// anonymous union shall contain a struct-declarator-list.
// This rule also existed in C89 and C99; the grammar for struct-declaration
// did not permit a struct-declaration without a struct-declarator-list.
if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
// Check for Microsoft C extension: anonymous struct/union member.
// Handle 2 kinds of anonymous struct/union:
// struct STRUCT;
// union UNION;
// and
// STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
// UNION_TYPE; <- where UNION_TYPE is a typedef union.
if ((Tag && Tag->getDeclName()) ||
DS.getTypeSpecType() == DeclSpec::TST_typename) {
RecordDecl *Record = nullptr;
if (Tag)
Record = dyn_cast<RecordDecl>(Tag);
else if (const RecordType *RT =
Record = RT->getDecl();
else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
Record = UT->getDecl();
if (Record && getLangOpts().MicrosoftExt) {
Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
<< Record->isUnion() << DS.getSourceRange();
return BuildMicrosoftCAnonymousStruct(S, DS, Record);
DeclaresAnything = false;
// Skip all the checks below if we have a type error.
if (DS.getTypeSpecType() == DeclSpec::TST_error ||
(TagD && TagD->isInvalidDecl()))
return TagD;
if (getLangOpts().CPlusPlus &&
DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
if (Enum->enumerator_begin() == Enum->enumerator_end() &&
!Enum->getIdentifier() && !Enum->isInvalidDecl())
DeclaresAnything = false;
if (!DS.isMissingDeclaratorOk()) {
// Customize diagnostic for a typedef missing a name.
if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
<< DS.getSourceRange();
DeclaresAnything = false;
if (DS.isModulePrivateSpecified() &&
Tag && Tag->getDeclContext()->isFunctionOrMethod())
Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
<< Tag->getTagKind()
<< FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
// C 6.7/2:
// A declaration [...] shall declare at least a declarator [...], a tag,
// or the members of an enumeration.
// C++ [dcl.dcl]p3:
// [If there are no declarators], and except for the declaration of an
// unnamed bit-field, the decl-specifier-seq shall introduce one or more
// names into the program, or shall redeclare a name introduced by a
// previous declaration.
if (!DeclaresAnything) {
// In C, we allow this as a (popular) extension / bug. Don't bother
// producing further diagnostics for redundant qualifiers after this.
Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
return TagD;
// C++ []p1:
// If a storage-class-specifier appears in a decl-specifier-seq, [...] the
// init-declarator-list of the declaration shall not be empty.
// C++ [dcl.fct.spec]p1:
// If a cv-qualifier appears in a decl-specifier-seq, the
// init-declarator-list of the declaration shall not be empty.
// Spurious qualifiers here appear to be valid in C.
unsigned DiagID = diag::warn_standalone_specifier;
if (getLangOpts().CPlusPlus)
DiagID = diag::ext_standalone_specifier;
// Note that a linkage-specification sets a storage class, but
// 'extern "C" struct foo;' is actually valid and not theoretically
// useless.
if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
if (SCS == DeclSpec::SCS_mutable)
// Since mutable is not a viable storage class specifier in C, there is
// no reason to treat it as an extension. Instead, diagnose as an error.
Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
Diag(DS.getStorageClassSpecLoc(), DiagID)
<< DeclSpec::getSpecifierName(SCS);
if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
<< DeclSpec::getSpecifierName(TSCS);
if (DS.getTypeQualifiers()) {
if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Diag(DS.getConstSpecLoc(), DiagID) << "const";
if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
// Restrict is covered above.
if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
// Warn about ignored type attributes, for example:
// __attribute__((aligned)) struct A;
// Attributes should be placed after tag to apply to type declaration.
if (!DS.getAttributes().empty()) {
DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
if (TypeSpecType == DeclSpec::TST_class ||
TypeSpecType == DeclSpec::TST_struct ||
TypeSpecType == DeclSpec::TST_interface ||
TypeSpecType == DeclSpec::TST_union ||
TypeSpecType == DeclSpec::TST_enum) {
for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
attrs = attrs->getNext())
Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
<< attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
return TagD;
/// We are trying to inject an anonymous member into the given scope;
/// check if there's an existing declaration that can't be overloaded.
/// \return true if this is a forbidden redeclaration
static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
Scope *S,
DeclContext *Owner,
DeclarationName Name,
SourceLocation NameLoc,
bool IsUnion) {
LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
if (!SemaRef.LookupName(R, S)) return false;
// Pick a representative declaration.
NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
assert(PrevDecl && "Expected a non-null Decl");
if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
return false;
SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
<< IsUnion << Name;
SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
return true;
/// InjectAnonymousStructOrUnionMembers - Inject the members of the
/// anonymous struct or union AnonRecord into the owning context Owner
/// and scope S. This routine will be invoked just after we realize
/// that an unnamed union or struct is actually an anonymous union or
/// struct, e.g.,
/// @code
/// union {
/// int i;
/// float f;
/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
/// // f into the surrounding scope.x
/// @endcode
/// This routine is recursive, injecting the names of nested anonymous
/// structs/unions into the owning context and scope as well.
static bool
InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
RecordDecl *AnonRecord, AccessSpecifier AS,
SmallVectorImpl<NamedDecl *> &Chaining) {
bool Invalid = false;
// Look every FieldDecl and IndirectFieldDecl with a name.
for (auto *D : AnonRecord->decls()) {
if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
cast<NamedDecl>(D)->getDeclName()) {
ValueDecl *VD = cast<ValueDecl>(D);
if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
AnonRecord->isUnion())) {
// C++ [class.union]p2:
// The names of the members of an anonymous union shall be
// distinct from the names of any other entity in the
// scope in which the anonymous union is declared.
Invalid = true;
} else {
// C++ [class.union]p2:
// For the purpose of name lookup, after the anonymous union
// definition, the members of the anonymous union are
// considered to have been defined in the scope in which the
// anonymous union is declared.
unsigned OldChainingSize = Chaining.size();
if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
Chaining.append(IF->chain_begin(), IF->chain_end());
assert(Chaining.size() >= 2);
NamedDecl **NamedChain =
new (SemaRef.Context)NamedDecl*[Chaining.size()];
for (unsigned i = 0; i < Chaining.size(); i++)
NamedChain[i] = Chaining[i];
IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
VD->getType(), {NamedChain, Chaining.size()});
for (const auto *Attr : VD->attrs())
SemaRef.PushOnScopeChains(IndirectField, S);
// That includes picking up the appropriate access specifier.
if (AS != AS_none) IndirectField->setAccess(AS);
return Invalid;
/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
/// a VarDecl::StorageClass. Any error reporting is up to the caller:
/// illegal input values are mapped to SC_None.
static StorageClass
StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
assert(StorageClassSpec != DeclSpec::SCS_typedef &&
"Parser allowed 'typedef' as storage class VarDecl.");
switch (StorageClassSpec) {
case DeclSpec::SCS_unspecified: return SC_None;
case DeclSpec::SCS_extern:
if (DS.isExternInLinkageSpec())
return SC_None;
return SC_Extern;
case DeclSpec::SCS_static: return SC_Static;
case DeclSpec::SCS_auto: return SC_Auto;
case DeclSpec::SCS_register: return SC_Register;
case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
// Illegal SCSs map to None: error reporting is up to the caller.
case DeclSpec::SCS_mutable: // Fall through.
case DeclSpec::SCS_typedef: return SC_None;
llvm_unreachable("unknown storage class specifier");
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
for (const auto *I : Record->decls()) {
const auto *FD = dyn_cast<FieldDecl>(I);
if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
FD = IFD->getAnonField();
if (FD && FD->hasInClassInitializer())
return FD->getLocation();
llvm_unreachable("couldn't find in-class initializer");
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
SourceLocation DefaultInitLoc) {
if (!Parent->isUnion() || !Parent->hasInClassInitializer())
S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
CXXRecordDecl *AnonUnion) {
if (!Parent->isUnion() || !Parent->hasInClassInitializer())
checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
/// BuildAnonymousStructOrUnion - Handle the declaration of an
/// anonymous structure or union. Anonymous unions are a C++ feature
/// (C++ [class.union]) and a C11 feature; anonymous structures
/// are a C11 feature and GNU C++ extension.
Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
AccessSpecifier AS,
RecordDecl *Record,
const PrintingPolicy &Policy) {
DeclContext *Owner = Record->getDeclContext();
// Diagnose whether this anonymous struct/union is an extension.
if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Diag(Record->getLocation(), diag::ext_anonymous_union);
else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
else if (!Record->isUnion() && !getLangOpts().C11)
Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
// C and C++ require different kinds of checks for anonymous
// structs/unions.
bool Invalid = false;
if (getLangOpts().CPlusPlus) {
const char *PrevSpec = nullptr;
unsigned DiagID;
if (Record->isUnion()) {
// C++ [class.union]p6:
// Anonymous unions declared in a named namespace or in the
// global namespace shall be declared static.
if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
(isa<TranslationUnitDecl>(Owner) ||
(isa<NamespaceDecl>(Owner) &&
cast<NamespaceDecl>(Owner)->getDeclName()))) {
Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
<< FixItHint::CreateInsertion(Record->getLocation(), "static ");
// Recover by adding 'static'.
DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
PrevSpec, DiagID, Policy);
// C++ [class.union]p6:
// A storage class is not allowed in a declaration of an
// anonymous union in a class scope.
else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
isa<RecordDecl>(Owner)) {
<< FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
// Recover by removing the storage specifier.
DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
PrevSpec, DiagID, Context.getPrintingPolicy());
// Ignore const/volatile/restrict qualifiers.
if (DS.getTypeQualifiers()) {
if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
<< Record->isUnion() << "const"
<< FixItHint::CreateRemoval(DS.getConstSpecLoc());
if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
<< Record->isUnion() << "volatile"
<< FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
<< Record->isUnion() << "restrict"
<< FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
<< Record->isUnion() << "_Atomic"
<< FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
<< Record->isUnion() << "__unaligned"
<< FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
// C++ [class.union]p2:
// The member-specification of an anonymous union shall only
// define non-static data members. [Note: nested types and
// functions cannot be declared within an anonymous union. ]
for (auto *Mem : Record->decls()) {
if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
// C++ [class.union]p3:
// An anonymous union shall not have private or protected
// members (clause 11).
assert(FD->getAccess() != AS_none);
if (FD->getAccess() != AS_public) {
Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
<< Record->isUnion() << (FD->getAccess() == AS_protected);
Invalid = true;
// C++ [class.union]p1
// An object of a class with a non-trivial constructor, a non-trivial
// copy constructor, a non-trivial destructor, or a non-trivial copy
// assignment operator cannot be a member of a union, nor can an
// array of such objects.
if (CheckNontrivialField(FD))
Invalid = true;
} else if (Mem->isImplicit()) {
// Any implicit members are fine.
} else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
// This is a type that showed up in an
// elaborated-type-specifier inside the anonymous struct or
// union, but which actually declares a type outside of the
// anonymous struct or union. It's okay.
} else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
if (!MemRecord->isAnonymousStructOrUnion() &&
MemRecord->getDeclName()) {
// Visual C++ allows type definition in anonymous struct or union.
if (getLangOpts().MicrosoftExt)
Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
<< Record->isUnion();
else {
// This is a nested type declaration.
Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
<< Record->isUnion();
Invalid = true;
} else {
// This is an anonymous type definition within another anonymous type.
// This is a popular extension, provided by Plan9, MSVC and GCC, but
// not part of standard C++.
<< Record->isUnion();
} else if (isa<AccessSpecDecl>(Mem)) {
// Any access specifier is fine.
} else if (isa<StaticAssertDecl>(Mem)) {
// In C++1z, static_assert declarations are also fine.
} else {
// We have something that isn't a non-static data
// member. Complain about it.
unsigned DK = diag::err_anonymous_record_bad_member;
if (isa<TypeDecl>(Mem))
DK = diag::err_anonymous_record_with_type;
else if (isa<FunctionDecl>(Mem))
DK = diag::err_anonymous_record_with_function;
else if (isa<VarDecl>(Mem))
DK = diag::err_anonymous_record_with_static;
// Visual C++ allows type definition in anonymous struct or union.
if (getLangOpts().MicrosoftExt &&
DK == diag::err_anonymous_record_with_type)
Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
<< Record->isUnion();
else {
Diag(Mem->getLocation(), DK) << Record->isUnion();
Invalid = true;
// C++11 [class.union]p8 (DR1460):
// At most one variant member of a union may have a
// brace-or-equal-initializer.
if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
if (!Record->isUnion() && !Owner->isRecord()) {
Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
<< getLangOpts().CPlusPlus;
Invalid = true;
// Mock up a declarator.
Declarator Dc(DS, Declarator::MemberContext);
TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
assert(TInfo && "couldn't build declarator info for anonymous struct/union");
// Create a declaration for this anonymous struct/union.
NamedDecl *Anon = nullptr;
if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Anon = FieldDecl::Create(Context, OwningClass,
/*BitWidth=*/nullptr, /*Mutable=*/false,
if (getLangOpts().CPlusPlus)
} else {
DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
if (SCSpec == DeclSpec::SCS_mutable) {
// mutable can only appear on non-static class members, so it's always
// an error here
Diag(Record->getLocation(), diag::err_mutable_nonmember);
Invalid = true;
SC = SC_None;
Anon = VarDecl::Create(Context, Owner,
Record->getLocation(), /*IdentifierInfo=*/nullptr,
TInfo, SC);
// Default-initialize the implicit variable. This initialization will be
// trivial in almost all cases, except if a union member has an in-class
// initializer:
// union { int n = 0; };
// Mark this as an anonymous struct/union type.
// Add the anonymous struct/union object to the current
// context. We'll be referencing this object when we refer to one of
// its members.
// Inject the members of the anonymous struct/union into the owning
// context and into the identifier resolver chain for name lookup
// purposes.
SmallVector<NamedDecl*, 2> Chain;
if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
Invalid = true;
if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Decl *ManglingContextDecl;
if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
NewVD->getDeclContext(), ManglingContextDecl)) {
NewVD, MCtx->getManglingNumber(
NewVD, getMSManglingNumber(getLangOpts(), S)));
Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
if (Invalid)
return Anon;
/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
/// Microsoft C anonymous structure.
/// Ref:
/// Example:
/// struct A { int a; };
/// struct B { struct A; int b; };
/// void foo() {
/// B var;
/// var.a = 3;
/// }
Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
RecordDecl *Record) {
assert(Record && "expected a record!");
// Mock up a declarator.
Declarator Dc(DS, Declarator::TypeNameContext);
TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
assert(TInfo && "couldn't build declarator info for anonymous struct");
auto *ParentDecl = cast<RecordDecl>(CurContext);
QualType RecTy = Context.getTypeDeclType(Record);
// Create a declaration for this anonymous struct.
NamedDecl *Anon = FieldDecl::Create(Context,
/*BitWidth=*/nullptr, /*Mutable=*/false,
// Add the anonymous struct object to the current context.
// Inject the members of the anonymous struct into the current
// context and into the identifier resolver chain for name lookup
// purposes.
SmallVector<NamedDecl*, 2> Chain;
RecordDecl *RecordDef = Record->getDefinition();
if (RequireCompleteType(Anon->getLocation(), RecTy,
diag::err_field_incomplete) ||
InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
AS_none, Chain)) {
return Anon;
/// GetNameForDeclarator - Determine the full declaration name for the
/// given Declarator.
DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
return GetNameFromUnqualifiedId(D.getName());
/// \brief Retrieves the declaration name from a parsed unqualified-id.
Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
DeclarationNameInfo NameInfo;
switch (Name.getKind()) {
case UnqualifiedId::IK_ImplicitSelfParam:
case UnqualifiedId::IK_Identifier:
return NameInfo;
case UnqualifiedId::IK_DeductionGuideName: {
// C++ []p3:
// The simple-template-id shall name a class template specialization.
// The template-name shall be the same identifier as the template-name
// of the simple-template-id.
// These together intend to imply that the template-name shall name a
// class template.
// FIXME: template<typename T> struct X {};
// template<typename T> using Y = X<T>;
// Y(int) -> Y<int>;
// satisfies these rules but does not name a class template.
TemplateName TN = Name.TemplateName.get().get();
auto *Template = TN.getAsTemplateDecl();
if (!Template || !isa<ClassTemplateDecl>(Template)) {
<< (int)getTemplateNameKindForDiagnostics(TN) << TN;
if (Template)
Diag(Template->getLocation(), diag::note_template_decl_here);
return DeclarationNameInfo();
return NameInfo;
case UnqualifiedId::IK_OperatorFunctionId:
= Name.OperatorFunctionId.SymbolLocations[0];
= Name.EndLocation.getRawEncoding();
return NameInfo;
case UnqualifiedId::IK_LiteralOperatorId:
return NameInfo;
case UnqualifiedId::IK_ConversionFunctionId: {
TypeSourceInfo *TInfo;
QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
if (Ty.isNull())
return DeclarationNameInfo();
return NameInfo;
case UnqualifiedId::IK_ConstructorName: {
TypeSourceInfo *TInfo;
QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
if (Ty.isNull())
return DeclarationNameInfo();
return NameInfo;
case UnqualifiedId::IK_ConstructorTemplateId: {
// In well-formed code, we can only have a constructor
// template-id that refers to the current context, so go there
// to find the actual type being constructed.