#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTLambda.h"
#include "clang/AST/ASTMutationListener.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/CharUnits.h"
#include "clang/AST/ComparisonCategories.h"
#include "clang/AST/EvaluatedExprVisitor.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/AST/TypeLoc.h"
#include "clang/AST/TypeOrdering.h"
#include "clang/Basic/AttributeCommonInfo.h"
#include "clang/Basic/PartialDiagnostic.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/LiteralSupport.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/CXXFieldCollector.h"
#include "clang/Sema/DeclSpec.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/ScopeExit.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include <map>
#include <set>
using namespace clang;
namespace {
class CheckDefaultArgumentVisitor
: public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
Sema &S;
const Expr *DefaultArg;
public:
CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
: S(S), DefaultArg(DefaultArg) {}
bool VisitExpr(const Expr *Node);
bool VisitDeclRefExpr(const DeclRefExpr *DRE);
bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
bool VisitLambdaExpr(const LambdaExpr *Lambda);
bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
};
bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
bool IsInvalid = false;
for (const Stmt *SubStmt : Node->children())
IsInvalid |= Visit(SubStmt);
return IsInvalid;
}
bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
const NamedDecl *Decl = DRE->getDecl();
if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
if (DRE->isNonOdrUse() != NOUR_Unevaluated)
return S.Diag(DRE->getBeginLoc(),
diag::err_param_default_argument_references_param)
<< Param->getDeclName() << DefaultArg->getSourceRange();
} else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
return S.Diag(DRE->getBeginLoc(),
diag::err_param_default_argument_references_local)
<< VDecl->getDeclName() << DefaultArg->getSourceRange();
}
return false;
}
bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
return S.Diag(ThisE->getBeginLoc(),
diag::err_param_default_argument_references_this)
<< ThisE->getSourceRange();
}
bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
const PseudoObjectExpr *POE) {
bool Invalid = false;
for (const Expr *E : POE->semantics()) {
if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
E = OVE->getSourceExpr();
assert(E && "pseudo-object binding without source expression?");
}
Invalid |= Visit(E);
}
return Invalid;
}
bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
if (Lambda->capture_begin() == Lambda->capture_end())
return false;
return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
}
}
void
Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
const CXXMethodDecl *Method) {
if (!Method || ComputedEST == EST_MSAny)
return;
const FunctionProtoType *Proto
= Method->getType()->getAs<FunctionProtoType>();
Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
if (!Proto)
return;
ExceptionSpecificationType EST = Proto->getExceptionSpecType();
if (ComputedEST == EST_None)
return;
if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
EST = EST_BasicNoexcept;
switch (EST) {
case EST_Unparsed:
case EST_Uninstantiated:
case EST_Unevaluated:
llvm_unreachable("should not see unresolved exception specs here");
case EST_MSAny:
case EST_None:
ClearExceptions();
ComputedEST = EST;
return;
case EST_NoexceptFalse:
ClearExceptions();
ComputedEST = EST_None;
return;
case EST_BasicNoexcept:
case EST_NoexceptTrue:
case EST_NoThrow:
return;
case EST_DynamicNone:
if (ComputedEST == EST_BasicNoexcept)
ComputedEST = EST_DynamicNone;
return;
case EST_DependentNoexcept:
llvm_unreachable(
"should not generate implicit declarations for dependent cases");
case EST_Dynamic:
break;
}
assert(EST == EST_Dynamic && "EST case not considered earlier.");
assert(ComputedEST != EST_None &&
"Shouldn't collect exceptions when throw-all is guaranteed.");
ComputedEST = EST_Dynamic;
for (const auto &E : Proto->exceptions())
if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
Exceptions.push_back(E);
}
void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
if (!S || ComputedEST == EST_MSAny)
return;
if (Self->canThrow(S))
ComputedEST = EST_None;
}
ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
SourceLocation EqualLoc) {
if (RequireCompleteType(Param->getLocation(), Param->getType(),
diag::err_typecheck_decl_incomplete_type))
return true;
InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
Param);
InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
EqualLoc);
InitializationSequence InitSeq(*this, Entity, Kind, Arg);
ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
if (Result.isInvalid())
return true;
Arg = Result.getAs<Expr>();
CheckCompletedExpr(Arg, EqualLoc);
Arg = MaybeCreateExprWithCleanups(Arg);
return Arg;
}
void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
SourceLocation EqualLoc) {
Param->setDefaultArg(Arg);
UnparsedDefaultArgInstantiationsMap::iterator InstPos
= UnparsedDefaultArgInstantiations.find(Param);
if (InstPos != UnparsedDefaultArgInstantiations.end()) {
for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
UnparsedDefaultArgInstantiations.erase(InstPos);
}
}
void
Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
Expr *DefaultArg) {
if (!param || !DefaultArg)
return;
ParmVarDecl *Param = cast<ParmVarDecl>(param);
UnparsedDefaultArgLocs.erase(Param);
auto Fail = [&] {
Param->setInvalidDecl();
Param->setDefaultArg(new (Context) OpaqueValueExpr(
EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
};
if (!getLangOpts().CPlusPlus) {
Diag(EqualLoc, diag::err_param_default_argument)
<< DefaultArg->getSourceRange();
return Fail();
}
if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
return Fail();
}
if (Param->isParameterPack()) {
Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
<< DefaultArg->getSourceRange();
Param->setDefaultArg(nullptr);
return;
}
ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
if (Result.isInvalid())
return Fail();
DefaultArg = Result.getAs<Expr>();
CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
if (DefaultArgChecker.Visit(DefaultArg))
return Fail();
SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
}
void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
SourceLocation EqualLoc,
SourceLocation ArgLoc) {
if (!param)
return;
ParmVarDecl *Param = cast<ParmVarDecl>(param);
Param->setUnparsedDefaultArg();
UnparsedDefaultArgLocs[Param] = ArgLoc;
}
void Sema::ActOnParamDefaultArgumentError(Decl *param,
SourceLocation EqualLoc) {
if (!param)
return;
ParmVarDecl *Param = cast<ParmVarDecl>(param);
Param->setInvalidDecl();
UnparsedDefaultArgLocs.erase(Param);
Param->setDefaultArg(new (Context) OpaqueValueExpr(
EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
}
void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
bool MightBeFunction = D.isFunctionDeclarationContext();
for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
DeclaratorChunk &chunk = D.getTypeObject(i);
if (chunk.Kind == DeclaratorChunk::Function) {
if (MightBeFunction) {
MightBeFunction = false;
continue;
}
for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
++argIdx) {
ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
if (Param->hasUnparsedDefaultArg()) {
std::unique_ptr<CachedTokens> Toks =
std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
SourceRange SR;
if (Toks->size() > 1)
SR = SourceRange((*Toks)[1].getLocation(),
Toks->back().getLocation());
else
SR = UnparsedDefaultArgLocs[Param];
Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
<< SR;
} else if (Param->getDefaultArg()) {
Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
<< Param->getDefaultArg()->getSourceRange();
Param->setDefaultArg(nullptr);
}
}
} else if (chunk.Kind != DeclaratorChunk::Paren) {
MightBeFunction = false;
}
}
}
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
});
}
bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
Scope *S) {
bool Invalid = false;
DeclContext *ScopeDC = New->isLocalExternDecl()
? New->getLexicalDeclContext()
: New->getDeclContext();
FunctionDecl *PrevForDefaultArgs = Old;
for (; PrevForDefaultArgs;
PrevForDefaultArgs = New->isLocalExternDecl()
? nullptr
: PrevForDefaultArgs->getPreviousDecl()) {
if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
continue;
if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
!New->isCXXClassMember()) {
continue;
}
if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
continue;
}
break;
}
for (unsigned p = 0, NumParams = PrevForDefaultArgs
? PrevForDefaultArgs->getNumParams()
: 0;
p < NumParams; ++p) {
ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
ParmVarDecl *NewParam = New->getParamDecl(p);
bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
bool NewParamHasDfl = NewParam->hasDefaultArg();
if (OldParamHasDfl && NewParamHasDfl) {
unsigned DiagDefaultParamID =
diag::err_param_default_argument_redefinition;
Invalid = true;
if (getLangOpts().MicrosoftExt) {
CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
if (MD && MD->getParent()->getDescribedClassTemplate()) {
NewParam->setHasInheritedDefaultArg();
if (OldParam->hasUninstantiatedDefaultArg())
NewParam->setUninstantiatedDefaultArg(
OldParam->getUninstantiatedDefaultArg());
else
NewParam->setDefaultArg(OldParam->getInit());
DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Invalid = false;
}
}
Diag(NewParam->getLocation(), DiagDefaultParamID)
<< NewParam->getDefaultArgRange();
for (auto Older = PrevForDefaultArgs;
OldParam->hasInheritedDefaultArg(); ) {
Older = Older->getPreviousDecl();
OldParam = Older->getParamDecl(p);
}
Diag(OldParam->getLocation(), diag::note_previous_definition)
<< OldParam->getDefaultArgRange();
} else if (OldParamHasDfl) {
if (New->getFriendObjectKind() == Decl::FOK_None ||
!New->getLexicalDeclContext()->isDependentContext()) {
NewParam->setHasInheritedDefaultArg();
if (OldParam->hasUnparsedDefaultArg())
NewParam->setUnparsedDefaultArg();
else if (OldParam->hasUninstantiatedDefaultArg())
NewParam->setUninstantiatedDefaultArg(
OldParam->getUninstantiatedDefaultArg());
else
NewParam->setDefaultArg(OldParam->getInit());
}
} else if (NewParamHasDfl) {
if (New->getDescribedFunctionTemplate()) {
Diag(NewParam->getLocation(),
diag::err_param_default_argument_template_redecl)
<< NewParam->getDefaultArgRange();
Diag(PrevForDefaultArgs->getLocation(),
diag::note_template_prev_declaration)
<< false;
} else if (New->getTemplateSpecializationKind()
!= TSK_ImplicitInstantiation &&
New->getTemplateSpecializationKind() != TSK_Undeclared) {
Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
<< (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
<< New->getDeclName()
<< NewParam->getDefaultArgRange();
} else if (New->getDeclContext()->isDependentContext()) {
int WhichKind = 2;
if (CXXRecordDecl *Record
= dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
if (Record->getDescribedClassTemplate())
WhichKind = 0;
else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
WhichKind = 1;
else
WhichKind = 2;
}
Diag(NewParam->getLocation(),
diag::err_param_default_argument_member_template_redecl)
<< WhichKind
<< NewParam->getDefaultArgRange();
}
}
}
if (isa<CXXConstructorDecl>(New) &&
New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
if (NewSM != OldSM) {
ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
assert(NewParam->hasDefaultArg());
Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
<< NewParam->getDefaultArgRange() << NewSM;
Diag(Old->getLocation(), diag::note_previous_declaration);
}
}
const FunctionDecl *Def;
if (New->getConstexprKind() != Old->getConstexprKind()) {
Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
<< New << static_cast<int>(New->getConstexprKind())
<< static_cast<int>(Old->getConstexprKind());
Diag(Old->getLocation(), diag::note_previous_declaration);
Invalid = true;
} else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
Old->isDefined(Def) &&
(New->isInlineSpecified() ||
New->getFriendObjectKind() == Decl::FOK_None)) {
Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
Diag(Def->getLocation(), diag::note_previous_definition);
Invalid = true;
}
if (isa<CXXDeductionGuideDecl>(New) &&
!New->isFunctionTemplateSpecialization() && isVisible(Old)) {
Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
Diag(Old->getLocation(), diag::note_previous_declaration);
}
if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
functionDeclHasDefaultArgument(Old)) {
Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
Diag(Old->getLocation(), diag::note_previous_declaration);
Invalid = true;
}
const FunctionDecl *OldDefinition = nullptr;
if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
Old->isDefined(OldDefinition, true))
CheckForFunctionRedefinition(New, OldDefinition);
return Invalid;
}
NamedDecl *
Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParamLists) {
assert(D.isDecompositionDeclarator());
const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
if (!D.mayHaveDecompositionDeclarator()) {
Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
<< Decomp.getSourceRange();
return nullptr;
}
if (!TemplateParamLists.empty()) {
Diag(TemplateParamLists.front()->getTemplateLoc(),
diag::err_decomp_decl_template);
return nullptr;
}
Diag(Decomp.getLSquareLoc(),
!getLangOpts().CPlusPlus17
? diag::ext_decomp_decl
: D.getContext() == DeclaratorContext::Condition
? diag::ext_decomp_decl_cond
: diag::warn_cxx14_compat_decomp_decl)
<< Decomp.getSourceRange();
DeclContext *const DC = CurContext;
auto &DS = D.getDeclSpec();
{
SmallVector<StringRef, 8> BadSpecifiers;
SmallVector<SourceLocation, 8> BadSpecifierLocs;
SmallVector<StringRef, 8> CPlusPlus20Specifiers;
SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
if (auto SCS = DS.getStorageClassSpec()) {
if (SCS == DeclSpec::SCS_static) {
CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
} else {
BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
}
}
if (auto TSCS = DS.getThreadStorageClassSpec()) {
CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
}
if (DS.hasConstexprSpecifier()) {
BadSpecifiers.push_back(
DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
}
if (DS.isInlineSpecified()) {
BadSpecifiers.push_back("inline");
BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
}
if (!BadSpecifiers.empty()) {
auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
Err << (int)BadSpecifiers.size()
<< llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
for (auto Loc : BadSpecifierLocs)
Err << SourceRange(Loc, Loc);
} else if (!CPlusPlus20Specifiers.empty()) {
auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
getLangOpts().CPlusPlus20
? diag::warn_cxx17_compat_decomp_decl_spec
: diag::ext_decomp_decl_spec);
Warn << (int)CPlusPlus20Specifiers.size()
<< llvm::join(CPlusPlus20Specifiers.begin(),
CPlusPlus20Specifiers.end(), " ");
for (auto Loc : CPlusPlus20SpecifierLocs)
Warn << SourceRange(Loc, Loc);
}
if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
return nullptr;
}
if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
getLangOpts().CPlusPlus20)
Diag(DS.getVolatileSpecLoc(),
diag::warn_deprecated_volatile_structured_binding);
TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
QualType R = TInfo->getType();
if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
UPPC_DeclarationType))
D.setInvalidType();
if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
(D.getNumTypeObjects() == 1 &&
D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
Diag(Decomp.getLSquareLoc(),
(D.hasGroupingParens() ||
(D.getNumTypeObjects() &&
D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
? diag::err_decomp_decl_parens
: diag::err_decomp_decl_type)
<< R;
if (R->isFunctionType())
D.setInvalidType();
}
SmallVector<BindingDecl*, 8> Bindings;
for (auto &B : D.getDecompositionDeclarator().bindings()) {
DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
ForVisibleRedeclaration);
LookupName(Previous, S,
DC->getRedeclContext()->isTranslationUnit());
if (Previous.isSingleResult() &&
Previous.getFoundDecl()->isTemplateParameter()) {
DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Previous.getFoundDecl());
Previous.clear();
}
auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
? getShadowedDeclaration(BD, Previous)
: nullptr;
bool ConsiderLinkage = DC->isFunctionOrMethod() &&
DS.getStorageClassSpec() == DeclSpec::SCS_extern;
FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
false);
if (!Previous.empty()) {
auto *Old = Previous.getRepresentativeDecl();
Diag(B.NameLoc, diag::err_redefinition) << B.Name;
Diag(Old->getLocation(), diag::note_previous_definition);
} else if (ShadowedDecl && !D.isRedeclaration()) {
CheckShadow(BD, ShadowedDecl, Previous);
}
PushOnScopeChains(BD, S, true);
Bindings.push_back(BD);
ParsingInitForAutoVars.insert(BD);
}
DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
Decomp.getLSquareLoc());
LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
ForVisibleRedeclaration);
bool AddToScope = true;
NamedDecl *New =
ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
MultiTemplateParamsArg(), AddToScope, Bindings);
if (AddToScope) {
S->AddDecl(New);
CurContext->addHiddenDecl(New);
}
if (isInOpenMPDeclareTargetContext())
checkDeclIsAllowedInOpenMPTarget(nullptr, New);
return New;
}
static bool checkSimpleDecomposition(
Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
if ((int64_t)Bindings.size() != NumElems) {
S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
<< DecompType << (unsigned)Bindings.size()
<< (unsigned)NumElems.getLimitedValue(UINT_MAX)
<< toString(NumElems, 10) << (NumElems < Bindings.size());
return true;
}
unsigned I = 0;
for (auto *B : Bindings) {
SourceLocation Loc = B->getLocation();
ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
if (E.isInvalid())
return true;
E = GetInit(Loc, E.get(), I++);
if (E.isInvalid())
return true;
B->setBinding(ElemType, E.get());
}
return false;
}
static bool checkArrayLikeDecomposition(Sema &S,
ArrayRef<BindingDecl *> Bindings,
ValueDecl *Src, QualType DecompType,
const llvm::APSInt &NumElems,
QualType ElemType) {
return checkSimpleDecomposition(
S, Bindings, Src, DecompType, NumElems, ElemType,
[&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
ExprResult E = S.ActOnIntegerConstant(Loc, I);
if (E.isInvalid())
return ExprError();
return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
});
}
static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
ValueDecl *Src, QualType DecompType,
const ConstantArrayType *CAT) {
return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
llvm::APSInt(CAT->getSize()),
CAT->getElementType());
}
static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
ValueDecl *Src, QualType DecompType,
const VectorType *VT) {
return checkArrayLikeDecomposition(
S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
S.Context.getQualifiedType(VT->getElementType(),
DecompType.getQualifiers()));
}
static bool checkComplexDecomposition(Sema &S,
ArrayRef<BindingDecl *> Bindings,
ValueDecl *Src, QualType DecompType,
const ComplexType *CT) {
return checkSimpleDecomposition(
S, Bindings, Src, DecompType, llvm::APSInt::get(2),
S.Context.getQualifiedType(CT->getElementType(),
DecompType.getQualifiers()),
[&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
});
}
static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
TemplateArgumentListInfo &Args,
const TemplateParameterList *Params) {
SmallString<128> SS;
llvm::raw_svector_ostream OS(SS);
bool First = true;
unsigned I = 0;
for (auto &Arg : Args.arguments()) {
if (!First)
OS << ", ";
Arg.getArgument().print(PrintingPolicy, OS,
TemplateParameterList::shouldIncludeTypeForArgument(
PrintingPolicy, Params, I));
First = false;
I++;
}
return std::string(OS.str());
}
static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
SourceLocation Loc, StringRef Trait,
TemplateArgumentListInfo &Args,
unsigned DiagID) {
auto DiagnoseMissing = [&] {
if (DiagID)
S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
Args, nullptr);
return true;
};
NamespaceDecl *Std = S.getStdNamespace();
if (!Std)
return DiagnoseMissing();
LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
Loc, Sema::LookupOrdinaryName);
if (!S.LookupQualifiedName(Result, Std))
return DiagnoseMissing();
if (Result.isAmbiguous())
return true;
ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
if (!TraitTD) {
Result.suppressDiagnostics();
NamedDecl *Found = *Result.begin();
S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
S.Diag(Found->getLocation(), diag::note_declared_at);
return true;
}
QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
if (TraitTy.isNull())
return true;
if (!S.isCompleteType(Loc, TraitTy)) {
if (DiagID)
S.RequireCompleteType(
Loc, TraitTy, DiagID,
printTemplateArgs(S.Context.getPrintingPolicy(), Args,
TraitTD->getTemplateParameters()));
return true;
}
CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
assert(RD && "specialization of class template is not a class?");
S.LookupQualifiedName(TraitMemberLookup, RD);
return TraitMemberLookup.isAmbiguous();
}
static TemplateArgumentLoc
getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
uint64_t I) {
TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
}
static TemplateArgumentLoc
getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
}
namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
llvm::APSInt &Size) {
EnterExpressionEvaluationContext ContextRAII(
S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
DeclarationName Value = S.PP.getIdentifierInfo("value");
LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
TemplateArgumentListInfo Args(Loc, Loc);
Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, 0) ||
R.empty())
return IsTupleLike::NotTupleLike;
struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
LookupResult &R;
TemplateArgumentListInfo &Args;
ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
: R(R), Args(Args) {}
Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
SourceLocation Loc) override {
return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
<< printTemplateArgs(S.Context.getPrintingPolicy(), Args,
nullptr);
}
} Diagnoser(R, Args);
ExprResult E =
S.BuildDeclarationNameExpr(CXXScopeSpec(), R, false);
if (E.isInvalid())
return IsTupleLike::Error;
E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
if (E.isInvalid())
return IsTupleLike::Error;
return IsTupleLike::TupleLike;
}
static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
unsigned I, QualType T) {
TemplateArgumentListInfo Args(Loc, Loc);
Args.addArgument(
getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
if (lookupStdTypeTraitMember(
S, R, Loc, "tuple_element", Args,
diag::err_decomp_decl_std_tuple_element_not_specialized))
return QualType();
auto *TD = R.getAsSingle<TypeDecl>();
if (!TD) {
R.suppressDiagnostics();
S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
<< printTemplateArgs(S.Context.getPrintingPolicy(), Args,
nullptr);
if (!R.empty())
S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
return QualType();
}
return S.Context.getTypeDeclType(TD);
}
namespace {
struct InitializingBinding {
Sema &S;
InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
Sema::CodeSynthesisContext Ctx;
Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
Ctx.PointOfInstantiation = BD->getLocation();
Ctx.Entity = BD;
S.pushCodeSynthesisContext(Ctx);
}
~InitializingBinding() {
S.popCodeSynthesisContext();
}
};
}
static bool checkTupleLikeDecomposition(Sema &S,
ArrayRef<BindingDecl *> Bindings,
VarDecl *Src, QualType DecompType,
const llvm::APSInt &TupleSize) {
if ((int64_t)Bindings.size() != TupleSize) {
S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
<< DecompType << (unsigned)Bindings.size()
<< (unsigned)TupleSize.getLimitedValue(UINT_MAX)
<< toString(TupleSize, 10) << (TupleSize < Bindings.size());
return true;
}
if (Bindings.empty())
return false;
DeclarationName GetDN = S.PP.getIdentifierInfo("get");
LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
bool UseMemberGet = false;
if (S.isCompleteType(Src->getLocation(), DecompType)) {
if (auto *RD = DecompType->getAsCXXRecordDecl())
S.LookupQualifiedName(MemberGet, RD);
if (MemberGet.isAmbiguous())
return true;
for (NamedDecl *D : MemberGet) {
if (FunctionTemplateDecl *FTD =
dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
TemplateParameterList *TPL = FTD->getTemplateParameters();
if (TPL->size() != 0 &&
isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
UseMemberGet = true;
break;
}
}
}
}
unsigned I = 0;
for (auto *B : Bindings) {
InitializingBinding InitContext(S, B);
SourceLocation Loc = B->getLocation();
ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
if (E.isInvalid())
return true;
if (!Src->getType()->isLValueReferenceType())
E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
E.get(), nullptr, VK_XValue,
FPOptionsOverride());
TemplateArgumentListInfo Args(Loc, Loc);
Args.addArgument(
getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
if (UseMemberGet) {
E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
CXXScopeSpec(), SourceLocation(), nullptr,
MemberGet, &Args, nullptr);
if (E.isInvalid())
return true;
E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
} else {
Expr *Get = UnresolvedLookupExpr::Create(
S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
DeclarationNameInfo(GetDN, Loc), true, &Args,
UnresolvedSetIterator(), UnresolvedSetIterator());
Expr *Arg = E.get();
E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
}
if (E.isInvalid())
return true;
Expr *Init = E.get();
QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
if (T.isNull())
return true;
QualType RefType =
S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
if (RefType.isNull())
return true;
auto *RefVD = VarDecl::Create(
S.Context, Src->getDeclContext(), Loc, Loc,
B->getDeclName().getAsIdentifierInfo(), RefType,
S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
RefVD->setTSCSpec(Src->getTSCSpec());
RefVD->setImplicit();
if (Src->isInlineSpecified())
RefVD->setInlineSpecified();
RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
InitializationSequence Seq(S, Entity, Kind, Init);
E = Seq.Perform(S, Entity, Kind, Init);
if (E.isInvalid())
return true;
E = S.ActOnFinishFullExpr(E.get(), Loc, false);
if (E.isInvalid())
return true;
RefVD->setInit(E.get());
S.CheckCompleteVariableDeclaration(RefVD);
E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
DeclarationNameInfo(B->getDeclName(), Loc),
RefVD);
if (E.isInvalid())
return true;
B->setBinding(T, E.get());
I++;
}
return false;
}
static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
const CXXRecordDecl *RD,
CXXCastPath &BasePath) {
auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
CXXBasePath &Path) {
return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
};
const CXXRecordDecl *ClassWithFields = nullptr;
AccessSpecifier AS = AS_public;
if (RD->hasDirectFields())
ClassWithFields = RD;
else {
CXXBasePaths Paths;
Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
if (!RD->lookupInBases(BaseHasFields, Paths)) {
return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
}
CXXBasePath *BestPath = nullptr;
for (auto &P : Paths) {
if (!BestPath)
BestPath = &P;
else if (!S.Context.hasSameType(P.back().Base->getType(),
BestPath->back().Base->getType())) {
S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
<< false << RD << BestPath->back().Base->getType()
<< P.back().Base->getType();
return DeclAccessPair();
} else if (P.Access < BestPath->Access) {
BestPath = &P;
}
}
QualType BaseType = BestPath->back().Base->getType();
if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
<< RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
return DeclAccessPair();
}
S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
*BestPath, diag::err_decomp_decl_inaccessible_base);
AS = BestPath->Access;
ClassWithFields = BaseType->getAsCXXRecordDecl();
S.BuildBasePathArray(Paths, BasePath);
}
CXXBasePaths Paths;
if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
<< (ClassWithFields == RD) << RD << ClassWithFields
<< Paths.front().back().Base->getType();
return DeclAccessPair();
}
return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
}
static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
ValueDecl *Src, QualType DecompType,
const CXXRecordDecl *OrigRD) {
if (S.RequireCompleteType(Src->getLocation(), DecompType,
diag::err_incomplete_type))
return true;
CXXCastPath BasePath;
DeclAccessPair BasePair =
findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
if (!RD)
return true;
QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
DecompType.getQualifiers());
auto DiagnoseBadNumberOfBindings = [&]() -> bool {
unsigned NumFields = llvm::count_if(
RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
assert(Bindings.size() != NumFields);
S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
<< DecompType << (unsigned)Bindings.size() << NumFields << NumFields
<< (NumFields < Bindings.size());
return true;
};
unsigned I = 0;
for (auto *FD : RD->fields()) {
if (FD->isUnnamedBitfield())
continue;
if (!FD->getDeclName()) {
if (RD->isLambda()) {
S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
S.Diag(RD->getLocation(), diag::note_lambda_decl);
return true;
}
if (FD->isAnonymousStructOrUnion()) {
S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
<< DecompType << FD->getType()->isUnionType();
S.Diag(FD->getLocation(), diag::note_declared_at);
return true;
}
}
if (I >= Bindings.size())
return DiagnoseBadNumberOfBindings();
auto *B = Bindings[I++];
SourceLocation Loc = B->getLocation();
S.CheckStructuredBindingMemberAccess(
Loc, const_cast<CXXRecordDecl *>(OrigRD),
DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
BasePair.getAccess(), FD->getAccess())));
ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
if (E.isInvalid())
return true;
E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
VK_LValue, &BasePath);
if (E.isInvalid())
return true;
E = S.BuildFieldReferenceExpr(E.get(), false, Loc,
CXXScopeSpec(), FD,
DeclAccessPair::make(FD, FD->getAccess()),
DeclarationNameInfo(FD->getDeclName(), Loc));
if (E.isInvalid())
return true;
Qualifiers Q = DecompType.getQualifiers();
if (FD->isMutable())
Q.removeConst();
B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
}
if (I != Bindings.size())
return DiagnoseBadNumberOfBindings();
return false;
}
void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
QualType DecompType = DD->getType();
if (DecompType->isDependentType()) {
for (auto *B : DD->bindings())
B->setType(Context.DependentTy);
return;
}
DecompType = DecompType.getNonReferenceType();
ArrayRef<BindingDecl*> Bindings = DD->bindings();
if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
DD->setInvalidDecl();
return;
}
if (auto *VT = DecompType->getAs<VectorType>()) {
if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
DD->setInvalidDecl();
return;
}
if (auto *CT = DecompType->getAs<ComplexType>()) {
if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
DD->setInvalidDecl();
return;
}
llvm::APSInt TupleSize(32);
switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
case IsTupleLike::Error:
DD->setInvalidDecl();
return;
case IsTupleLike::TupleLike:
if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
DD->setInvalidDecl();
return;
case IsTupleLike::NotTupleLike:
break;
}
CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
if (!RD || RD->isUnion()) {
Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
<< DD << !RD << DecompType;
DD->setInvalidDecl();
return;
}
if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
DD->setInvalidDecl();
}
void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
if (!getLangOpts().CXXExceptions)
return;
assert(Context.hasSameType(New->getType(), Old->getType()) &&
"Should only be called if types are otherwise the same.");
QualType NewType = New->getType();
QualType OldType = Old->getType();
if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
NewType = R->getPointeeType();
OldType = OldType->castAs<ReferenceType>()->getPointeeType();
} else if (const PointerType *P = NewType->getAs<PointerType>()) {
NewType = P->getPointeeType();
OldType = OldType->castAs<PointerType>()->getPointeeType();
} else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
NewType = M->getPointeeType();
OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
}
if (!NewType->isFunctionProtoType())
return;
if (CheckEquivalentExceptionSpec(
OldType->getAs<FunctionProtoType>(), Old->getLocation(),
NewType->getAs<FunctionProtoType>(), New->getLocation())) {
New->setInvalidDecl();
}
}
void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
unsigned NumParams = FD->getNumParams();
unsigned ParamIdx = 0;
if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
return;
if (auto *FTD = FD->getDescribedFunctionTemplate())
if (FTD->isMemberSpecialization())
return;
for (; ParamIdx < NumParams; ++ParamIdx) {
ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
if (Param->hasDefaultArg())
break;
}
for (; ParamIdx < NumParams; ++ParamIdx) {
ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
!(CurrentInstantiationScope &&
CurrentInstantiationScope->isLocalPackExpansion(Param))) {
if (Param->isInvalidDecl())
;
else if (Param->getIdentifier())
Diag(Param->getLocation(),
diag::err_param_default_argument_missing_name)
<< Param->getIdentifier();
else
Diag(Param->getLocation(),
diag::err_param_default_argument_missing);
}
}
}
template <typename... Ts>
static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
SourceLocation Loc, QualType T, unsigned DiagID,
Ts &&...DiagArgs) {
if (T->isDependentType())
return false;
switch (Kind) {
case Sema::CheckConstexprKind::Diagnose:
return SemaRef.RequireLiteralType(Loc, T, DiagID,
std::forward<Ts>(DiagArgs)...);
case Sema::CheckConstexprKind::CheckValid:
return !T->isLiteralType(SemaRef.Context);
}
llvm_unreachable("unknown CheckConstexprKind");
}
static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
const CXXDestructorDecl *DD,
Sema::CheckConstexprKind Kind) {
auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
const CXXRecordDecl *RD =
T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
if (!RD || RD->hasConstexprDestructor())
return true;
if (Kind == Sema::CheckConstexprKind::Diagnose) {
SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
<< static_cast<int>(DD->getConstexprKind()) << !FD
<< (FD ? FD->getDeclName() : DeclarationName()) << T;
SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
<< !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
}
return false;
};
const CXXRecordDecl *RD = DD->getParent();
for (const CXXBaseSpecifier &B : RD->bases())
if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
return false;
for (const FieldDecl *FD : RD->fields())
if (!Check(FD->getLocation(), FD->getType(), FD))
return false;
return true;
}
static bool CheckConstexprParameterTypes(Sema &SemaRef,
const FunctionDecl *FD,
Sema::CheckConstexprKind Kind) {
unsigned ArgIndex = 0;
const auto *FT = FD->getType()->castAs<FunctionProtoType>();
for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
e = FT->param_type_end();
i != e; ++i, ++ArgIndex) {
const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
SourceLocation ParamLoc = PD->getLocation();
if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
diag::err_constexpr_non_literal_param, ArgIndex + 1,
PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
FD->isConsteval()))
return false;
}
return true;
}
static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
Sema::CheckConstexprKind Kind) {
if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
diag::err_constexpr_non_literal_return,
FD->isConsteval()))
return false;
return true;
}
static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
switch (Tag) {
case TTK_Struct: return 0;
case TTK_Interface: return 1;
case TTK_Class: return 2;
default: llvm_unreachable("Invalid tag kind for record diagnostic!");
}
}
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
Stmt *Body,
Sema::CheckConstexprKind Kind);
bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
CheckConstexprKind Kind) {
const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
if (MD && MD->isInstance()) {
const CXXRecordDecl *RD = MD->getParent();
if (RD->getNumVBases()) {
if (Kind == CheckConstexprKind::CheckValid)
return false;
Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
<< isa<CXXConstructorDecl>(NewFD)
<< getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
for (const auto &I : RD->vbases())
Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
<< I.getSourceRange();
return false;
}
}
if (!isa<CXXConstructorDecl>(NewFD)) {
const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
if (Method && Method->isVirtual()) {
if (getLangOpts().CPlusPlus20) {
if (Kind == CheckConstexprKind::Diagnose)
Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
} else {
if (Kind == CheckConstexprKind::CheckValid)
return false;
Method = Method->getCanonicalDecl();
Diag(Method->getLocation(), diag::err_constexpr_virtual);
const CXXMethodDecl *WrittenVirtual = Method;
while (!WrittenVirtual->isVirtualAsWritten())
WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
if (WrittenVirtual != Method)
Diag(WrittenVirtual->getLocation(),
diag::note_overridden_virtual_function);
return false;
}
}
if (!CheckConstexprReturnType(*this, NewFD, Kind))
return false;
}
if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
if (Kind == CheckConstexprKind::CheckValid)
return false;
if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
return false;
}
}
if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
return false;
Stmt *Body = NewFD->getBody();
assert(Body &&
"CheckConstexprFunctionDefinition called on function with no body");
return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
}
static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
DeclStmt *DS, SourceLocation &Cxx1yLoc,
Sema::CheckConstexprKind Kind) {
for (const auto *DclIt : DS->decls()) {
switch (DclIt->getKind()) {
case Decl::StaticAssert:
case Decl::Using:
case Decl::UsingShadow:
case Decl::UsingDirective:
case Decl::UnresolvedUsingTypename:
case Decl::UnresolvedUsingValue:
case Decl::UsingEnum:
continue;
case Decl::Typedef:
case Decl::TypeAlias: {
const auto *TN = cast<TypedefNameDecl>(DclIt);
if (TN->getUnderlyingType()->isVariablyModifiedType()) {
if (Kind == Sema::CheckConstexprKind::Diagnose) {
TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
<< TL.getSourceRange() << TL.getType()
<< isa<CXXConstructorDecl>(Dcl);
}
return false;
}
continue;
}
case Decl::Enum:
case Decl::CXXRecord:
if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
if (Kind == Sema::CheckConstexprKind::Diagnose) {
SemaRef.Diag(DS->getBeginLoc(),
SemaRef.getLangOpts().CPlusPlus14
? diag::warn_cxx11_compat_constexpr_type_definition
: diag::ext_constexpr_type_definition)
<< isa<CXXConstructorDecl>(Dcl);
} else if (!SemaRef.getLangOpts().CPlusPlus14) {
return false;
}
}
continue;
case Decl::EnumConstant:
case Decl::IndirectField:
case Decl::ParmVar:
continue;
case Decl::Var:
case Decl::Decomposition: {
const auto *VD = cast<VarDecl>(DclIt);
if (VD->isThisDeclarationADefinition()) {
if (VD->isStaticLocal()) {
if (Kind == Sema::CheckConstexprKind::Diagnose) {
SemaRef.Diag(VD->getLocation(),
SemaRef.getLangOpts().CPlusPlus2b
? diag::warn_cxx20_compat_constexpr_var
: diag::ext_constexpr_static_var)
<< isa<CXXConstructorDecl>(Dcl)
<< (VD->getTLSKind() == VarDecl::TLS_Dynamic);
} else if (!SemaRef.getLangOpts().CPlusPlus2b) {
return false;
}
}
if (SemaRef.LangOpts.CPlusPlus2b) {
CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
diag::warn_cxx20_compat_constexpr_var,
isa<CXXConstructorDecl>(Dcl),
2);
} else if (CheckLiteralType(
SemaRef, Kind, VD->getLocation(), VD->getType(),
diag::err_constexpr_local_var_non_literal_type,
isa<CXXConstructorDecl>(Dcl))) {
return false;
}
if (!VD->getType()->isDependentType() &&
!VD->hasInit() && !VD->isCXXForRangeDecl()) {
if (Kind == Sema::CheckConstexprKind::Diagnose) {
SemaRef.Diag(
VD->getLocation(),
SemaRef.getLangOpts().CPlusPlus20
? diag::warn_cxx17_compat_constexpr_local_var_no_init
: diag::ext_constexpr_local_var_no_init)
<< isa<CXXConstructorDecl>(Dcl);
} else if (!SemaRef.getLangOpts().CPlusPlus20) {
return false;
}
continue;
}
}
if (Kind == Sema::CheckConstexprKind::Diagnose) {
SemaRef.Diag(VD->getLocation(),
SemaRef.getLangOpts().CPlusPlus14
? diag::warn_cxx11_compat_constexpr_local_var
: diag::ext_constexpr_local_var)
<< isa<CXXConstructorDecl>(Dcl);
} else if (!SemaRef.getLangOpts().CPlusPlus14) {
return false;
}
continue;
}
case Decl::NamespaceAlias:
case Decl::Function:
if (!Cxx1yLoc.isValid())
Cxx1yLoc = DS->getBeginLoc();
continue;
default:
if (Kind == Sema::CheckConstexprKind::Diagnose) {
SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
<< isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
}
return false;
}
}
return true;
}
static bool CheckConstexprCtorInitializer(Sema &SemaRef,
const FunctionDecl *Dcl,
FieldDecl *Field,
llvm::SmallSet<Decl*, 16> &Inits,
bool &Diagnosed,
Sema::CheckConstexprKind Kind) {
if (Kind == Sema::CheckConstexprKind::CheckValid &&
SemaRef.getLangOpts().CPlusPlus20)
return true;
if (Field->isInvalidDecl())
return true;
if (Field->isUnnamedBitfield())
return true;
if (Field->isAnonymousStructOrUnion() &&
(Field->getType()->isUnionType()
? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
: Field->getType()->getAsCXXRecordDecl()->isEmpty()))
return true;
if (!Inits.count(Field)) {
if (Kind == Sema::CheckConstexprKind::Diagnose) {
if (!Diagnosed) {
SemaRef.Diag(Dcl->getLocation(),
SemaRef.getLangOpts().CPlusPlus20
? diag::warn_cxx17_compat_constexpr_ctor_missing_init
: diag::ext_constexpr_ctor_missing_init);
Diagnosed = true;
}
SemaRef.Diag(Field->getLocation(),
diag::note_constexpr_ctor_missing_init);
} else if (!SemaRef.getLangOpts().CPlusPlus20) {
return false;
}
} else if (Field->isAnonymousStructOrUnion()) {
const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
for (auto *I : RD->fields())
if (!RD->isUnion() || Inits.count(I))
if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
Kind))
return false;
}
return true;
}
static bool
CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
SmallVectorImpl<SourceLocation> &ReturnStmts,
SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
SourceLocation &Cxx2bLoc,
Sema::CheckConstexprKind Kind) {
switch (S->getStmtClass()) {
case Stmt::NullStmtClass:
return true;
case Stmt::DeclStmtClass:
if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
return false;
return true;
case Stmt::ReturnStmtClass:
if (isa<CXXConstructorDecl>(Dcl)) {
if (!Cxx1yLoc.isValid())
Cxx1yLoc = S->getBeginLoc();
return true;
}
ReturnStmts.push_back(S->getBeginLoc());
return true;
case Stmt::AttributedStmtClass:
return CheckConstexprFunctionStmt(
SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
case Stmt::CompoundStmtClass: {
if (!Cxx1yLoc.isValid())
Cxx1yLoc = S->getBeginLoc();
CompoundStmt *CompStmt = cast<CompoundStmt>(S);
for (auto *BodyIt : CompStmt->body()) {
if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
return false;
}
return true;
}
case Stmt::IfStmtClass: {
if (!Cxx1yLoc.isValid())
Cxx1yLoc = S->getBeginLoc();
IfStmt *If = cast<IfStmt>(S);
if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
return false;
if (If->getElse() &&
!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
return false;
return true;
}
case Stmt::WhileStmtClass:
case Stmt::DoStmtClass:
case Stmt::ForStmtClass:
case Stmt::CXXForRangeStmtClass:
case Stmt::ContinueStmtClass:
if (!SemaRef.getLangOpts().CPlusPlus14)
break;
if (!Cxx1yLoc.isValid())
Cxx1yLoc = S->getBeginLoc();
for (Stmt *SubStmt : S->children()) {
if (SubStmt &&
!CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
return false;
}
return true;
case Stmt::SwitchStmtClass:
case Stmt::CaseStmtClass:
case Stmt::DefaultStmtClass:
case Stmt::BreakStmtClass:
if (!Cxx1yLoc.isValid())
Cxx1yLoc = S->getBeginLoc();
for (Stmt *SubStmt : S->children()) {
if (SubStmt &&
!CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
return false;
}
return true;
case Stmt::LabelStmtClass:
case Stmt::GotoStmtClass:
if (Cxx2bLoc.isInvalid())
Cxx2bLoc = S->getBeginLoc();
for (Stmt *SubStmt : S->children()) {
if (SubStmt &&
!CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
return false;
}
return true;
case Stmt::GCCAsmStmtClass:
case Stmt::MSAsmStmtClass:
case Stmt::CXXTryStmtClass:
if (Cxx2aLoc.isInvalid())
Cxx2aLoc = S->getBeginLoc();
for (Stmt *SubStmt : S->children()) {
if (SubStmt &&
!CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
return false;
}
return true;
case Stmt::CXXCatchStmtClass:
if (!CheckConstexprFunctionStmt(
SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
return false;
return true;
default:
if (!isa<Expr>(S))
break;
if (!Cxx1yLoc.isValid())
Cxx1yLoc = S->getBeginLoc();
return true;
}
if (Kind == Sema::CheckConstexprKind::Diagnose) {
SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
<< isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
}
return false;
}
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
Stmt *Body,
Sema::CheckConstexprKind Kind) {
SmallVector<SourceLocation, 4> ReturnStmts;
if (isa<CXXTryStmt>(Body)) {
switch (Kind) {
case Sema::CheckConstexprKind::CheckValid:
if (!SemaRef.getLangOpts().CPlusPlus20)
return false;
break;
case Sema::CheckConstexprKind::Diagnose:
SemaRef.Diag(Body->getBeginLoc(),
!SemaRef.getLangOpts().CPlusPlus20
? diag::ext_constexpr_function_try_block_cxx20
: diag::warn_cxx17_compat_constexpr_function_try_block)
<< isa<CXXConstructorDecl>(Dcl);
break;
}
}
SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
for (Stmt *SubStmt : Body->children()) {
if (SubStmt &&
!CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
return false;
}
if (Kind == Sema::CheckConstexprKind::CheckValid) {
if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2b) ||
(Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
(Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
return false;
} else if (Cxx2bLoc.isValid()) {
SemaRef.Diag(Cxx2bLoc,
SemaRef.getLangOpts().CPlusPlus2b
? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
: diag::ext_constexpr_body_invalid_stmt_cxx2b)
<< isa<CXXConstructorDecl>(Dcl);
} else if (Cxx2aLoc.isValid()) {
SemaRef.Diag(Cxx2aLoc,
SemaRef.getLangOpts().CPlusPlus20
? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
: diag::ext_constexpr_body_invalid_stmt_cxx20)
<< isa<CXXConstructorDecl>(Dcl);
} else if (Cxx1yLoc.isValid()) {
SemaRef.Diag(Cxx1yLoc,
SemaRef.getLangOpts().CPlusPlus14
? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
: diag::ext_constexpr_body_invalid_stmt)
<< isa<CXXConstructorDecl>(Dcl);
}
if (const CXXConstructorDecl *Constructor
= dyn_cast<CXXConstructorDecl>(Dcl)) {
const CXXRecordDecl *RD = Constructor->getParent();
if (RD->isUnion()) {
if (Constructor->getNumCtorInitializers() == 0 &&
RD->hasVariantMembers()) {
if (Kind == Sema::CheckConstexprKind::Diagnose) {
SemaRef.Diag(
Dcl->getLocation(),
SemaRef.getLangOpts().CPlusPlus20
? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
: diag::ext_constexpr_union_ctor_no_init);
} else if (!SemaRef.getLangOpts().CPlusPlus20) {
return false;
}
}
} else if (!Constructor->isDependentContext() &&
!Constructor->isDelegatingConstructor()) {
assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
bool AnyAnonStructUnionMembers = false;
unsigned Fields = 0;
for (CXXRecordDecl::field_iterator I = RD->field_begin(),
E = RD->field_end(); I != E; ++I, ++Fields) {
if (I->isAnonymousStructOrUnion()) {
AnyAnonStructUnionMembers = true;
break;
}
}
if (AnyAnonStructUnionMembers ||
Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
llvm::SmallSet<Decl*, 16> Inits;
for (const auto *I: Constructor->inits()) {
if (FieldDecl *FD = I->getMember())
Inits.insert(FD);
else if (IndirectFieldDecl *ID = I->getIndirectMember())
Inits.insert(ID->chain_begin(), ID->chain_end());
}
bool Diagnosed = false;
for (auto *I : RD->fields())
if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
Kind))
return false;
}
}
} else {
if (ReturnStmts.empty()) {
bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
(Dcl->getReturnType()->isVoidType() ||
Dcl->getReturnType()->isDependentType());
switch (Kind) {
case Sema::CheckConstexprKind::Diagnose:
SemaRef.Diag(Dcl->getLocation(),
OK ? diag::warn_cxx11_compat_constexpr_body_no_return
: diag::err_constexpr_body_no_return)
<< Dcl->isConsteval();
if (!OK)
return false;
break;
case Sema::CheckConstexprKind::CheckValid:
if (!SemaRef.getLangOpts().CPlusPlus14)
return false;
break;
}
} else if (ReturnStmts.size() > 1) {
switch (Kind) {
case Sema::CheckConstexprKind::Diagnose:
SemaRef.Diag(
ReturnStmts.back(),
SemaRef.getLangOpts().CPlusPlus14
? diag::warn_cxx11_compat_constexpr_body_multiple_return
: diag::ext_constexpr_body_multiple_return);
for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
SemaRef.Diag(ReturnStmts[I],
diag::note_constexpr_body_previous_return);
break;
case Sema::CheckConstexprKind::CheckValid:
if (!SemaRef.getLangOpts().CPlusPlus14)
return false;
break;
}
}
}
SmallVector<PartialDiagnosticAt, 8> Diags;
if (Kind == Sema::CheckConstexprKind::Diagnose &&
!Expr::isPotentialConstantExpr(Dcl, Diags)) {
SemaRef.Diag(Dcl->getLocation(),
diag::ext_constexpr_function_never_constant_expr)
<< isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
for (size_t I = 0, N = Diags.size(); I != N; ++I)
SemaRef.Diag(Diags[I].first, Diags[I].second);
}
return true;
}
CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
assert(getLangOpts().CPlusPlus && "No class names in C!");
if (SS && SS->isInvalid())
return nullptr;
if (SS && SS->isNotEmpty()) {
DeclContext *DC = computeDeclContext(*SS, true);
return dyn_cast_or_null<CXXRecordDecl>(DC);
}
return dyn_cast_or_null<CXXRecordDecl>(CurContext);
}
bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
const CXXScopeSpec *SS) {
CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
return CurDecl && &II == CurDecl->getIdentifier();
}
bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
assert(getLangOpts().CPlusPlus && "No class names in C!");
if (!getLangOpts().SpellChecking)
return false;
CXXRecordDecl *CurDecl;
if (SS && SS->isSet() && !SS->isInvalid()) {
DeclContext *DC = computeDeclContext(*SS, true);
CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
} else
CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
< II->getLength()) {
II = CurDecl->getIdentifier();
return true;
}
return false;
}
static bool findCircularInheritance(const CXXRecordDecl *Class,
const CXXRecordDecl *Current) {
SmallVector<const CXXRecordDecl*, 8> Queue;
Class = Class->getCanonicalDecl();
while (true) {
for (const auto &I : Current->bases()) {
CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
if (!Base)
continue;
Base = Base->getDefinition();
if (!Base)
continue;
if (Base->getCanonicalDecl() == Class)
return true;
Queue.push_back(Base);
}
if (Queue.empty())
return false;
Current = Queue.pop_back_val();
}
return false;
}
CXXBaseSpecifier *
Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
SourceRange SpecifierRange,
bool Virtual, AccessSpecifier Access,
TypeSourceInfo *TInfo,
SourceLocation EllipsisLoc) {
if (getLangOpts().HLSL && Class->getTagKind() == TTK_Class &&
Access == AS_none)
Access = AS_public;
QualType BaseType = TInfo->getType();
if (BaseType->containsErrors()) {
return nullptr;
}
if (Class->isUnion()) {
Diag(Class->getLocation(), diag::err_base_clause_on_union)
<< SpecifierRange;
return nullptr;
}
if (EllipsisLoc.isValid() &&
!TInfo->getType()->containsUnexpandedParameterPack()) {
Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
<< TInfo->getTypeLoc().getSourceRange();
EllipsisLoc = SourceLocation();
}
SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
if (BaseType->isDependentType()) {
if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
((BaseDecl = BaseDecl->getDefinition()) &&
findCircularInheritance(Class, BaseDecl))) {
Diag(BaseLoc, diag::err_circular_inheritance)
<< BaseType << Context.getTypeDeclType(Class);
if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
Diag(BaseDecl->getLocation(), diag::note_previous_decl)
<< BaseType;
return nullptr;
}
}
if (!Class->getTypeForDecl()->isDependentType())
Class->setInvalidDecl();
return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Class->getTagKind() == TTK_Class,
Access, TInfo, EllipsisLoc);
}
if (!BaseType->isRecordType()) {
Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
return nullptr;
}
if (BaseType->isUnionType()) {
Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
return nullptr;
}
if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
if (Attr *ClassAttr = getDLLAttr(Class)) {
if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
BaseType->getAsCXXRecordDecl())) {
propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
BaseLoc);
}
}
}
if (RequireCompleteType(BaseLoc, BaseType,
diag::err_incomplete_base_class, SpecifierRange)) {
Class->setInvalidDecl();
return nullptr;
}
RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
assert(BaseDecl && "Record type has no declaration");
BaseDecl = BaseDecl->getDefinition();
assert(BaseDecl && "Base type is not incomplete, but has no definition");
CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
assert(CXXBaseDecl && "Base type is not a C++ type");
const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
if ((DerivedCSA || BaseCSA) &&
(!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
<< CXXBaseDecl;
return nullptr;
}
if (CXXBaseDecl->hasFlexibleArrayMember()) {
Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
<< CXXBaseDecl->getDeclName();
return nullptr;
}
if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
<< CXXBaseDecl->getDeclName()
<< FA->isSpelledAsSealed();
Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
<< CXXBaseDecl->getDeclName() << FA->getRange();
return nullptr;
}
if (BaseDecl->isInvalidDecl())
Class->setInvalidDecl();
return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Class->getTagKind() == TTK_Class,
Access, TInfo, EllipsisLoc);
}
BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
const ParsedAttributesView &Attributes,
bool Virtual, AccessSpecifier Access,
ParsedType basetype, SourceLocation BaseLoc,
SourceLocation EllipsisLoc) {
if (!classdecl)
return true;
AdjustDeclIfTemplate(classdecl);
CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
if (!Class)
return true;
Class->setIsParsingBaseSpecifiers();
for (const ParsedAttr &AL : Attributes) {
if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
continue;
Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
? (unsigned)diag::warn_unknown_attribute_ignored
: (unsigned)diag::err_base_specifier_attribute)
<< AL << AL.getRange();
}
TypeSourceInfo *TInfo = nullptr;
GetTypeFromParser(basetype, &TInfo);
if (EllipsisLoc.isInvalid() &&
DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
UPPC_BaseType))
return true;
if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Virtual, Access, TInfo,
EllipsisLoc))
return BaseSpec;
else
Class->setInvalidDecl();
return true;
}
typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
static void
NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
const QualType &Type)
{
if (auto Rec = Type->getAs<RecordType>()) {
auto Decl = Rec->getAsCXXRecordDecl();
for (const auto &BaseSpec : Decl->bases()) {
QualType Base = Context.getCanonicalType(BaseSpec.getType())
.getUnqualifiedType();
if (Set.insert(Base).second)
NoteIndirectBases(Context, Set, Base);
}
}
}
bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
MutableArrayRef<CXXBaseSpecifier *> Bases) {
if (Bases.empty())
return false;
std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
IndirectBaseSet IndirectBaseTypes;
unsigned NumGoodBases = 0;
bool Invalid = false;
for (unsigned idx = 0; idx < Bases.size(); ++idx) {
QualType NewBaseType
= Context.getCanonicalType(Bases[idx]->getType());
NewBaseType = NewBaseType.getLocalUnqualifiedType();
CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
if (KnownBase) {
Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
<< KnownBase->getType() << Bases[idx]->getSourceRange();
Context.Deallocate(Bases[idx]);
Invalid = true;
} else {
KnownBase = Bases[idx];
Bases[NumGoodBases++] = Bases[idx];
if (NewBaseType->isDependentType())
continue;
if (Bases.size() > 1)
NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
if (Class->isInterface() &&
(!RD->isInterfaceLike() ||
KnownBase->getAccessSpecifier() != AS_public)) {
Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
<< getRecordDiagFromTagKind(RD->getTagKind()) << RD
<< RD->getSourceRange();
Invalid = true;
}
if (RD->hasAttr<WeakAttr>())
Class->addAttr(WeakAttr::CreateImplicit(Context));
}
}
}
Class->setBases(Bases.data(), NumGoodBases);
for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
QualType BaseType = Bases[idx]->getType();
if (BaseType->isDependentType())
continue;
CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
.getUnqualifiedType();
if (IndirectBaseTypes.count(CanonicalBase)) {
CXXBasePaths Paths(true, true,
true);
bool found
= Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
assert(found);
(void)found;
if (Paths.isAmbiguous(CanonicalBase))
Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
<< BaseType << getAmbiguousPathsDisplayString(Paths)
<< Bases[idx]->getSourceRange();
else
assert(Bases[idx]->isVirtual());
}
Context.Deallocate(Bases[idx]);
}
return Invalid;
}
void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
MutableArrayRef<CXXBaseSpecifier *> Bases) {
if (!ClassDecl || Bases.empty())
return;
AdjustDeclIfTemplate(ClassDecl);
AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
}
bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
if (!getLangOpts().CPlusPlus)
return false;
CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
if (!DerivedRD)
return false;
CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
if (!BaseRD)
return false;
if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
return false;
if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
return false;
return DerivedRD->isDerivedFrom(BaseRD);
}
bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
CXXBasePaths &Paths) {
if (!getLangOpts().CPlusPlus)
return false;
CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
if (!DerivedRD)
return false;
CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
if (!BaseRD)
return false;
if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
return false;
return DerivedRD->isDerivedFrom(BaseRD, Paths);
}
static void BuildBasePathArray(const CXXBasePath &Path,
CXXCastPath &BasePathArray) {
unsigned Start = 0;
for (unsigned I = Path.size(); I != 0; --I) {
if (Path[I - 1].Base->isVirtual()) {
Start = I - 1;
break;
}
}
for (unsigned I = Start, E = Path.size(); I != E; ++I)
BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
}
void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
CXXCastPath &BasePathArray) {
assert(BasePathArray.empty() && "Base path array must be empty!");
assert(Paths.isRecordingPaths() && "Must record paths!");
return ::BuildBasePathArray(Paths.front(), BasePathArray);
}
bool
Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
unsigned InaccessibleBaseID,
unsigned AmbiguousBaseConvID,
SourceLocation Loc, SourceRange Range,
DeclarationName Name,
CXXCastPath *BasePath,
bool IgnoreAccess) {
CXXBasePaths Paths(true, true,
false);
bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
if (!DerivationOkay)
return true;
const CXXBasePath *Path = nullptr;
if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
Path = &Paths.front();
if (!Path && getLangOpts().MSVCCompat) {
for (const CXXBasePath &PossiblePath : Paths) {
if (PossiblePath.size() == 1) {
Path = &PossiblePath;
if (AmbiguousBaseConvID)
Diag(Loc, diag::ext_ms_ambiguous_direct_base)
<< Base << Derived << Range;
break;
}
}
}
if (Path) {
if (!IgnoreAccess) {
switch (
CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
case AR_inaccessible:
return true;
case AR_accessible:
case AR_dependent:
case AR_delayed:
break;
}
}
if (BasePath)
::BuildBasePathArray(*Path, *BasePath);
return false;
}
if (AmbiguousBaseConvID) {
Paths.clear();
Paths.setRecordingPaths(true);
bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
assert(StillOkay && "Can only be used with a derived-to-base conversion");
(void)StillOkay;
std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
Diag(Loc, AmbiguousBaseConvID)
<< Derived << Base << PathDisplayStr << Range << Name;
}
return true;
}
bool
Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
SourceLocation Loc, SourceRange Range,
CXXCastPath *BasePath,
bool IgnoreAccess) {
return CheckDerivedToBaseConversion(
Derived, Base, diag::err_upcast_to_inaccessible_base,
diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
BasePath, IgnoreAccess);
}
std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
std::string PathDisplayStr;
std::set<unsigned> DisplayedPaths;
for (CXXBasePaths::paths_iterator Path = Paths.begin();
Path != Paths.end(); ++Path) {
if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
PathDisplayStr += "\n ";
PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
for (CXXBasePath::const_iterator Element = Path->begin();
Element != Path->end(); ++Element)
PathDisplayStr += " -> " + Element->Base->getType().getAsString();
}
}
return PathDisplayStr;
}
bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
SourceLocation ColonLoc,
const ParsedAttributesView &Attrs) {
assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
ASLoc, ColonLoc);
CurContext->addHiddenDecl(ASDecl);
return ProcessAccessDeclAttributeList(ASDecl, Attrs);
}
void Sema::CheckOverrideControl(NamedDecl *D) {
if (D->isInvalidDecl())
return;
if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
return;
CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
if (MD && MD->isInstance() &&
(MD->getParent()->hasAnyDependentBases() ||
MD->getType()->isDependentType()))
return;
if (MD && !MD->isVirtual()) {
SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
FindHiddenVirtualMethods(MD, OverloadedMethods);
if (!OverloadedMethods.empty()) {
if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
Diag(OA->getLocation(),
diag::override_keyword_hides_virtual_member_function)
<< "override" << (OverloadedMethods.size() > 1);
} else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Diag(FA->getLocation(),
diag::override_keyword_hides_virtual_member_function)
<< (FA->isSpelledAsSealed() ? "sealed" : "final")
<< (OverloadedMethods.size() > 1);
}
NoteHiddenVirtualMethods(MD, OverloadedMethods);
MD->setInvalidDecl();
return;
}
}
if (!MD || !MD->isVirtual()) {
if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
Diag(OA->getLocation(),
diag::override_keyword_only_allowed_on_virtual_member_functions)
<< "override" << FixItHint::CreateRemoval(OA->getLocation());
D->dropAttr<OverrideAttr>();
}
if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Diag(FA->getLocation(),
diag::override_keyword_only_allowed_on_virtual_member_functions)
<< (FA->isSpelledAsSealed() ? "sealed" : "final")
<< FixItHint::CreateRemoval(FA->getLocation());
D->dropAttr<FinalAttr>();
}
return;
}
bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
<< MD->getDeclName();
}
void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
return;
CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
return;
SourceLocation Loc = MD->getLocation();
SourceLocation SpellingLoc = Loc;
if (getSourceManager().isMacroArgExpansion(Loc))
SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
return;
if (MD->size_overridden_methods() > 0) {
auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
unsigned DiagID =
Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
? DiagInconsistent
: DiagSuggest;
Diag(MD->getLocation(), DiagID) << MD->getDeclName();
const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
};
if (isa<CXXDestructorDecl>(MD))
EmitDiag(
diag::warn_inconsistent_destructor_marked_not_override_overriding,
diag::warn_suggest_destructor_marked_not_override_overriding);
else
EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
diag::warn_suggest_function_marked_not_override_overriding);
}
}
bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
const CXXMethodDecl *Old) {
FinalAttr *FA = Old->getAttr<FinalAttr>();
if (!FA)
return false;
Diag(New->getLocation(), diag::err_final_function_overridden)
<< New->getDeclName()
<< FA->isSpelledAsSealed();
Diag(Old->getLocation(), diag::note_overridden_virtual_function);
return true;
}
static bool InitializationHasSideEffects(const FieldDecl &FD) {
const Type *T = FD.getType()->getBaseElementTypeUnsafe();
if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
return !RD->isCompleteDefinition() ||
!RD->hasTrivialDefaultConstructor() ||
!RD->hasTrivialDestructor();
return false;
}
static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
ParsedAttributesView::const_iterator Itr =
llvm::find_if(list, [](const ParsedAttr &AL) {
return AL.isDeclspecPropertyAttribute();
});
if (Itr != list.end())
return &*Itr;
return nullptr;
}
void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
DeclarationName FieldName,
const CXXRecordDecl *RD,
bool DeclIsField) {
if (Diags.isIgnored(diag::warn_shadow_field, Loc))
return;
std::map<CXXRecordDecl*, NamedDecl*> Bases;
auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
CXXBasePath &Path) {
const auto Base = Specifier->getType()->getAsCXXRecordDecl();
if (Bases.find(Base) != Bases.end())
return true;
for (const auto Field : Base->lookup(FieldName)) {
if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
Field->getAccess() != AS_private) {
assert(Field->getAccess() != AS_none);
assert(Bases.find(Base) == Bases.end());
Bases[Base] = Field;
return true;
}
}
return false;
};
CXXBasePaths Paths(true, true,
true);
if (!RD->lookupInBases(FieldShadowed, Paths))
return;
for (const auto &P : Paths) {
auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
auto It = Bases.find(Base);
if (It == Bases.end())
continue;
auto BaseField = It->second;
assert(BaseField->getAccess() != AS_private);
if (AS_none !=
CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
Diag(Loc, diag::warn_shadow_field)
<< FieldName << RD << Base << DeclIsField;
Diag(BaseField->getLocation(), diag::note_shadow_field);
Bases.erase(It);
}
}
}
NamedDecl *
Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
MultiTemplateParamsArg TemplateParameterLists,
Expr *BW, const VirtSpecifiers &VS,
InClassInitStyle InitStyle) {
const DeclSpec &DS = D.getDeclSpec();
DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
DeclarationName Name = NameInfo.getName();
SourceLocation Loc = NameInfo.getLoc();
if (Loc.isInvalid())
Loc = D.getBeginLoc();
Expr *BitWidth = static_cast<Expr*>(BW);
assert(isa<CXXRecordDecl>(CurContext));
assert(!DS.isFriendSpecified());
bool isFunc = D.isDeclarationOfFunction();
const ParsedAttr *MSPropertyAttr =
getMSPropertyAttr(D.getDeclSpec().getAttributes());
if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
unsigned InvalidDecl;
bool ShowDeclName = true;
if (!isFunc &&
(DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
InvalidDecl = 0;
else if (!isFunc)
InvalidDecl = 1;
else if (AS != AS_public)
InvalidDecl = 2;
else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
InvalidDecl = 3;
else switch (Name.getNameKind()) {
case DeclarationName::CXXConstructorName:
InvalidDecl = 4;
ShowDeclName = false;
break;
case DeclarationName::CXXDestructorName:
InvalidDecl = 5;
ShowDeclName = false;
break;
case DeclarationName::CXXOperatorName:
case DeclarationName::CXXConversionFunctionName:
InvalidDecl = 6;
break;
default:
InvalidDecl = 0;
break;
}
if (InvalidDecl) {
if (ShowDeclName)
Diag(Loc, diag::err_invalid_member_in_interface)
<< (InvalidDecl-1) << Name;
else
Diag(Loc, diag::err_invalid_member_in_interface)
<< (InvalidDecl-1) << "";
return nullptr;
}
}
switch (DS.getStorageClassSpec()) {
case DeclSpec::SCS_unspecified:
case DeclSpec::SCS_typedef:
case DeclSpec::SCS_static:
break;
case DeclSpec::SCS_mutable:
if (isFunc) {
Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
D.getMutableDeclSpec().ClearStorageClassSpecs();
}
break;
default:
Diag(DS.getStorageClassSpecLoc(),
diag::err_storageclass_invalid_for_member);
D.getMutableDeclSpec().ClearStorageClassSpecs();
break;
}
bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
!isFunc);
if (DS.hasConstexprSpecifier() && isInstField) {
SemaDiagnosticBuilder B =
Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
if (InitStyle == ICIS_NoInit) {
B << 0 << 0;
if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
B << FixItHint::CreateRemoval(ConstexprLoc);
else {
B << FixItHint::CreateReplacement(ConstexprLoc, "const");
D.getMutableDeclSpec().ClearConstexprSpec();
const char *PrevSpec;
unsigned DiagID;
bool Failed = D.getMutableDeclSpec().SetTypeQual(
DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
(void)Failed;
assert(!Failed && "Making a constexpr member const shouldn't fail");
}
} else {
B << 1;
const char *PrevSpec;
unsigned DiagID;
if (D.getMutableDeclSpec().SetStorageClassSpec(
*this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
Context.getPrintingPolicy())) {
assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
"This is the only DeclSpec that should fail to be applied");
B << 1;
} else {
B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
isInstField = false;
}
}
}
NamedDecl *Member;
if (isInstField) {
CXXScopeSpec &SS = D.getCXXScopeSpec();
if (!Name.isIdentifier()) {
Diag(Loc, diag::err_bad_variable_name)
<< Name;
return nullptr;
}
IdentifierInfo *II = Name.getAsIdentifierInfo();
if (TemplateParameterLists.size()) {
TemplateParameterList* TemplateParams = TemplateParameterLists[0];
if (TemplateParams->size()) {
Diag(D.getIdentifierLoc(), diag::err_template_member)
<< II
<< SourceRange(TemplateParams->getTemplateLoc(),
TemplateParams->getRAngleLoc());
} else {
Diag(TemplateParams->getTemplateLoc(),
diag::err_template_member_noparams)
<< II
<< SourceRange(TemplateParams->getTemplateLoc(),
TemplateParams->getRAngleLoc());
}
return nullptr;
}
if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
<< II
<< SourceRange(D.getName().TemplateId->LAngleLoc,
D.getName().TemplateId->RAngleLoc)
<< D.getName().TemplateId->LAngleLoc;
D.SetIdentifier(II, Loc);
}
if (SS.isSet() && !SS.isInvalid()) {
if (DeclContext *DC = computeDeclContext(SS, false))
diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
D.getName().getKind() ==
UnqualifiedIdKind::IK_TemplateId);
else
Diag(D.getIdentifierLoc(), diag::err_member_qualification)
<< Name << SS.getRange();
SS.clear();
}
if (MSPropertyAttr) {
Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
BitWidth, InitStyle, AS, *MSPropertyAttr);
if (!Member)
return nullptr;
isInstField = false;
} else {
Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
BitWidth, InitStyle, AS);
if (!Member)
return nullptr;
}
CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
} else {
Member = HandleDeclarator(S, D, TemplateParameterLists);
if (!Member)
return nullptr;
if (BitWidth) {
if (Member->isInvalidDecl()) {
} else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Diag(Loc, diag::err_static_not_bitfield)
<< Name << BitWidth->getSourceRange();
} else if (isa<TypedefDecl>(Member)) {
Diag(Loc, diag::err_typedef_not_bitfield)
<< Name << BitWidth->getSourceRange();
} else {
Diag(Loc, diag::err_not_integral_type_bitfield)
<< Name << cast<ValueDecl>(Member)->getType()
<< BitWidth->getSourceRange();
}
BitWidth = nullptr;
Member->setInvalidDecl();
}
NamedDecl *NonTemplateMember = Member;
if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
NonTemplateMember = FunTmpl->getTemplatedDecl();
else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
NonTemplateMember = VarTmpl->getTemplatedDecl();
Member->setAccess(AS);
if (NonTemplateMember != Member)
NonTemplateMember->setAccess(AS);
if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
auto *TD = DG->getDeducedTemplate();
if (AS != TD->getAccess() &&
TD->getDeclContext()->getRedeclContext()->Equals(
DG->getDeclContext()->getRedeclContext())) {
Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
<< TD->getAccess();
const AccessSpecDecl *LastAccessSpec = nullptr;
for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
LastAccessSpec = AccessSpec;
}
assert(LastAccessSpec && "differing access with no access specifier");
Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
<< AS;
}
}
}
if (VS.isOverrideSpecified())
Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
AttributeCommonInfo::AS_Keyword));
if (VS.isFinalSpecified())
Member->addAttr(FinalAttr::Create(
Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
if (VS.getLastLocation().isValid()) {
if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
MD->setRangeEnd(VS.getLastLocation());
}
CheckOverrideControl(Member);
assert((Name || isInstField) && "No identifier for non-field ?");
if (isInstField) {
FieldDecl *FD = cast<FieldDecl>(Member);
FieldCollector->Add(FD);
if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
if (!FD->isImplicit() && FD->getDeclName() &&
FD->getAccess() == AS_private &&
!FD->hasAttr<UnusedAttr>() &&
!FD->getParent()->isDependentContext() &&
!InitializationHasSideEffects(*FD))
UnusedPrivateFields.insert(FD);
}
}
return Member;
}
namespace {
class UninitializedFieldVisitor
: public EvaluatedExprVisitor<UninitializedFieldVisitor> {
Sema &S;
llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
llvm::SmallPtrSetImpl<QualType> &BaseClasses;
llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
const CXXConstructorDecl *Constructor;
bool InitList;
FieldDecl *InitListFieldDecl;
llvm::SmallVector<unsigned, 4> InitFieldIndex;
public:
typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
UninitializedFieldVisitor(Sema &S,
llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
llvm::SmallPtrSetImpl<QualType> &BaseClasses)
: Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
bool IsInitListMemberExprInitialized(MemberExpr *ME,
bool CheckReferenceOnly) {
llvm::SmallVector<FieldDecl*, 4> Fields;
bool ReferenceField = false;
while (ME) {
FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
if (!FD)
return false;
Fields.push_back(FD);
if (FD->getType()->isReferenceType())
ReferenceField = true;
ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
}
if (CheckReferenceOnly && !ReferenceField)
return true;
llvm::SmallVector<unsigned, 4> UsedFieldIndex;
for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
UsedFieldIndex.push_back(FD->getFieldIndex());
for (auto UsedIter = UsedFieldIndex.begin(),
UsedEnd = UsedFieldIndex.end(),
OrigIter = InitFieldIndex.begin(),
OrigEnd = InitFieldIndex.end();
UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
if (*UsedIter < *OrigIter)
return true;
if (*UsedIter > *OrigIter)
break;
}
return false;
}
void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
bool AddressOf) {
if (isa<EnumConstantDecl>(ME->getMemberDecl()))
return;
MemberExpr *FieldME = ME;
bool AllPODFields = FieldME->getType().isPODType(S.Context);
Expr *Base = ME;
while (MemberExpr *SubME =
dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
if (isa<VarDecl>(SubME->getMemberDecl()))
return;
if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
if (!FD->isAnonymousStructOrUnion())
FieldME = SubME;
if (!FieldME->getType().isPODType(S.Context))
AllPODFields = false;
Base = SubME->getBase();
}
if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
Visit(Base);
return;
}
if (AddressOf && AllPODFields)
return;
ValueDecl* FoundVD = FieldME->getMemberDecl();
if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
}
if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
QualType T = BaseCast->getType();
if (T->isPointerType() &&
BaseClasses.count(T->getPointeeType())) {
S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
<< T->getPointeeType() << FoundVD;
}
}
}
if (!Decls.count(FoundVD))
return;
const bool IsReference = FoundVD->getType()->isReferenceType();
if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
return;
}
} else {
if (CheckReferenceOnly && !IsReference)
return;
}
unsigned diag = IsReference
? diag::warn_reference_field_is_uninit
: diag::warn_field_is_uninit;
S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
if (Constructor)
S.Diag(Constructor->getLocation(),
diag::note_uninit_in_this_constructor)
<< (Constructor->isDefaultConstructor() && Constructor->isImplicit());
}
void HandleValue(Expr *E, bool AddressOf) {
E = E->IgnoreParens();
if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
HandleMemberExpr(ME, false ,
AddressOf );
return;
}
if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Visit(CO->getCond());
HandleValue(CO->getTrueExpr(), AddressOf);
HandleValue(CO->getFalseExpr(), AddressOf);
return;
}
if (BinaryConditionalOperator *BCO =
dyn_cast<BinaryConditionalOperator>(E)) {
Visit(BCO->getCond());
HandleValue(BCO->getFalseExpr(), AddressOf);
return;
}
if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
HandleValue(OVE->getSourceExpr(), AddressOf);
return;
}
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
switch (BO->getOpcode()) {
default:
break;
case(BO_PtrMemD):
case(BO_PtrMemI):
HandleValue(BO->getLHS(), AddressOf);
Visit(BO->getRHS());
return;
case(BO_Comma):
Visit(BO->getLHS());
HandleValue(BO->getRHS(), AddressOf);
return;
}
}
Visit(E);
}
void CheckInitListExpr(InitListExpr *ILE) {
InitFieldIndex.push_back(0);
for (auto Child : ILE->children()) {
if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
CheckInitListExpr(SubList);
} else {
Visit(Child);
}
++InitFieldIndex.back();
}
InitFieldIndex.pop_back();
}
void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
FieldDecl *Field, const Type *BaseClass) {
for (ValueDecl* VD : DeclsToRemove)
Decls.erase(VD);
DeclsToRemove.clear();
Constructor = FieldConstructor;
InitListExpr *ILE = dyn_cast<InitListExpr>(E);
if (ILE && Field) {
InitList = true;
InitListFieldDecl = Field;
InitFieldIndex.clear();
CheckInitListExpr(ILE);
} else {
InitList = false;
Visit(E);
}
if (Field)
Decls.erase(Field);
if (BaseClass)
BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
}
void VisitMemberExpr(MemberExpr *ME) {
HandleMemberExpr(ME, true , false );
}
void VisitImplicitCastExpr(ImplicitCastExpr *E) {
if (E->getCastKind() == CK_LValueToRValue) {
HandleValue(E->getSubExpr(), false );
return;
}
Inherited::VisitImplicitCastExpr(E);
}
void VisitCXXConstructExpr(CXXConstructExpr *E) {
if (E->getConstructor()->isCopyConstructor()) {
Expr *ArgExpr = E->getArg(0);
if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
if (ILE->getNumInits() == 1)
ArgExpr = ILE->getInit(0);
if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
if (ICE->getCastKind() == CK_NoOp)
ArgExpr = ICE->getSubExpr();
HandleValue(ArgExpr, false );
return;
}
Inherited::VisitCXXConstructExpr(E);
}
void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
Expr *Callee = E->getCallee();
if (isa<MemberExpr>(Callee)) {
HandleValue(Callee, false );
for (auto Arg : E->arguments())
Visit(Arg);
return;
}
Inherited::VisitCXXMemberCallExpr(E);
}
void VisitCallExpr(CallExpr *E) {
if (E->isCallToStdMove()) {
HandleValue(E->getArg(0), false);
return;
}
Inherited::VisitCallExpr(E);
}
void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
Expr *Callee = E->getCallee();
if (isa<UnresolvedLookupExpr>(Callee))
return Inherited::VisitCXXOperatorCallExpr(E);
Visit(Callee);
for (auto Arg : E->arguments())
HandleValue(Arg->IgnoreParenImpCasts(), false );
}
void VisitBinaryOperator(BinaryOperator *E) {
if (E->getOpcode() == BO_Assign)
if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
if (!FD->getType()->isReferenceType())
DeclsToRemove.push_back(FD);
if (E->isCompoundAssignmentOp()) {
HandleValue(E->getLHS(), false );
Visit(E->getRHS());
return;
}
Inherited::VisitBinaryOperator(E);
}
void VisitUnaryOperator(UnaryOperator *E) {
if (E->isIncrementDecrementOp()) {
HandleValue(E->getSubExpr(), false );
return;
}
if (E->getOpcode() == UO_AddrOf) {
if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
HandleValue(ME->getBase(), true );
return;
}
}
Inherited::VisitUnaryOperator(E);
}
};
static void DiagnoseUninitializedFields(
Sema &SemaRef, const CXXConstructorDecl *Constructor) {
if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
Constructor->getLocation())) {
return;
}
if (Constructor->isInvalidDecl())
return;
const CXXRecordDecl *RD = Constructor->getParent();
if (RD->isDependentContext())
return;
llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
for (auto *I : RD->decls()) {
if (auto *FD = dyn_cast<FieldDecl>(I)) {
UninitializedFields.insert(FD);
} else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
UninitializedFields.insert(IFD->getAnonField());
}
}
llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
for (auto I : RD->bases())
UninitializedBaseClasses.insert(I.getType().getCanonicalType());
if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
return;
UninitializedFieldVisitor UninitializedChecker(SemaRef,
UninitializedFields,
UninitializedBaseClasses);
for (const auto *FieldInit : Constructor->inits()) {
if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
break;
Expr *InitExpr = FieldInit->getInit();
if (!InitExpr)
continue;
if (CXXDefaultInitExpr *Default =
dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
InitExpr = Default->getExpr();
if (!InitExpr)
continue;
UninitializedChecker.CheckInitializer(InitExpr, Constructor,
FieldInit->getAnyMember(),
FieldInit->getBaseClass());
} else {
UninitializedChecker.CheckInitializer(InitExpr, nullptr,
FieldInit->getAnyMember(),
FieldInit->getBaseClass());
}
}
}
}
void Sema::ActOnStartCXXInClassMemberInitializer() {
PushFunctionScope();
}
void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
if (!D.isFunctionDeclarator())
return;
auto &FTI = D.getFunctionTypeInfo();
if (!FTI.Params)
return;
for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
FTI.NumParams)) {
auto *ParamDecl = cast<NamedDecl>(Param.Param);
if (ParamDecl->getDeclName())
PushOnScopeChains(ParamDecl, S, false);
}
}
ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
return ActOnRequiresClause(ConstraintExpr);
}
ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
if (ConstraintExpr.isInvalid())
return ExprError();
ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
if (ConstraintExpr.isInvalid())
return ExprError();
if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
UPPC_RequiresClause))
return ExprError();
return ConstraintExpr;
}
void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
SourceLocation InitLoc,
Expr *InitExpr) {
PopFunctionScopeInfo(nullptr, D);
FieldDecl *FD = dyn_cast<FieldDecl>(D);
assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
"must set init style when field is created");
if (!InitExpr) {
D->setInvalidDecl();
if (FD)
FD->removeInClassInitializer();
return;
}
if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
FD->setInvalidDecl();
FD->removeInClassInitializer();
return;
}
ExprResult Init = InitExpr;
if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
InitializedEntity Entity =
InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
InitializationKind Kind =
FD->getInClassInitStyle() == ICIS_ListInit
? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
InitExpr->getBeginLoc(),
InitExpr->getEndLoc())
: InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
InitializationSequence Seq(*this, Entity, Kind, InitExpr);
Init = Seq.Perform(*this, Entity, Kind, InitExpr);
if (Init.isInvalid()) {
FD->setInvalidDecl();
return;
}
}
Init = ActOnFinishFullExpr(Init.get(), InitLoc, false);
if (Init.isInvalid()) {
FD->setInvalidDecl();
return;
}
InitExpr = Init.get();
FD->setInClassInitializer(InitExpr);
}
static bool FindBaseInitializer(Sema &SemaRef,
CXXRecordDecl *ClassDecl,
QualType BaseType,
const CXXBaseSpecifier *&DirectBaseSpec,
const CXXBaseSpecifier *&VirtualBaseSpec) {
DirectBaseSpec = nullptr;
for (const auto &Base : ClassDecl->bases()) {
if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
DirectBaseSpec = &Base;
break;
}
}
VirtualBaseSpec = nullptr;
if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
CXXBasePaths Paths(true, true,
false);
if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
SemaRef.Context.getTypeDeclType(ClassDecl),
BaseType, Paths)) {
for (CXXBasePaths::paths_iterator Path = Paths.begin();
Path != Paths.end(); ++Path) {
if (Path->back().Base->isVirtual()) {
VirtualBaseSpec = Path->back().Base;
break;
}
}
}
}
return DirectBaseSpec || VirtualBaseSpec;
}
MemInitResult
Sema::ActOnMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
Expr *InitList,
SourceLocation EllipsisLoc) {
return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
DS, IdLoc, InitList,
EllipsisLoc);
}
MemInitResult
Sema::ActOnMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
SourceLocation LParenLoc,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
SourceLocation EllipsisLoc) {
Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
DS, IdLoc, List, EllipsisLoc);
}
namespace {
class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
public:
explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
: ClassDecl(ClassDecl) {}
bool ValidateCandidate(const TypoCorrection &candidate) override {
if (NamedDecl *ND = candidate.getCorrectionDecl()) {
if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
return isa<TypeDecl>(ND);
}
return false;
}
std::unique_ptr<CorrectionCandidateCallback> clone() override {
return std::make_unique<MemInitializerValidatorCCC>(*this);
}
private:
CXXRecordDecl *ClassDecl;
};
}
ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
CXXScopeSpec &SS,
ParsedType TemplateTypeTy,
IdentifierInfo *MemberOrBase) {
if (SS.getScopeRep() || TemplateTypeTy)
return nullptr;
for (auto *D : ClassDecl->lookup(MemberOrBase))
if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
return cast<ValueDecl>(D);
return nullptr;
}
MemInitResult
Sema::BuildMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
Expr *Init,
SourceLocation EllipsisLoc) {
ExprResult Res = CorrectDelayedTyposInExpr(Init, nullptr,
true);
if (!Res.isUsable())
return true;
Init = Res.get();
if (!ConstructorD)
return true;
AdjustDeclIfTemplate(ConstructorD);
CXXConstructorDecl *Constructor
= dyn_cast<CXXConstructorDecl>(ConstructorD);
if (!Constructor) {
return true;
}
CXXRecordDecl *ClassDecl = Constructor->getParent();
if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
if (EllipsisLoc.isValid())
Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
<< MemberOrBase
<< SourceRange(IdLoc, Init->getSourceRange().getEnd());
return BuildMemberInitializer(Member, Init, IdLoc);
}
QualType BaseType;
TypeSourceInfo *TInfo = nullptr;
if (TemplateTypeTy) {
BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
if (BaseType.isNull())
return true;
} else if (DS.getTypeSpecType() == TST_decltype) {
BaseType = BuildDecltypeType(DS.getRepAsExpr());
} else if (DS.getTypeSpecType() == TST_decltype_auto) {
Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
return true;
} else {
LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
LookupParsedName(R, S, &SS);
TypeDecl *TyD = R.getAsSingle<TypeDecl>();
if (!TyD) {
if (R.isAmbiguous()) return true;
R.suppressDiagnostics();
if (SS.isSet() && isDependentScopeSpecifier(SS)) {
bool NotUnknownSpecialization = false;
DeclContext *DC = computeDeclContext(SS, false);
if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
NotUnknownSpecialization = !Record->hasAnyDependentBases();
if (!NotUnknownSpecialization) {
BaseType = CheckTypenameType(ETK_None, SourceLocation(),
SS.getWithLocInContext(Context),
*MemberOrBase, IdLoc);
if (BaseType.isNull())
return true;
TInfo = Context.CreateTypeSourceInfo(BaseType);
DependentNameTypeLoc TL =
TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
if (!TL.isNull()) {
TL.setNameLoc(IdLoc);
TL.setElaboratedKeywordLoc(SourceLocation());
TL.setQualifierLoc(SS.getWithLocInContext(Context));
}
R.clear();
R.setLookupName(MemberOrBase);
}
}
if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>();
if (UnqualifiedBase) {
Diag(IdLoc, diag::ext_unqualified_base_class)
<< SourceRange(IdLoc, Init->getSourceRange().getEnd());
BaseType = UnqualifiedBase->getInjectedClassNameSpecialization();
}
}
TypoCorrection Corr;
MemInitializerValidatorCCC CCC(ClassDecl);
if (R.empty() && BaseType.isNull() &&
(Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
CCC, CTK_ErrorRecovery, ClassDecl))) {
if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
diagnoseTypo(Corr,
PDiag(diag::err_mem_init_not_member_or_class_suggest)
<< MemberOrBase << true);
return BuildMemberInitializer(Member, Init, IdLoc);
} else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
const CXXBaseSpecifier *DirectBaseSpec;
const CXXBaseSpecifier *VirtualBaseSpec;
if (FindBaseInitializer(*this, ClassDecl,
Context.getTypeDeclType(Type),
DirectBaseSpec, VirtualBaseSpec)) {
diagnoseTypo(Corr,
PDiag(diag::err_mem_init_not_member_or_class_suggest)
<< MemberOrBase << false,
PDiag() );
const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
: VirtualBaseSpec;
Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
<< BaseSpec->getType() << BaseSpec->getSourceRange();
TyD = Type;
}
}
}
if (!TyD && BaseType.isNull()) {
Diag(IdLoc, diag::err_mem_init_not_member_or_class)
<< MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
return true;
}
}
if (BaseType.isNull()) {
BaseType = Context.getTypeDeclType(TyD);
MarkAnyDeclReferenced(TyD->getLocation(), TyD, false);
if (SS.isSet()) {
BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
BaseType);
TInfo = Context.CreateTypeSourceInfo(BaseType);
ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
TL.setElaboratedKeywordLoc(SourceLocation());
TL.setQualifierLoc(SS.getWithLocInContext(Context));
}
}
}
if (!TInfo)
TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
}
MemInitResult
Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
SourceLocation IdLoc) {
FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
assert((DirectMember || IndirectMember) &&
"Member must be a FieldDecl or IndirectFieldDecl");
if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
return true;
if (Member->isInvalidDecl())
return true;
MultiExprArg Args;
if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
} else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
} else {
Args = Init;
}
SourceRange InitRange = Init->getSourceRange();
if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
DiscardCleanupsInEvaluationContext();
} else {
bool InitList = false;
if (isa<InitListExpr>(Init)) {
InitList = true;
Args = Init;
}
InitializedEntity MemberEntity =
DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
: InitializedEntity::InitializeMember(IndirectMember,
nullptr);
InitializationKind Kind =
InitList ? InitializationKind::CreateDirectList(
IdLoc, Init->getBeginLoc(), Init->getEndLoc())
: InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
InitRange.getEnd());
InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
nullptr);
if (!MemberInit.isInvalid()) {
MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
false);
}
if (MemberInit.isInvalid()) {
Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
Member->getType())
.get();
if (!Init)
return true;
} else {
Init = MemberInit.get();
}
}
if (DirectMember) {
return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
InitRange.getBegin(), Init,
InitRange.getEnd());
} else {
return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
InitRange.getBegin(), Init,
InitRange.getEnd());
}
}
MemInitResult
Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
CXXRecordDecl *ClassDecl) {
SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
if (!LangOpts.CPlusPlus11)
return Diag(NameLoc, diag::err_delegating_ctor)
<< TInfo->getTypeLoc().getLocalSourceRange();
Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
bool InitList = true;
MultiExprArg Args = Init;
if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
InitList = false;
Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
}
SourceRange InitRange = Init->getSourceRange();
InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
QualType(ClassDecl->getTypeForDecl(), 0));
InitializationKind Kind =
InitList ? InitializationKind::CreateDirectList(
NameLoc, Init->getBeginLoc(), Init->getEndLoc())
: InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
InitRange.getEnd());
InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Args, nullptr);
if (!DelegationInit.isInvalid()) {
assert((DelegationInit.get()->containsErrors() ||
cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
"Delegating constructor with no target?");
DelegationInit = ActOnFinishFullExpr(
DelegationInit.get(), InitRange.getBegin(), false);
}
if (DelegationInit.isInvalid()) {
DelegationInit =
CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
QualType(ClassDecl->getTypeForDecl(), 0));
if (DelegationInit.isInvalid())
return true;
} else {
if (CurContext->isDependentContext())
DelegationInit = Init;
}
return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
DelegationInit.getAs<Expr>(),
InitRange.getEnd());
}
MemInitResult
Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Expr *Init, CXXRecordDecl *ClassDecl,
SourceLocation EllipsisLoc) {
SourceLocation BaseLoc
= BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
if (!BaseType->isDependentType() && !BaseType->isRecordType())
return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
<< BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
bool Dependent = CurContext->isDependentContext() &&
(BaseType->isDependentType() || Init->isTypeDependent());
SourceRange InitRange = Init->getSourceRange();
if (EllipsisLoc.isValid()) {
if (!BaseType->containsUnexpandedParameterPack()) {
Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
<< SourceRange(BaseLoc, InitRange.getEnd());
EllipsisLoc = SourceLocation();
}
} else {
if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
return true;
if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
return true;
}
const CXXBaseSpecifier *DirectBaseSpec = nullptr;
const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
if (!Dependent) {
if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
BaseType))
return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
VirtualBaseSpec);
if (!DirectBaseSpec && !VirtualBaseSpec) {
if (ClassDecl->hasAnyDependentBases())
Dependent = true;
else
return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
<< BaseType << Context.getTypeDeclType(ClassDecl)
<< BaseTInfo->getTypeLoc().getLocalSourceRange();
}
}
if (Dependent) {
DiscardCleanupsInEvaluationContext();
return new (Context) CXXCtorInitializer(Context, BaseTInfo,
false,
InitRange.getBegin(), Init,
InitRange.getEnd(), EllipsisLoc);
}
if (DirectBaseSpec && VirtualBaseSpec)
return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
<< BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
if (!BaseSpec)
BaseSpec = VirtualBaseSpec;
bool InitList = true;
MultiExprArg Args = Init;
if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
InitList = false;
Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
}
InitializedEntity BaseEntity =
InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
InitializationKind Kind =
InitList ? InitializationKind::CreateDirectList(BaseLoc)
: InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
InitRange.getEnd());
InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
if (!BaseInit.isInvalid()) {
BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
false);
}
if (BaseInit.isInvalid()) {
BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
Args, BaseType);
if (BaseInit.isInvalid())
return true;
} else {
if (CurContext->isDependentContext())
BaseInit = Init;
}
return new (Context) CXXCtorInitializer(Context, BaseTInfo,
BaseSpec->isVirtual(),
InitRange.getBegin(),
BaseInit.getAs<Expr>(),
InitRange.getEnd(), EllipsisLoc);
}
static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
if (T.isNull()) T = E->getType();
QualType TargetType = SemaRef.BuildReferenceType(
T, false, SourceLocation(), DeclarationName());
SourceLocation ExprLoc = E->getBeginLoc();
TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
TargetType, ExprLoc);
return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
SourceRange(ExprLoc, ExprLoc),
E->getSourceRange()).get();
}
enum ImplicitInitializerKind {
IIK_Default,
IIK_Copy,
IIK_Move,
IIK_Inherit
};
static bool
BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
ImplicitInitializerKind ImplicitInitKind,
CXXBaseSpecifier *BaseSpec,
bool IsInheritedVirtualBase,
CXXCtorInitializer *&CXXBaseInit) {
InitializedEntity InitEntity
= InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
IsInheritedVirtualBase);
ExprResult BaseInit;
switch (ImplicitInitKind) {
case IIK_Inherit:
case IIK_Default: {
InitializationKind InitKind
= InitializationKind::CreateDefault(Constructor->getLocation());
InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
break;
}
case IIK_Move:
case IIK_Copy: {
bool Moving = ImplicitInitKind == IIK_Move;
ParmVarDecl *Param = Constructor->getParamDecl(0);
QualType ParamType = Param->getType().getNonReferenceType();
Expr *CopyCtorArg =
DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
SourceLocation(), Param, false,
Constructor->getLocation(), ParamType,
VK_LValue, nullptr);
SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
QualType ArgTy =
SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
ParamType.getQualifiers());
if (Moving) {
CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
}
CXXCastPath BasePath;
BasePath.push_back(BaseSpec);
CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
CK_UncheckedDerivedToBase,
Moving ? VK_XValue : VK_LValue,
&BasePath).get();
InitializationKind InitKind
= InitializationKind::CreateDirect(Constructor->getLocation(),
SourceLocation(), SourceLocation());
InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
break;
}
}
BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
if (BaseInit.isInvalid())
return true;
CXXBaseInit =
new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
SourceLocation()),
BaseSpec->isVirtual(),
SourceLocation(),
BaseInit.getAs<Expr>(),
SourceLocation(),
SourceLocation());
return false;
}
static bool RefersToRValueRef(Expr *MemRef) {
ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
return Referenced->getType()->isRValueReferenceType();
}
static bool
BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
ImplicitInitializerKind ImplicitInitKind,
FieldDecl *Field, IndirectFieldDecl *Indirect,
CXXCtorInitializer *&CXXMemberInit) {
if (Field->isInvalidDecl())
return true;
SourceLocation Loc = Constructor->getLocation();
if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
bool Moving = ImplicitInitKind == IIK_Move;
ParmVarDecl *Param = Constructor->getParamDecl(0);
QualType ParamType = Param->getType().getNonReferenceType();
if (Field->isZeroLengthBitField(SemaRef.Context))
return false;
Expr *MemberExprBase =
DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
SourceLocation(), Param, false,
Loc, ParamType, VK_LValue, nullptr);
SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
if (Moving) {
MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
}
CXXScopeSpec SS;
LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
Sema::LookupMemberName);
MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
: cast<ValueDecl>(Field), AS_public);
MemberLookup.resolveKind();
ExprResult CtorArg
= SemaRef.BuildMemberReferenceExpr(MemberExprBase,
ParamType, Loc,
false,
SS,
SourceLocation(),
nullptr,
MemberLookup,
nullptr,
nullptr);
if (CtorArg.isInvalid())
return true;
if (RefersToRValueRef(CtorArg.get())) {
CtorArg = CastForMoving(SemaRef, CtorArg.get());
}
InitializedEntity Entity =
Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
true)
: InitializedEntity::InitializeMember(Field, nullptr,
true);
InitializationKind InitKind =
InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
Expr *CtorArgE = CtorArg.getAs<Expr>();
InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
ExprResult MemberInit =
InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
if (MemberInit.isInvalid())
return true;
if (Indirect)
CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
else
CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
return false;
}
assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
"Unhandled implicit init kind!");
QualType FieldBaseElementType =
SemaRef.Context.getBaseElementType(Field->getType());
if (FieldBaseElementType->isRecordType()) {
InitializedEntity InitEntity =
Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
true)
: InitializedEntity::InitializeMember(Field, nullptr,
true);
InitializationKind InitKind =
InitializationKind::CreateDefault(Loc);
InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
ExprResult MemberInit =
InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
if (MemberInit.isInvalid())
return true;
if (Indirect)
CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Indirect, Loc,
Loc,
MemberInit.get(),
Loc);
else
CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Field, Loc, Loc,
MemberInit.get(),
Loc);
return false;
}
if (!Field->getParent()->isUnion()) {
if (FieldBaseElementType->isReferenceType()) {
SemaRef.Diag(Constructor->getLocation(),
diag::err_uninitialized_member_in_ctor)
<< (int)Constructor->isImplicit()
<< SemaRef.Context.getTagDeclType(Constructor->getParent())
<< 0 << Field->getDeclName();
SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
return true;
}
if (FieldBaseElementType.isConstQualified()) {
SemaRef.Diag(Constructor->getLocation(),
diag::err_uninitialized_member_in_ctor)
<< (int)Constructor->isImplicit()
<< SemaRef.Context.getTagDeclType(Constructor->getParent())
<< 1 << Field->getDeclName();
SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
return true;
}
}
if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
CXXMemberInit
= new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
Loc, Loc,
new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
Loc);
return false;
}
CXXMemberInit = nullptr;
return false;
}
namespace {
struct BaseAndFieldInfo {
Sema &S;
CXXConstructorDecl *Ctor;
bool AnyErrorsInInits;
ImplicitInitializerKind IIK;
llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
SmallVector<CXXCtorInitializer*, 8> AllToInit;
llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
: S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
if (Ctor->getInheritedConstructor())
IIK = IIK_Inherit;
else if (Generated && Ctor->isCopyConstructor())
IIK = IIK_Copy;
else if (Generated && Ctor->isMoveConstructor())
IIK = IIK_Move;
else
IIK = IIK_Default;
}
bool isImplicitCopyOrMove() const {
switch (IIK) {
case IIK_Copy:
case IIK_Move:
return true;
case IIK_Default:
case IIK_Inherit:
return false;
}
llvm_unreachable("Invalid ImplicitInitializerKind!");
}
bool addFieldInitializer(CXXCtorInitializer *Init) {
AllToInit.push_back(Init);
if (Init->getInit()->HasSideEffects(S.Context))
S.UnusedPrivateFields.remove(Init->getAnyMember());
return false;
}
bool isInactiveUnionMember(FieldDecl *Field) {
RecordDecl *Record = Field->getParent();
if (!Record->isUnion())
return false;
if (FieldDecl *Active =
ActiveUnionMember.lookup(Record->getCanonicalDecl()))
return Active != Field->getCanonicalDecl();
if (isImplicitCopyOrMove())
return true;
if (Field->hasInClassInitializer())
return false;
if (!Field->isAnonymousStructOrUnion())
return true;
CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
return !FieldRD->hasInClassInitializer();
}
bool isWithinInactiveUnionMember(FieldDecl *Field,
IndirectFieldDecl *Indirect) {
if (!Indirect)
return isInactiveUnionMember(Field);
for (auto *C : Indirect->chain()) {
FieldDecl *Field = dyn_cast<FieldDecl>(C);
if (Field && isInactiveUnionMember(Field))
return true;
}
return false;
}
};
}
static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
if (T->isIncompleteArrayType())
return true;
while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
if (!ArrayT->getSize())
return true;
T = ArrayT->getElementType();
}
return false;
}
static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
FieldDecl *Field,
IndirectFieldDecl *Indirect = nullptr) {
if (Field->isInvalidDecl())
return false;
if (CXXCtorInitializer *Init =
Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
return Info.addFieldInitializer(Init);
if (Info.isWithinInactiveUnionMember(Field, Indirect))
return false;
if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
ExprResult DIE =
SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
if (DIE.isInvalid())
return true;
auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
SemaRef.checkInitializerLifetime(Entity, DIE.get());
CXXCtorInitializer *Init;
if (Indirect)
Init = new (SemaRef.Context)
CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
SourceLocation(), DIE.get(), SourceLocation());
else
Init = new (SemaRef.Context)
CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
SourceLocation(), DIE.get(), SourceLocation());
return Info.addFieldInitializer(Init);
}
if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
return false;
if (Info.AnyErrorsInInits)
return false;
CXXCtorInitializer *Init = nullptr;
if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
Indirect, Init))
return true;
if (!Init)
return false;
return Info.addFieldInitializer(Init);
}
bool
Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
CXXCtorInitializer *Initializer) {
assert(Initializer->isDelegatingInitializer());
Constructor->setNumCtorInitializers(1);
CXXCtorInitializer **initializer =
new (Context) CXXCtorInitializer*[1];
memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
Constructor->setCtorInitializers(initializer);
if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
}
DelegatingCtorDecls.push_back(Constructor);
DiagnoseUninitializedFields(*this, Constructor);
return false;
}
bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
ArrayRef<CXXCtorInitializer *> Initializers) {
if (Constructor->isDependentContext()) {
if (!Initializers.empty()) {
Constructor->setNumCtorInitializers(Initializers.size());
CXXCtorInitializer **baseOrMemberInitializers =
new (Context) CXXCtorInitializer*[Initializers.size()];
memcpy(baseOrMemberInitializers, Initializers.data(),
Initializers.size() * sizeof(CXXCtorInitializer*));
Constructor->setCtorInitializers(baseOrMemberInitializers);
}
if (AnyErrors)
Constructor->setInvalidDecl();
return false;
}
BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
if (!ClassDecl)
return true;
bool HadError = false;
for (unsigned i = 0; i < Initializers.size(); i++) {
CXXCtorInitializer *Member = Initializers[i];
if (Member->isBaseInitializer())
Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
else {
Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
if (IndirectFieldDecl *F = Member->getIndirectMember()) {
for (auto *C : F->chain()) {
FieldDecl *FD = dyn_cast<FieldDecl>(C);
if (FD && FD->getParent()->isUnion())
Info.ActiveUnionMember.insert(std::make_pair(
FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
}
} else if (FieldDecl *FD = Member->getMember()) {
if (FD->getParent()->isUnion())
Info.ActiveUnionMember.insert(std::make_pair(
FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
}
}
}
llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
for (auto &I : ClassDecl->bases()) {
if (I.isVirtual())
DirectVBases.insert(&I);
}
for (auto &VBase : ClassDecl->vbases()) {
if (CXXCtorInitializer *Value
= Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
if (ClassDecl->isAbstract()) {
Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
<< VBase.getType() << ClassDecl;
DiagnoseAbstractType(ClassDecl);
}
Info.AllToInit.push_back(Value);
} else if (!AnyErrors && !ClassDecl->isAbstract()) {
bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
CXXCtorInitializer *CXXBaseInit;
if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
&VBase, IsInheritedVirtualBase,
CXXBaseInit)) {
HadError = true;
continue;
}
Info.AllToInit.push_back(CXXBaseInit);
}
}
for (auto &Base : ClassDecl->bases()) {
if (Base.isVirtual())
continue;
if (CXXCtorInitializer *Value
= Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
Info.AllToInit.push_back(Value);
} else if (!AnyErrors) {
CXXCtorInitializer *CXXBaseInit;
if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
&Base, false,
CXXBaseInit)) {
HadError = true;
continue;
}
Info.AllToInit.push_back(CXXBaseInit);
}
}
for (auto *Mem : ClassDecl->decls()) {
if (auto *F = dyn_cast<FieldDecl>(Mem)) {
if (F->isUnnamedBitfield())
continue;
if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
continue;
if (CollectFieldInitializer(*this, Info, F))
HadError = true;
continue;
}
if (Info.isImplicitCopyOrMove())
continue;
if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
if (F->getType()->isIncompleteArrayType()) {
assert(ClassDecl->hasFlexibleArrayMember() &&
"Incomplete array type is not valid");
continue;
}
if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
HadError = true;
continue;
}
}
unsigned NumInitializers = Info.AllToInit.size();
if (NumInitializers > 0) {
Constructor->setNumCtorInitializers(NumInitializers);
CXXCtorInitializer **baseOrMemberInitializers =
new (Context) CXXCtorInitializer*[NumInitializers];
memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
NumInitializers * sizeof(CXXCtorInitializer*));
Constructor->setCtorInitializers(baseOrMemberInitializers);
MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
Constructor->getParent());
}
return HadError;
}
static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
const RecordDecl *RD = RT->getDecl();
if (RD->isAnonymousStructOrUnion()) {
for (auto *Field : RD->fields())
PopulateKeysForFields(Field, IdealInits);
return;
}
}
IdealInits.push_back(Field->getCanonicalDecl());
}
static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
return Context.getCanonicalType(BaseType).getTypePtr();
}
static const void *GetKeyForMember(ASTContext &Context,
CXXCtorInitializer *Member) {
if (!Member->isAnyMemberInitializer())
return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
return Member->getAnyMember()->getCanonicalDecl();
}
static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
const CXXCtorInitializer *Previous,
const CXXCtorInitializer *Current) {
if (Previous->isAnyMemberInitializer())
Diag << 0 << Previous->getAnyMember();
else
Diag << 1 << Previous->getTypeSourceInfo()->getType();
if (Current->isAnyMemberInitializer())
Diag << 0 << Current->getAnyMember();
else
Diag << 1 << Current->getTypeSourceInfo()->getType();
}
static void DiagnoseBaseOrMemInitializerOrder(
Sema &SemaRef, const CXXConstructorDecl *Constructor,
ArrayRef<CXXCtorInitializer *> Inits) {
if (Constructor->getDeclContext()->isDependentContext())
return;
bool ShouldCheckOrder = false;
for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
CXXCtorInitializer *Init = Inits[InitIndex];
if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
Init->getSourceLocation())) {
ShouldCheckOrder = true;
break;
}
}
if (!ShouldCheckOrder)
return;
SmallVector<const void*, 32> IdealInitKeys;
const CXXRecordDecl *ClassDecl = Constructor->getParent();
for (const auto &VBase : ClassDecl->vbases())
IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
for (const auto &Base : ClassDecl->bases()) {
if (Base.isVirtual())
continue;
IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
}
for (auto *Field : ClassDecl->fields()) {
if (Field->isUnnamedBitfield())
continue;
PopulateKeysForFields(Field, IdealInitKeys);
}
unsigned NumIdealInits = IdealInitKeys.size();
unsigned IdealIndex = 0;
SmallVector<unsigned> WarnIndexes;
SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
for (; IdealIndex != NumIdealInits; ++IdealIndex)
if (InitKey == IdealInitKeys[IdealIndex])
break;
if (IdealIndex == NumIdealInits && InitIndex) {
WarnIndexes.push_back(InitIndex);
for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
if (InitKey == IdealInitKeys[IdealIndex])
break;
assert(IdealIndex < NumIdealInits &&
"initializer not found in initializer list");
}
CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
}
if (WarnIndexes.empty())
return;
llvm::sort(CorrelatedInitOrder, llvm::less_first());
{
Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
Inits[WarnIndexes.front() - 1]->getSourceLocation(),
WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
: diag::warn_some_initializers_out_of_order);
for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
if (CorrelatedInitOrder[I].second == I)
continue;
D << FixItHint::CreateReplacement(
Inits[I]->getSourceRange(),
Lexer::getSourceText(
CharSourceRange::getTokenRange(
Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
SemaRef.getSourceManager(), SemaRef.getLangOpts()));
}
if (WarnIndexes.size() == 1) {
AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
Inits[WarnIndexes.front()]);
return;
}
}
for (unsigned WarnIndex : WarnIndexes) {
const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
diag::note_initializer_out_of_order);
AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
D << PrevInit->getSourceRange();
}
}
namespace {
bool CheckRedundantInit(Sema &S,
CXXCtorInitializer *Init,
CXXCtorInitializer *&PrevInit) {
if (!PrevInit) {
PrevInit = Init;
return false;
}
if (FieldDecl *Field = Init->getAnyMember())
S.Diag(Init->getSourceLocation(),
diag::err_multiple_mem_initialization)
<< Field->getDeclName()
<< Init->getSourceRange();
else {
const Type *BaseClass = Init->getBaseClass();
assert(BaseClass && "neither field nor base");
S.Diag(Init->getSourceLocation(),
diag::err_multiple_base_initialization)
<< QualType(BaseClass, 0)
<< Init->getSourceRange();
}
S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
<< 0 << PrevInit->getSourceRange();
return true;
}
typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
bool CheckRedundantUnionInit(Sema &S,
CXXCtorInitializer *Init,
RedundantUnionMap &Unions) {
FieldDecl *Field = Init->getAnyMember();
RecordDecl *Parent = Field->getParent();
NamedDecl *Child = Field;
while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
if (Parent->isUnion()) {
UnionEntry &En = Unions[Parent];
if (En.first && En.first != Child) {
S.Diag(Init->getSourceLocation(),
diag::err_multiple_mem_union_initialization)
<< Field->getDeclName()
<< Init->getSourceRange();
S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
<< 0 << En.second->getSourceRange();
return true;
}
if (!En.first) {
En.first = Child;
En.second = Init;
}
if (!Parent->isAnonymousStructOrUnion())
return false;
}
Child = Parent;
Parent = cast<RecordDecl>(Parent->getDeclContext());
}
return false;
}
}
void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
SourceLocation ColonLoc,
ArrayRef<CXXCtorInitializer*> MemInits,
bool AnyErrors) {
if (!ConstructorDecl)
return;
AdjustDeclIfTemplate(ConstructorDecl);
CXXConstructorDecl *Constructor
= dyn_cast<CXXConstructorDecl>(ConstructorDecl);
if (!Constructor) {
Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
return;
}
llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
RedundantUnionMap MemberUnions;
bool HadError = false;
for (unsigned i = 0; i < MemInits.size(); i++) {
CXXCtorInitializer *Init = MemInits[i];
Init->setSourceOrder(i);
if (Init->isAnyMemberInitializer()) {
const void *Key = GetKeyForMember(Context, Init);
if (CheckRedundantInit(*this, Init, Members[Key]) ||
CheckRedundantUnionInit(*this, Init, MemberUnions))
HadError = true;
} else if (Init->isBaseInitializer()) {
const void *Key = GetKeyForMember(Context, Init);
if (CheckRedundantInit(*this, Init, Members[Key]))
HadError = true;
} else {
assert(Init->isDelegatingInitializer());
if (MemInits.size() != 1) {
Diag(Init->getSourceLocation(),
diag::err_delegating_initializer_alone)
<< Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
}
SetDelegatingInitializer(Constructor, MemInits[i]);
return;
}
}
if (HadError)
return;
DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
SetCtorInitializers(Constructor, AnyErrors, MemInits);
DiagnoseUninitializedFields(*this, Constructor);
}
void
Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
CXXRecordDecl *ClassDecl) {
if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
return;
for (auto *Field : ClassDecl->fields()) {
if (Field->isInvalidDecl())
continue;
if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
continue;
QualType FieldType = Context.getBaseElementType(Field->getType());
const RecordType* RT = FieldType->getAs<RecordType>();
if (!RT)
continue;
CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
if (FieldClassDecl->isInvalidDecl())
continue;
if (FieldClassDecl->hasIrrelevantDestructor())
continue;
if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
continue;
CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
assert(Dtor && "No dtor found for FieldClassDecl!");
CheckDestructorAccess(Field->getLocation(), Dtor,
PDiag(diag::err_access_dtor_field)
<< Field->getDeclName()
<< FieldType);
MarkFunctionReferenced(Location, Dtor);
DiagnoseUseOfDecl(Dtor, Location);
}
bool VisitVirtualBases = !ClassDecl->isAbstract();
if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
if (Dtor && Dtor->isUsed())
VisitVirtualBases = false;
}
llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
for (const auto &Base : ClassDecl->bases()) {
const RecordType *RT = Base.getType()->getAs<RecordType>();
if (!RT)
continue;
if (Base.isVirtual()) {
if (!VisitVirtualBases)
continue;
DirectVirtualBases.insert(RT);
}
CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
if (BaseClassDecl->isInvalidDecl())
continue;
if (BaseClassDecl->hasIrrelevantDestructor())
continue;
CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
assert(Dtor && "No dtor found for BaseClassDecl!");
CheckDestructorAccess(Base.getBeginLoc(), Dtor,
PDiag(diag::err_access_dtor_base)
<< Base.getType() << Base.getSourceRange(),
Context.getTypeDeclType(ClassDecl));
MarkFunctionReferenced(Location, Dtor);
DiagnoseUseOfDecl(Dtor, Location);
}
if (VisitVirtualBases)
MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
&DirectVirtualBases);
}
void Sema::MarkVirtualBaseDestructorsReferenced(
SourceLocation Location, CXXRecordDecl *ClassDecl,
llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
for (const auto &VBase : ClassDecl->vbases()) {
const RecordType *RT = VBase.getType()->castAs<RecordType>();
if (DirectVirtualBases && DirectVirtualBases->count(RT))
continue;
CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
if (BaseClassDecl->isInvalidDecl())
continue;
if (BaseClassDecl->hasIrrelevantDestructor())
continue;
CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
assert(Dtor && "No dtor found for BaseClassDecl!");
if (CheckDestructorAccess(
ClassDecl->getLocation(), Dtor,
PDiag(diag::err_access_dtor_vbase)
<< Context.getTypeDeclType(ClassDecl) << VBase.getType(),
Context.getTypeDeclType(ClassDecl)) ==
AR_accessible) {
CheckDerivedToBaseConversion(
Context.getTypeDeclType(ClassDecl), VBase.getType(),
diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
SourceRange(), DeclarationName(), nullptr);
}
MarkFunctionReferenced(Location, Dtor);
DiagnoseUseOfDecl(Dtor, Location);
}
}
void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
if (!CDtorDecl)
return;
if (CXXConstructorDecl *Constructor
= dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
SetCtorInitializers(Constructor, false);
DiagnoseUninitializedFields(*this, Constructor);
}
}
bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
if (!getLangOpts().CPlusPlus)
return false;
const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
if (!RD)
return false;
const CXXRecordDecl *Def = RD->getDefinition();
if (!Def || Def->isBeingDefined())
return false;
return RD->isAbstract();
}
bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser) {
if (!isAbstractType(Loc, T))
return false;
T = Context.getBaseElementType(T);
Diagnoser.diagnose(*this, Loc, T);
DiagnoseAbstractType(T->getAsCXXRecordDecl());
return true;
}
void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
return;
if (Diags.isLastDiagnosticIgnored())
return;
CXXFinalOverriderMap FinalOverriders;
RD->getFinalOverriders(FinalOverriders);
llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
MEnd = FinalOverriders.end();
M != MEnd;
++M) {
for (OverridingMethods::iterator SO = M->second.begin(),
SOEnd = M->second.end();
SO != SOEnd; ++SO) {
if (SO->second.size() != 1)
continue;
if (!SO->second.front().Method->isPure())
continue;
if (!SeenPureMethods.insert(SO->second.front().Method).second)
continue;
Diag(SO->second.front().Method->getLocation(),
diag::note_pure_virtual_function)
<< SO->second.front().Method->getDeclName() << RD->getDeclName();
}
}
if (!PureVirtualClassDiagSet)
PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
PureVirtualClassDiagSet->insert(RD);
}
namespace {
struct AbstractUsageInfo {
Sema &S;
CXXRecordDecl *Record;
CanQualType AbstractType;
bool Invalid;
AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
: S(S), Record(Record),
AbstractType(S.Context.getCanonicalType(
S.Context.getTypeDeclType(Record))),
Invalid(false) {}
void DiagnoseAbstractType() {
if (Invalid) return;
S.DiagnoseAbstractType(Record);
Invalid = true;
}
void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
};
struct CheckAbstractUsage {
AbstractUsageInfo &Info;
const NamedDecl *Ctx;
CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
: Info(Info), Ctx(Ctx) {}
void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
switch (TL.getTypeLocClass()) {
#define ABSTRACT_TYPELOC(CLASS, PARENT)
#define TYPELOC(CLASS, PARENT) \
case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
#include "clang/AST/TypeLocNodes.def"
}
}
void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
if (!TL.getParam(I))
continue;
TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
}
}
void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Visit(TL.getElementLoc(), Sema::AbstractArrayType);
}
void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
TemplateArgumentLoc TAL = TL.getArgLoc(I);
if (TAL.getArgument().getKind() == TemplateArgument::Type)
if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
Visit(TSI->getTypeLoc(), Sema::AbstractNone);
}
}
#define CheckPolymorphic(Type) \
void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
}
CheckPolymorphic(PointerTypeLoc)
CheckPolymorphic(ReferenceTypeLoc)
CheckPolymorphic(MemberPointerTypeLoc)
CheckPolymorphic(BlockPointerTypeLoc)
CheckPolymorphic(AtomicTypeLoc)
void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
if (TypeLoc Next = TL.getNextTypeLoc())
return Visit(Next, Sel);
if (Sel == Sema::AbstractNone) return;
QualType T = TL.getType();
if (T->isArrayType()) {
Sel = Sema::AbstractArrayType;
T = Info.S.Context.getBaseElementType(T);
}
CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
if (CT != Info.AbstractType) return;
if (Sel == Sema::AbstractArrayType) {
Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
<< T << TL.getSourceRange();
} else {
Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
<< Sel << T << TL.getSourceRange();
}
Info.DiagnoseAbstractType();
}
};
void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
Sema::AbstractDiagSelID Sel) {
CheckAbstractUsage(*this, D).Visit(TL, Sel);
}
}
static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
FunctionDecl *FD) {
if (FD->doesThisDeclarationHaveABody())
return;
if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
}
static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
VarDecl *VD) {
if (VD->isThisDeclarationADefinition())
return;
Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
Sema::AbstractVariableType);
}
static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
CXXRecordDecl *RD) {
for (auto *D : RD->decls()) {
if (D->isImplicit()) continue;
if (auto *FD = dyn_cast<FriendDecl>(D)) {
D = FD->getFriendDecl();
if (!D) continue;
}
if (auto *FD = dyn_cast<FunctionDecl>(D)) {
CheckAbstractClassUsage(Info, FD);
} else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
} else if (auto *FD = dyn_cast<FieldDecl>(D)) {
if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
} else if (auto *VD = dyn_cast<VarDecl>(D)) {
CheckAbstractClassUsage(Info, VD);
} else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
} else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
CheckAbstractClassUsage(Info, RD);
} else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
}
}
}
static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
Attr *ClassAttr = getDLLAttr(Class);
if (!ClassAttr)
return;
assert(ClassAttr->getKind() == attr::DLLExport);
TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
if (TSK == TSK_ExplicitInstantiationDeclaration)
return;
struct MarkingClassDllexported {
Sema &S;
MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
SourceLocation AttrLoc)
: S(S) {
Sema::CodeSynthesisContext Ctx;
Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
Ctx.PointOfInstantiation = AttrLoc;
Ctx.Entity = Class;
S.pushCodeSynthesisContext(Ctx);
}
~MarkingClassDllexported() {
S.popCodeSynthesisContext();
}
} MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
S.MarkVTableUsed(Class->getLocation(), Class, true);
for (Decl *Member : Class->decls()) {
if (!Member->hasAttr<DLLExportAttr>())
continue;
auto *VD = dyn_cast<VarDecl>(Member);
if (VD && VD->getStorageClass() == SC_Static &&
TSK == TSK_ImplicitInstantiation)
S.MarkVariableReferenced(VD->getLocation(), VD);
auto *MD = dyn_cast<CXXMethodDecl>(Member);
if (!MD)
continue;
if (MD->isUserProvided()) {
if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
continue;
if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
auto *CD = dyn_cast<CXXConstructorDecl>(MD);
if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
S.InstantiateDefaultCtorDefaultArgs(CD);
}
}
S.MarkFunctionReferenced(Class->getLocation(), MD);
} else if (MD->isExplicitlyDefaulted()) {
S.MarkFunctionReferenced(Class->getLocation(), MD);
if (TSK != TSK_ExplicitInstantiationDefinition) {
S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
}
} else if (!MD->isTrivial() ||
MD->isCopyAssignmentOperator() ||
MD->isMoveAssignmentOperator()) {
S.MarkFunctionReferenced(Class->getLocation(), MD);
S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
}
}
}
static void checkForMultipleExportedDefaultConstructors(Sema &S,
CXXRecordDecl *Class) {
if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
return;
CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
for (Decl *Member : Class->decls()) {
auto *CD = dyn_cast<CXXConstructorDecl>(Member);
if (!CD || !CD->isDefaultConstructor())
continue;
auto *Attr = CD->getAttr<DLLExportAttr>();
if (!Attr)
continue;
if (!Class->isDependentContext()) {
for (ParmVarDecl *PD : CD->parameters()) {
(void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
S.DiscardCleanupsInEvaluationContext();
}
}
if (LastExportedDefaultCtor) {
S.Diag(LastExportedDefaultCtor->getLocation(),
diag::err_attribute_dll_ambiguous_default_ctor)
<< Class;
S.Diag(CD->getLocation(), diag::note_entity_declared_at)
<< CD->getDeclName();
return;
}
LastExportedDefaultCtor = CD;
}
}
static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
CXXRecordDecl *Class) {
bool ErrorReported = false;
auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
ClassTemplateDecl *TD) {
if (ErrorReported)
return;
S.Diag(TD->getLocation(),
diag::err_cuda_device_builtin_surftex_cls_template)
<< 0 << TD;
ErrorReported = true;
};
ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
if (!TD) {
auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
if (!SD) {
S.Diag(Class->getLocation(),
diag::err_cuda_device_builtin_surftex_ref_decl)
<< 0 << Class;
S.Diag(Class->getLocation(),
diag::note_cuda_device_builtin_surftex_should_be_template_class)
<< Class;
return;
}
TD = SD->getSpecializedTemplate();
}
TemplateParameterList *Params = TD->getTemplateParameters();
unsigned N = Params->size();
if (N != 2) {
reportIllegalClassTemplate(S, TD);
S.Diag(TD->getLocation(),
diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
<< TD << 2;
}
if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
reportIllegalClassTemplate(S, TD);
S.Diag(TD->getLocation(),
diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
<< TD << 0 << 0;
}
if (N > 1) {
auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
reportIllegalClassTemplate(S, TD);
S.Diag(TD->getLocation(),
diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
<< TD << 1 << 1;
}
}
}
static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
CXXRecordDecl *Class) {
bool ErrorReported = false;
auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
ClassTemplateDecl *TD) {
if (ErrorReported)
return;
S.Diag(TD->getLocation(),
diag::err_cuda_device_builtin_surftex_cls_template)
<< 1 << TD;
ErrorReported = true;
};
ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
if (!TD) {
auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
if (!SD) {
S.Diag(Class->getLocation(),
diag::err_cuda_device_builtin_surftex_ref_decl)
<< 1 << Class;
S.Diag(Class->getLocation(),
diag::note_cuda_device_builtin_surftex_should_be_template_class)
<< Class;
return;
}
TD = SD->getSpecializedTemplate();
}
TemplateParameterList *Params = TD->getTemplateParameters();
unsigned N = Params->size();
if (N != 3) {
reportIllegalClassTemplate(S, TD);
S.Diag(TD->getLocation(),
diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
<< TD << 3;
}
if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
reportIllegalClassTemplate(S, TD);
S.Diag(TD->getLocation(),
diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
<< TD << 0 << 0;
}
if (N > 1) {
auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
reportIllegalClassTemplate(S, TD);
S.Diag(TD->getLocation(),
diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
<< TD << 1 << 1;
}
}
if (N > 2) {
auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
reportIllegalClassTemplate(S, TD);
S.Diag(TD->getLocation(),
diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
<< TD << 2 << 1;
}
}
}
void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
for (auto *Method : Class->methods()) {
if (Method->isUserProvided())
continue;
if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, true))
Method->addAttr(A);
}
}
void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
Attr *ClassAttr = getDLLAttr(Class);
if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
if (Attr *TemplateAttr =
getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
A->setInherited(true);
ClassAttr = A;
}
}
}
if (!ClassAttr)
return;
if (!Class->isExternallyVisible()) {
Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
<< Class << ClassAttr;
return;
}
if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
!ClassAttr->isInherited()) {
for (Decl *Member : Class->decls()) {
if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
continue;
InheritableAttr *MemberAttr = getDLLAttr(Member);
if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
continue;
Diag(MemberAttr->getLocation(),
diag::err_attribute_dll_member_of_dll_class)
<< MemberAttr << ClassAttr;
Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
Member->setInvalidDecl();
}
}
if (Class->getDescribedClassTemplate())
return;
const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
const bool PropagatedImport =
!ClassExported &&
cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
if (ClassExported && !ClassAttr->isInherited() &&
TSK == TSK_ExplicitInstantiationDeclaration &&
!Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
Class->dropAttr<DLLExportAttr>();
return;
}
ForceDeclarationOfImplicitMembers(Class);
for (Decl *Member : Class->decls()) {
VarDecl *VD = dyn_cast<VarDecl>(Member);
CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
if (!VD && !MD)
continue;
if (MD) {
if (MD->isDeleted())
continue;
if (MD->isInlined()) {
if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
TSK != TSK_ExplicitInstantiationDeclaration &&
TSK != TSK_ExplicitInstantiationDefinition)
continue;
auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
if ((MD->isMoveAssignmentOperator() ||
(Ctor && Ctor->isMoveConstructor())) &&
!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
continue;
if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
(Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
continue;
}
}
if (VD && PropagatedImport)
continue;
if (!cast<NamedDecl>(Member)->isExternallyVisible())
continue;
if (!getDLLAttr(Member)) {
InheritableAttr *NewAttr = nullptr;
if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
TSK != TSK_ExplicitInstantiationDeclaration &&
TSK != TSK_ExplicitInstantiationDefinition) {
if (ClassExported) {
NewAttr = ::new (getASTContext())
DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
} else {
NewAttr = ::new (getASTContext())
DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
}
} else {
NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
}
NewAttr->setInherited(true);
Member->addAttr(NewAttr);
if (MD) {
for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
FD = FD->getPreviousDecl()) {
if (FD->getFriendObjectKind() == Decl::FOK_None)
continue;
assert(!getDLLAttr(FD) &&
"friend re-decl should not already have a DLLAttr");
NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
NewAttr->setInherited(true);
FD->addAttr(NewAttr);
}
}
}
}
if (ClassExported)
DelayedDllExportClasses.push_back(Class);
}
void Sema::propagateDLLAttrToBaseClassTemplate(
CXXRecordDecl *Class, Attr *ClassAttr,
ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
if (getDLLAttr(
BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
return;
}
auto TSK = BaseTemplateSpec->getSpecializationKind();
if (!getDLLAttr(BaseTemplateSpec) &&
(TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
TSK == TSK_ImplicitInstantiation)) {
auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
NewAttr->setInherited(true);
BaseTemplateSpec->addAttr(NewAttr);
if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
ImportAttr->setPropagatedToBaseTemplate();
if (TSK != TSK_Undeclared)
checkClassLevelDLLAttribute(BaseTemplateSpec);
return;
}
if (getDLLAttr(BaseTemplateSpec)) {
return;
}
Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
<< BaseTemplateSpec->isExplicitSpecialization();
Diag(ClassAttr->getLocation(), diag::note_attribute);
if (BaseTemplateSpec->isExplicitSpecialization()) {
Diag(BaseTemplateSpec->getLocation(),
diag::note_template_class_explicit_specialization_was_here)
<< BaseTemplateSpec;
} else {
Diag(BaseTemplateSpec->getPointOfInstantiation(),
diag::note_template_class_instantiation_was_here)
<< BaseTemplateSpec;
}
}
Sema::DefaultedFunctionKind
Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
if (Ctor->isDefaultConstructor())
return Sema::CXXDefaultConstructor;
if (Ctor->isCopyConstructor())
return Sema::CXXCopyConstructor;
if (Ctor->isMoveConstructor())
return Sema::CXXMoveConstructor;
}
if (MD->isCopyAssignmentOperator())
return Sema::CXXCopyAssignment;
if (MD->isMoveAssignmentOperator())
return Sema::CXXMoveAssignment;
if (isa<CXXDestructorDecl>(FD))
return Sema::CXXDestructor;
}
switch (FD->getDeclName().getCXXOverloadedOperator()) {
case OO_EqualEqual:
return DefaultedComparisonKind::Equal;
case OO_ExclaimEqual:
return DefaultedComparisonKind::NotEqual;
case OO_Spaceship:
if (!getLangOpts().CPlusPlus20)
break;
return DefaultedComparisonKind::ThreeWay;
case OO_Less:
case OO_LessEqual:
case OO_Greater:
case OO_GreaterEqual:
if (!getLangOpts().CPlusPlus20)
break;
return DefaultedComparisonKind::Relational;
default:
break;
}
return DefaultedFunctionKind();
}
static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
SourceLocation DefaultLoc) {
Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
if (DFK.isComparison())
return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
switch (DFK.asSpecialMember()) {
case Sema::CXXDefaultConstructor:
S.DefineImplicitDefaultConstructor(DefaultLoc,
cast<CXXConstructorDecl>(FD));
break;
case Sema::CXXCopyConstructor:
S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
break;
case Sema::CXXCopyAssignment:
S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
break;
case Sema::CXXDestructor:
S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
break;
case Sema::CXXMoveConstructor:
S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
break;
case Sema::CXXMoveAssignment:
S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
break;
case Sema::CXXInvalid:
llvm_unreachable("Invalid special member.");
}
}
static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
TargetInfo::CallingConvKind CCK) {
if (D->isDependentType() || D->isInvalidDecl())
return false;
if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
return !D->hasNonTrivialDestructorForCall() &&
!D->hasNonTrivialCopyConstructorForCall();
if (CCK == TargetInfo::CCK_MicrosoftWin64) {
bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
bool DtorIsTrivialForCall = false;
if (D->needsImplicitCopyConstructor()) {
if (!D->defaultedCopyConstructorIsDeleted()) {
if (D->hasTrivialCopyConstructor())
CopyCtorIsTrivial = true;
if (D->hasTrivialCopyConstructorForCall())
CopyCtorIsTrivialForCall = true;
}
} else {
for (const CXXConstructorDecl *CD : D->ctors()) {
if (CD->isCopyConstructor() && !CD->isDeleted()) {
if (CD->isTrivial())
CopyCtorIsTrivial = true;
if (CD->isTrivialForCall())
CopyCtorIsTrivialForCall = true;
}
}
}
if (D->needsImplicitDestructor()) {
if (!D->defaultedDestructorIsDeleted() &&
D->hasTrivialDestructorForCall())
DtorIsTrivialForCall = true;
} else if (const auto *DD = D->getDestructor()) {
if (!DD->isDeleted() && DD->isTrivialForCall())
DtorIsTrivialForCall = true;
}
if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
return true;
bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
uint64_t TypeSize = isAArch64 ? 128 : 64;
if (CopyCtorIsTrivial &&
S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
return true;
return false;
}
bool HasNonDeletedCopyOrMove = false;
if (D->needsImplicitCopyConstructor() &&
!D->defaultedCopyConstructorIsDeleted()) {
if (!D->hasTrivialCopyConstructorForCall())
return false;
HasNonDeletedCopyOrMove = true;
}
if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
!D->defaultedMoveConstructorIsDeleted()) {
if (!D->hasTrivialMoveConstructorForCall())
return false;
HasNonDeletedCopyOrMove = true;
}
if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
!D->hasTrivialDestructorForCall())
return false;
for (const CXXMethodDecl *MD : D->methods()) {
if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
continue;
auto *CD = dyn_cast<CXXConstructorDecl>(MD);
if (CD && CD->isCopyOrMoveConstructor())
HasNonDeletedCopyOrMove = true;
else if (!isa<CXXDestructorDecl>(MD))
continue;
if (!MD->isTrivialForCall())
return false;
}
return HasNonDeletedCopyOrMove;
}
static bool
ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
bool IssuedDiagnostic = false;
for (const CXXMethodDecl *O : MD->overridden_methods()) {
if (Report(O)) {
if (!IssuedDiagnostic) {
S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
IssuedDiagnostic = true;
}
S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
}
}
return IssuedDiagnostic;
}
void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
if (!Record)
return;
if (Record->isAbstract() && !Record->isInvalidDecl()) {
AbstractUsageInfo Info(*this, Record);
CheckAbstractClassUsage(Info, Record);
}
if (!Record->isInvalidDecl() && !Record->isDependentType() &&
!Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
!Record->isLambda()) {
bool Complained = false;
for (const auto *F : Record->fields()) {
if (F->hasInClassInitializer() || F->isUnnamedBitfield())
continue;
if (F->getType()->isReferenceType() ||
(F->getType().isConstQualified() && F->getType()->isScalarType())) {
if (!Complained) {
Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
<< Record->getTagKind() << Record;
Complained = true;
}
Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
<< F->getType()->isReferenceType()
<< F->getDeclName();
}
}
}
if (Record->getIdentifier()) {
DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
++I) {
NamedDecl *D = (*I)->getUnderlyingDecl();
if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
Record->hasUserDeclaredConstructor()) ||
isa<IndirectFieldDecl>(D)) {
Diag((*I)->getLocation(), diag::err_member_name_of_class)
<< D->getDeclName();
break;
}
}
}
if (Record->isPolymorphic() && !Record->isDependentType()) {
CXXDestructorDecl *dtor = Record->getDestructor();
if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
!Record->hasAttr<FinalAttr>())
Diag(dtor ? dtor->getLocation() : Record->getLocation(),
diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
}
if (Record->isAbstract()) {
if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
Diag(Record->getLocation(), diag::warn_abstract_final_class)
<< FA->isSpelledAsSealed();
DiagnoseAbstractType(Record);
}
}
if (!Record->hasAttr<FinalAttr>()) {
if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
<< FA->isSpelledAsSealed()
<< FixItHint::CreateInsertion(
getLocForEndOfToken(Record->getLocation()),
(FA->isSpelledAsSealed() ? " sealed" : " final"));
Diag(Record->getLocation(),
diag::note_final_dtor_non_final_class_silence)
<< Context.getRecordType(Record) << FA->isSpelledAsSealed();
}
}
}
if (Record->hasAttr<TrivialABIAttr>())
checkIllFormedTrivialABIStruct(*Record);
bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
if (HasTrivialABI)
Record->setHasTrivialSpecialMemberForCall();
llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
if (MD->getStorageClass() == SC_Static) {
if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
[](const CXXMethodDecl *) { return true; }))
return;
}
if (ReportOverrides(*this,
MD->isDeleted() ? diag::err_deleted_override
: diag::err_non_deleted_override,
MD, [&](const CXXMethodDecl *V) {
return MD->isDeleted() != V->isDeleted();
})) {
if (MD->isDefaulted() && MD->isDeleted())
DiagnoseDeletedDefaultedFunction(MD);
return;
}
if (ReportOverrides(*this,
MD->isConsteval() ? diag::err_consteval_override
: diag::err_non_consteval_override,
MD, [&](const CXXMethodDecl *V) {
return MD->isConsteval() != V->isConsteval();
})) {
if (MD->isDefaulted() && MD->isDeleted())
DiagnoseDeletedDefaultedFunction(MD);
return;
}
};
auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
return false;
DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
DFK.asComparison() == DefaultedComparisonKind::Relational) {
DefaultedSecondaryComparisons.push_back(FD);
return true;
}
CheckExplicitlyDefaultedFunction(S, FD);
return false;
};
auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
bool Incomplete = CheckForDefaultedFunction(M);
if (Record->isDependentType())
return;
CXXSpecialMember CSM = getSpecialMember(M);
if (!M->isImplicit() && !M->isUserProvided()) {
if (CSM != CXXInvalid) {
M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Record->finishedDefaultedOrDeletedMember(M);
M->setTrivialForCall(
HasTrivialABI ||
SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
Record->setTrivialForCallFlags(M);
}
}
if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
CSM == CXXDestructor) && M->isUserProvided()) {
M->setTrivialForCall(HasTrivialABI);
Record->setTrivialForCallFlags(M);
}
if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
M->hasAttr<DLLExportAttr>()) {
if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
M->isTrivial() &&
(CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
CSM == CXXDestructor))
M->dropAttr<DLLExportAttr>();
if (M->hasAttr<DLLExportAttr>()) {
DelayedDllExportMemberFunctions.push_back(M);
}
}
if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
DefineDefaultedFunction(*this, M, M->getLocation());
if (!Incomplete)
CheckCompletedMemberFunction(M);
};
if (CXXDestructorDecl *Dtor = Record->getDestructor())
CompleteMemberFunction(Dtor);
bool HasMethodWithOverrideControl = false,
HasOverridingMethodWithoutOverrideControl = false;
for (auto *D : Record->decls()) {
if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
if (!Record->isDependentType()) {
if (!M->isStatic())
DiagnoseHiddenVirtualMethods(M);
if (M->hasAttr<OverrideAttr>())
HasMethodWithOverrideControl = true;
else if (M->size_overridden_methods() > 0)
HasOverridingMethodWithoutOverrideControl = true;
}
if (!isa<CXXDestructorDecl>(M))
CompleteMemberFunction(M);
} else if (auto *F = dyn_cast<FriendDecl>(D)) {
CheckForDefaultedFunction(
dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
}
}
if (HasOverridingMethodWithoutOverrideControl) {
bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
for (auto *M : Record->methods())
DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
}
for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
CheckExplicitlyDefaultedFunction(S, FD);
if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
CheckCompletedMemberFunction(MD);
}
if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
(Record->isPolymorphic() || Record->getNumBases())) {
Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
}
checkClassLevelDLLAttribute(Record);
checkClassLevelCodeSegAttribute(Record);
bool ClangABICompat4 =
Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
TargetInfo::CallingConvKind CCK =
Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
bool CanPass = canPassInRegisters(*this, Record, CCK);
if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
Record->setArgPassingRestrictions(CanPass
? RecordDecl::APK_CanPassInRegs
: RecordDecl::APK_CannotPassInRegs);
if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
Record->setParamDestroyedInCallee(true);
else if (Record->hasNonTrivialDestructor())
Record->setParamDestroyedInCallee(CanPass);
if (getLangOpts().ForceEmitVTables) {
MarkVTableUsed(Record->getInnerLocStart(), Record);
}
if (getLangOpts().CUDA) {
if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
}
}
static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
unsigned FieldQuals, bool ConstRHS) {
unsigned LHSQuals = 0;
if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
LHSQuals = FieldQuals;
unsigned RHSQuals = FieldQuals;
if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
RHSQuals = 0;
else if (ConstRHS)
RHSQuals |= Qualifiers::Const;
return S.LookupSpecialMember(Class, CSM,
RHSQuals & Qualifiers::Const,
RHSQuals & Qualifiers::Volatile,
false,
LHSQuals & Qualifiers::Const,
LHSQuals & Qualifiers::Volatile);
}
class Sema::InheritedConstructorInfo {
Sema &S;
SourceLocation UseLoc;
llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
InheritedFromBases;
public:
InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
ConstructorUsingShadowDecl *Shadow)
: S(S), UseLoc(UseLoc) {
bool DiagnosedMultipleConstructedBases = false;
CXXRecordDecl *ConstructedBase = nullptr;
BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
for (auto *D : Shadow->redecls()) {
auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
auto *DNominatedBase = DShadow->getNominatedBaseClass();
auto *DConstructedBase = DShadow->getConstructedBaseClass();
InheritedFromBases.insert(
std::make_pair(DNominatedBase->getCanonicalDecl(),
DShadow->getNominatedBaseClassShadowDecl()));
if (DShadow->constructsVirtualBase())
InheritedFromBases.insert(
std::make_pair(DConstructedBase->getCanonicalDecl(),
DShadow->getConstructedBaseClassShadowDecl()));
else
assert(DNominatedBase == DConstructedBase);
if (!ConstructedBase) {
ConstructedBase = DConstructedBase;
ConstructedBaseIntroducer = D->getIntroducer();
} else if (ConstructedBase != DConstructedBase &&
!Shadow->isInvalidDecl()) {
if (!DiagnosedMultipleConstructedBases) {
S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
<< Shadow->getTargetDecl();
S.Diag(ConstructedBaseIntroducer->getLocation(),
diag::note_ambiguous_inherited_constructor_using)
<< ConstructedBase;
DiagnosedMultipleConstructedBases = true;
}
S.Diag(D->getIntroducer()->getLocation(),
diag::note_ambiguous_inherited_constructor_using)
<< DConstructedBase;
}
}
if (DiagnosedMultipleConstructedBases)
Shadow->setInvalidDecl();
}
std::pair<CXXConstructorDecl *, bool>
findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
auto It = InheritedFromBases.find(Base->getCanonicalDecl());
if (It == InheritedFromBases.end())
return std::make_pair(nullptr, false);
if (It->second)
return std::make_pair(
S.findInheritingConstructor(UseLoc, Ctor, It->second),
It->second->constructsVirtualBase());
return std::make_pair(Ctor, false);
}
};
static bool
specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
Sema::CXXSpecialMember CSM, unsigned Quals,
bool ConstRHS,
CXXConstructorDecl *InheritedCtor = nullptr,
Sema::InheritedConstructorInfo *Inherited = nullptr) {
if (InheritedCtor) {
assert(CSM == Sema::CXXDefaultConstructor);
auto BaseCtor =
Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
if (BaseCtor)
return BaseCtor->isConstexpr();
}
if (CSM == Sema::CXXDefaultConstructor)
return ClassDecl->hasConstexprDefaultConstructor();
if (CSM == Sema::CXXDestructor)
return ClassDecl->hasConstexprDestructor();
Sema::SpecialMemberOverloadResult SMOR =
lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
if (!SMOR.getMethod())
return true;
return SMOR.getMethod()->isConstexpr();
}
static bool defaultedSpecialMemberIsConstexpr(
Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
Sema::InheritedConstructorInfo *Inherited = nullptr) {
if (!S.getLangOpts().CPlusPlus11)
return false;
bool Ctor = true;
switch (CSM) {
case Sema::CXXDefaultConstructor:
if (Inherited)
break;
return ClassDecl->defaultedDefaultConstructorIsConstexpr();
case Sema::CXXCopyConstructor:
case Sema::CXXMoveConstructor:
break;
case Sema::CXXCopyAssignment:
case Sema::CXXMoveAssignment:
if (!S.getLangOpts().CPlusPlus14)
return false;
Ctor = false;
break;
case Sema::CXXDestructor:
return ClassDecl->defaultedDestructorIsConstexpr();
case Sema::CXXInvalid:
return false;
}
if (Ctor && ClassDecl->isUnion())
return CSM == Sema::CXXDefaultConstructor
? ClassDecl->hasInClassInitializer() ||
!ClassDecl->hasVariantMembers()
: true;
if (Ctor && ClassDecl->getNumVBases())
return false;
if (!Ctor && !ClassDecl->isLiteral())
return false;
for (const auto &B : ClassDecl->bases()) {
const RecordType *BaseType = B.getType()->getAs<RecordType>();
if (!BaseType) continue;
CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
InheritedCtor, Inherited))
return false;
}
for (const auto *F : ClassDecl->fields()) {
if (F->isInvalidDecl())
continue;
if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
continue;
QualType BaseType = S.Context.getBaseElementType(F->getType());
if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
BaseType.getCVRQualifiers(),
ConstArg && !F->isMutable()))
return false;
} else if (CSM == Sema::CXXDefaultConstructor) {
return false;
}
}
return true;
}
namespace {
struct ComputingExceptionSpec {
Sema &S;
ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
: S(S) {
Sema::CodeSynthesisContext Ctx;
Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
Ctx.PointOfInstantiation = Loc;
Ctx.Entity = FD;
S.pushCodeSynthesisContext(Ctx);
}
~ComputingExceptionSpec() {
S.popCodeSynthesisContext();
}
};
}
static Sema::ImplicitExceptionSpecification
ComputeDefaultedSpecialMemberExceptionSpec(
Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
Sema::InheritedConstructorInfo *ICI);
static Sema::ImplicitExceptionSpecification
ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
FunctionDecl *FD,
Sema::DefaultedComparisonKind DCK);
static Sema::ImplicitExceptionSpecification
computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
auto DFK = S.getDefaultedFunctionKind(FD);
if (DFK.isSpecialMember())
return ComputeDefaultedSpecialMemberExceptionSpec(
S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
if (DFK.isComparison())
return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
DFK.asComparison());
auto *CD = cast<CXXConstructorDecl>(FD);
assert(CD->getInheritedConstructor() &&
"only defaulted functions and inherited constructors have implicit "
"exception specs");
Sema::InheritedConstructorInfo ICI(
S, Loc, CD->getInheritedConstructor().getShadowDecl());
return ComputeDefaultedSpecialMemberExceptionSpec(
S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
}
static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
CXXMethodDecl *MD) {
FunctionProtoType::ExtProtoInfo EPI;
EPI.ExceptionSpec.Type = EST_Unevaluated;
EPI.ExceptionSpec.SourceDecl = MD;
EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
S.Context.getDefaultCallingConvention(false,
true));
return EPI;
}
void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
if (FPT->getExceptionSpecType() != EST_Unevaluated)
return;
auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
auto ESI = IES.getExceptionSpec();
UpdateExceptionSpec(FD, ESI);
}
void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
if (!DefKind) {
assert(FD->getDeclContext()->isDependentContext());
return;
}
if (DefKind.isComparison())
UnusedPrivateFields.clear();
if (DefKind.isSpecialMember()
? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
DefKind.asSpecialMember())
: CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
FD->setInvalidDecl();
}
bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
CXXSpecialMember CSM) {
CXXRecordDecl *RD = MD->getParent();
assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
"not an explicitly-defaulted special member");
if (RD->isDependentType())
return false;
bool First = MD == MD->getCanonicalDecl();
bool HadError = false;
bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
bool ShouldDeleteForTypeMismatch = false;
unsigned ExpectedParams = 1;
if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
ExpectedParams = 0;
if (MD->getNumParams() != ExpectedParams) {
Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
<< CSM << MD->getSourceRange();
HadError = true;
} else if (MD->isVariadic()) {
if (DeleteOnTypeMismatch)
ShouldDeleteForTypeMismatch = true;
else {
Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
<< CSM << MD->getSourceRange();
HadError = true;
}
}
const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
bool CanHaveConstParam = false;
if (CSM == CXXCopyConstructor)
CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
else if (CSM == CXXCopyAssignment)
CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
QualType ReturnType = Context.VoidTy;
if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
ReturnType = Type->getReturnType();
QualType DeclType = Context.getTypeDeclType(RD);
DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
<< (CSM == CXXMoveAssignment) << ExpectedReturnType;
HadError = true;
}
if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
if (DeleteOnTypeMismatch)
ShouldDeleteForTypeMismatch = true;
else {
Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
<< (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
HadError = true;
}
}
}
QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
bool HasConstParam = false;
if (ExpectedParams && ArgType->isReferenceType()) {
QualType ReferentType = ArgType->getPointeeType();
HasConstParam = ReferentType.isConstQualified();
if (ReferentType.isVolatileQualified()) {
if (DeleteOnTypeMismatch)
ShouldDeleteForTypeMismatch = true;
else {
Diag(MD->getLocation(),
diag::err_defaulted_special_member_volatile_param) << CSM;
HadError = true;
}
}
if (HasConstParam && !CanHaveConstParam) {
if (DeleteOnTypeMismatch)
ShouldDeleteForTypeMismatch = true;
else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
Diag(MD->getLocation(),
diag::err_defaulted_special_member_copy_const_param)
<< (CSM == CXXCopyAssignment);
HadError = true;
} else {
Diag(MD->getLocation(),
diag::err_defaulted_special_member_move_const_param)
<< (CSM == CXXMoveAssignment);
HadError = true;
}
}
} else if (ExpectedParams) {
assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
HadError = true;
}
bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
HasConstParam);
if ((getLangOpts().CPlusPlus20 ||
(getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
: isa<CXXConstructorDecl>(MD))) &&
MD->isConstexpr() && !Constexpr &&
MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Diag(MD->getBeginLoc(), MD->isConsteval()
? diag::err_incorrect_defaulted_consteval
: diag::err_incorrect_defaulted_constexpr)
<< CSM;
HadError = true;
}
if (First) {
MD->setConstexprKind(Constexpr ? (MD->isConsteval()
? ConstexprSpecKind::Consteval
: ConstexprSpecKind::Constexpr)
: ConstexprSpecKind::Unspecified);
if (!Type->hasExceptionSpec()) {
FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
EPI.ExceptionSpec.Type = EST_Unevaluated;
EPI.ExceptionSpec.SourceDecl = MD;
MD->setType(Context.getFunctionType(ReturnType,
llvm::makeArrayRef(&ArgType,
ExpectedParams),
EPI));
}
}
if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
if (First) {
SetDeclDeleted(MD, MD->getLocation());
if (!inTemplateInstantiation() && !HadError) {
Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
if (ShouldDeleteForTypeMismatch) {
Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
} else {
ShouldDeleteSpecialMember(MD, CSM, nullptr, true);
}
}
if (ShouldDeleteForTypeMismatch && !HadError) {
Diag(MD->getLocation(),
diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
}
} else {
Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
ShouldDeleteSpecialMember(MD, CSM, nullptr, true);
HadError = true;
}
}
return HadError;
}
namespace {
template<typename Derived, typename ResultList, typename Result,
typename Subobject>
class DefaultedComparisonVisitor {
public:
using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
DefaultedComparisonKind DCK)
: S(S), RD(RD), FD(FD), DCK(DCK) {
if (auto *Info = FD->getDefaultedFunctionInfo()) {
Fns.assign(Info->getUnqualifiedLookups().begin(),
Info->getUnqualifiedLookups().end());
}
}
ResultList visit() {
QualType ParamLvalType =
FD->getParamDecl(0)->getType().getNonReferenceType();
ResultList Results;
switch (DCK) {
case DefaultedComparisonKind::None:
llvm_unreachable("not a defaulted comparison");
case DefaultedComparisonKind::Equal:
case DefaultedComparisonKind::ThreeWay:
getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
return Results;
case DefaultedComparisonKind::NotEqual:
case DefaultedComparisonKind::Relational:
Results.add(getDerived().visitExpandedSubobject(
ParamLvalType, getDerived().getCompleteObject()));
return Results;
}
llvm_unreachable("");
}
protected:
Derived &getDerived() { return static_cast<Derived&>(*this); }
bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
Qualifiers Quals) {
for (CXXBaseSpecifier &Base : Record->bases())
if (Results.add(getDerived().visitSubobject(
S.Context.getQualifiedType(Base.getType(), Quals),
getDerived().getBase(&Base))))
return true;
for (FieldDecl *Field : Record->fields()) {
if (Field->isAnonymousStructOrUnion()) {
if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
Quals))
return true;
continue;
}
Qualifiers FieldQuals = Quals;
if (Field->isMutable())
FieldQuals.removeConst();
QualType FieldType =
S.Context.getQualifiedType(Field->getType(), FieldQuals);
if (Results.add(getDerived().visitSubobject(
FieldType, getDerived().getField(Field))))
return true;
}
return false;
}
Result visitSubobject(QualType Type, Subobject Subobj) {
const ArrayType *AT = S.Context.getAsArrayType(Type);
if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
return getDerived().visitSubobjectArray(CAT->getElementType(),
CAT->getSize(), Subobj);
return getDerived().visitExpandedSubobject(Type, Subobj);
}
Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
Subobject Subobj) {
return getDerived().visitSubobject(Type, Subobj);
}
protected:
Sema &S;
CXXRecordDecl *RD;
FunctionDecl *FD;
DefaultedComparisonKind DCK;
UnresolvedSet<16> Fns;
};
struct DefaultedComparisonInfo {
bool Deleted = false;
bool Constexpr = true;
ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
static DefaultedComparisonInfo deleted() {
DefaultedComparisonInfo Deleted;
Deleted.Deleted = true;
return Deleted;
}
bool add(const DefaultedComparisonInfo &R) {
Deleted |= R.Deleted;
Constexpr &= R.Constexpr;
Category = commonComparisonType(Category, R.Category);
return Deleted;
}
};
struct DefaultedComparisonSubobject {
enum { CompleteObject, Member, Base } Kind;
NamedDecl *Decl;
SourceLocation Loc;
};
class DefaultedComparisonAnalyzer
: public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
DefaultedComparisonInfo,
DefaultedComparisonInfo,
DefaultedComparisonSubobject> {
public:
enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
private:
DiagnosticKind Diagnose;
public:
using Base = DefaultedComparisonVisitor;
using Result = DefaultedComparisonInfo;
using Subobject = DefaultedComparisonSubobject;
friend Base;
DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
DefaultedComparisonKind DCK,
DiagnosticKind Diagnose = NoDiagnostics)
: Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
Result visit() {
if ((DCK == DefaultedComparisonKind::Equal ||
DCK == DefaultedComparisonKind::ThreeWay) &&
RD->hasVariantMembers()) {
if (Diagnose == ExplainDeleted) {
S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
<< FD << RD->isUnion() << RD;
}
return Result::deleted();
}
return Base::visit();
}
private:
Subobject getCompleteObject() {
return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
}
Subobject getBase(CXXBaseSpecifier *Base) {
return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
Base->getBaseTypeLoc()};
}
Subobject getField(FieldDecl *Field) {
return Subobject{Subobject::Member, Field, Field->getLocation()};
}
Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
if (Type->isReferenceType()) {
if (Diagnose == ExplainDeleted) {
S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
<< FD << RD;
}
return Result::deleted();
}
OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
Expr *Args[] = {&Xi, &Xi};
OverloadedOperatorKind OO = FD->getOverloadedOperator();
assert(OO != OO_None && "not an overloaded operator!");
return visitBinaryOperator(OO, Args, Subobj);
}
Result
visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
Subobject Subobj,
OverloadCandidateSet *SpaceshipCandidates = nullptr) {
OverloadCandidateSet CandidateSet(
FD->getLocation(), OverloadCandidateSet::CSK_Operator,
OverloadCandidateSet::OperatorRewriteInfo(
OO, !SpaceshipCandidates));
CandidateSet.exclude(FD);
if (Args[0]->getType()->isOverloadableType())
S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
else
S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
Result R;
OverloadCandidateSet::iterator Best;
switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
case OR_Success: {
if ((DCK == DefaultedComparisonKind::NotEqual ||
DCK == DefaultedComparisonKind::Relational) &&
!Best->RewriteKind) {
if (Diagnose == ExplainDeleted) {
if (Best->Function) {
S.Diag(Best->Function->getLocation(),
diag::note_defaulted_comparison_not_rewritten_callee)
<< FD;
} else {
assert(Best->Conversions.size() == 2 &&
Best->Conversions[0].isUserDefined() &&
"non-user-defined conversion from class to built-in "
"comparison");
S.Diag(Best->Conversions[0]
.UserDefined.FoundConversionFunction.getDecl()
->getLocation(),
diag::note_defaulted_comparison_not_rewritten_conversion)
<< FD;
}
}
return Result::deleted();
}
CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
if (ArgClass && Best->FoundDecl.getDecl() &&
Best->FoundDecl.getDecl()->isCXXClassMember()) {
QualType ObjectType = Subobj.Kind == Subobject::Member
? Args[0]->getType()
: S.Context.getRecordType(RD);
if (!S.isMemberAccessibleForDeletion(
ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
Diagnose == ExplainDeleted
? S.PDiag(diag::note_defaulted_comparison_inaccessible)
<< FD << Subobj.Kind << Subobj.Decl
: S.PDiag()))
return Result::deleted();
}
bool NeedsDeducing =
OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
if (FunctionDecl *BestFD = Best->Function) {
assert(!BestFD->isDeleted() && "wrong overload resolution result");
if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
if (Subobj.Kind != Subobject::CompleteObject)
S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
<< Subobj.Kind << Subobj.Decl;
S.Diag(BestFD->getLocation(),
diag::note_defaulted_comparison_not_constexpr_here);
return Result::deleted();
}
R.Constexpr &= BestFD->isConstexpr();
if (NeedsDeducing) {
if (BestFD->getReturnType()->isUndeducedType() &&
S.DeduceReturnType(BestFD, FD->getLocation(),
false)) {
if (Diagnose == NoDiagnostics) {
S.Diag(
FD->getLocation(),
diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
<< Subobj.Kind << Subobj.Decl;
S.Diag(
Subobj.Loc,
diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
<< Subobj.Kind << Subobj.Decl;
S.Diag(BestFD->getLocation(),
diag::note_defaulted_comparison_cannot_deduce_callee)
<< Subobj.Kind << Subobj.Decl;
}
return Result::deleted();
}
auto *Info = S.Context.CompCategories.lookupInfoForType(
BestFD->getCallResultType());
if (!Info) {
if (Diagnose == ExplainDeleted) {
S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
<< Subobj.Kind << Subobj.Decl
<< BestFD->getCallResultType().withoutLocalFastQualifiers();
S.Diag(BestFD->getLocation(),
diag::note_defaulted_comparison_cannot_deduce_callee)
<< Subobj.Kind << Subobj.Decl;
}
return Result::deleted();
}
R.Category = Info->Kind;
}
} else {
QualType T = Best->BuiltinParamTypes[0];
assert(T == Best->BuiltinParamTypes[1] &&
"builtin comparison for different types?");
assert(Best->BuiltinParamTypes[2].isNull() &&
"invalid builtin comparison");
if (NeedsDeducing) {
Optional<ComparisonCategoryType> Cat =
getComparisonCategoryForBuiltinCmp(T);
assert(Cat && "no category for builtin comparison?");
R.Category = *Cat;
}
}
break;
}
case OR_Ambiguous:
if (Diagnose == ExplainDeleted) {
unsigned Kind = 0;
if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
Kind = OO == OO_EqualEqual ? 1 : 2;
CandidateSet.NoteCandidates(
PartialDiagnosticAt(
Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
<< FD << Kind << Subobj.Kind << Subobj.Decl),
S, OCD_AmbiguousCandidates, Args);
}
R = Result::deleted();
break;
case OR_Deleted:
if (Diagnose == ExplainDeleted) {
if ((DCK == DefaultedComparisonKind::NotEqual ||
DCK == DefaultedComparisonKind::Relational) &&
!Best->RewriteKind) {
S.Diag(Best->Function->getLocation(),
diag::note_defaulted_comparison_not_rewritten_callee)
<< FD;
} else {
S.Diag(Subobj.Loc,
diag::note_defaulted_comparison_calls_deleted)
<< FD << Subobj.Kind << Subobj.Decl;
S.NoteDeletedFunction(Best->Function);
}
}
R = Result::deleted();
break;
case OR_No_Viable_Function:
if (OO == OO_Spaceship &&
S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
&CandidateSet)))
R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
break;
}
if (Diagnose == ExplainDeleted) {
S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
<< FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl;
if (SpaceshipCandidates) {
SpaceshipCandidates->NoteCandidates(
S, Args,
SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
Args, FD->getLocation()));
S.Diag(Subobj.Loc,
diag::note_defaulted_comparison_no_viable_function_synthesized)
<< (OO == OO_EqualEqual ? 0 : 1);
}
CandidateSet.NoteCandidates(
S, Args,
CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
FD->getLocation()));
}
R = Result::deleted();
break;
}
return R;
}
};
struct StmtListResult {
bool IsInvalid = false;
llvm::SmallVector<Stmt*, 16> Stmts;
bool add(const StmtResult &S) {
IsInvalid |= S.isInvalid();
if (IsInvalid)
return true;
Stmts.push_back(S.get());
return false;
}
};
class DefaultedComparisonSynthesizer
: public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
StmtListResult, StmtResult,
std::pair<ExprResult, ExprResult>> {
SourceLocation Loc;
unsigned ArrayDepth = 0;
public:
using Base = DefaultedComparisonVisitor;
using ExprPair = std::pair<ExprResult, ExprResult>;
friend Base;
DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
DefaultedComparisonKind DCK,
SourceLocation BodyLoc)
: Base(S, RD, FD, DCK), Loc(BodyLoc) {}
StmtResult build() {
Sema::CompoundScopeRAII CompoundScope(S);
StmtListResult Stmts = visit();
if (Stmts.IsInvalid)
return StmtError();
ExprResult RetVal;
switch (DCK) {
case DefaultedComparisonKind::None:
llvm_unreachable("not a defaulted comparison");
case DefaultedComparisonKind::Equal: {
auto OldStmts = std::move(Stmts.Stmts);
Stmts.Stmts.clear();
ExprResult CmpSoFar;
auto FinishCmp = [&] {
if (Expr *Prior = CmpSoFar.get()) {
if (RetVal.isUnset() && Stmts.Stmts.empty())
RetVal = CmpSoFar;
else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
return true;
CmpSoFar = ExprResult();
}
return false;
};
for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
Expr *E = dyn_cast<Expr>(EAsStmt);
if (!E) {
if (FinishCmp() || Stmts.add(EAsStmt))
return StmtError();
continue;
}
if (CmpSoFar.isUnset()) {
CmpSoFar = E;
continue;
}
CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
if (CmpSoFar.isInvalid())
return StmtError();
}
if (FinishCmp())
return StmtError();
std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
if (RetVal.isUnset())
RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
break;
}
case DefaultedComparisonKind::ThreeWay: {
QualType StrongOrdering = S.CheckComparisonCategoryType(
ComparisonCategoryType::StrongOrdering, Loc,
Sema::ComparisonCategoryUsage::DefaultedOperator);
if (StrongOrdering.isNull())
return StmtError();
VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
.getValueInfo(ComparisonCategoryResult::Equal)
->VD;
RetVal = getDecl(EqualVD);
if (RetVal.isInvalid())
return StmtError();
RetVal = buildStaticCastToR(RetVal.get());
break;
}
case DefaultedComparisonKind::NotEqual:
case DefaultedComparisonKind::Relational:
RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
break;
}
if (RetVal.isInvalid())
return StmtError();
StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
if (ReturnStmt.isInvalid())
return StmtError();
Stmts.Stmts.push_back(ReturnStmt.get());
return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, false);
}
private:
ExprResult getDecl(ValueDecl *VD) {
return S.BuildDeclarationNameExpr(
CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
}
ExprResult getParam(unsigned I) {
ParmVarDecl *PD = FD->getParamDecl(I);
return getDecl(PD);
}
ExprPair getCompleteObject() {
unsigned Param = 0;
ExprResult LHS;
if (isa<CXXMethodDecl>(FD)) {
LHS = S.ActOnCXXThis(Loc);
if (!LHS.isInvalid())
LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
} else {
LHS = getParam(Param++);
}
ExprResult RHS = getParam(Param++);
assert(Param == FD->getNumParams());
return {LHS, RHS};
}
ExprPair getBase(CXXBaseSpecifier *Base) {
ExprPair Obj = getCompleteObject();
if (Obj.first.isInvalid() || Obj.second.isInvalid())
return {ExprError(), ExprError()};
CXXCastPath Path = {Base};
return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
CK_DerivedToBase, VK_LValue, &Path),
S.ImpCastExprToType(Obj.second.get(), Base->getType(),
CK_DerivedToBase, VK_LValue, &Path)};
}
ExprPair getField(FieldDecl *Field) {
ExprPair Obj = getCompleteObject();
if (Obj.first.isInvalid() || Obj.second.isInvalid())
return {ExprError(), ExprError()};
DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
return {S.BuildFieldReferenceExpr(Obj.first.get(), false, Loc,
CXXScopeSpec(), Field, Found, NameInfo),
S.BuildFieldReferenceExpr(Obj.second.get(), false, Loc,
CXXScopeSpec(), Field, Found, NameInfo)};
}
StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
if (Cond.isInvalid())
return StmtError();
ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
if (NotCond.isInvalid())
return StmtError();
ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
assert(!False.isInvalid() && "should never fail");
StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
if (ReturnFalse.isInvalid())
return StmtError();
return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
S.ActOnCondition(nullptr, Loc, NotCond.get(),
Sema::ConditionKind::Boolean),
Loc, ReturnFalse.get(), SourceLocation(), nullptr);
}
StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
ExprPair Subobj) {
QualType SizeType = S.Context.getSizeType();
Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
IdentifierInfo *IterationVarName = nullptr;
{
SmallString<8> Str;
llvm::raw_svector_ostream OS(Str);
OS << "i" << ArrayDepth;
IterationVarName = &S.Context.Idents.get(OS.str());
}
VarDecl *IterationVar = VarDecl::Create(
S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
IterationVar->setInit(
IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
auto IterRef = [&] {
ExprResult Ref = S.BuildDeclarationNameExpr(
CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
IterationVar);
assert(!Ref.isInvalid() && "can't reference our own variable?");
return Ref.get();
};
ExprResult Cond = S.CreateBuiltinBinOp(
Loc, BO_NE, IterRef(),
IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
assert(!Cond.isInvalid() && "should never fail");
ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
assert(!Inc.isInvalid() && "should never fail");
auto Index = [&](ExprResult E) {
if (E.isInvalid())
return ExprError();
return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
};
Subobj.first = Index(Subobj.first);
Subobj.second = Index(Subobj.second);
++ArrayDepth;
StmtResult Substmt = visitSubobject(Type, Subobj);
--ArrayDepth;
if (Substmt.isInvalid())
return StmtError();
if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
assert(DCK == DefaultedComparisonKind::Equal &&
"should have non-expression statement");
Substmt = buildIfNotCondReturnFalse(ElemCmp);
if (Substmt.isInvalid())
return StmtError();
}
return S.ActOnForStmt(Loc, Loc, Init,
S.ActOnCondition(nullptr, Loc, Cond.get(),
Sema::ConditionKind::Boolean),
S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
Substmt.get());
}
StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
if (Obj.first.isInvalid() || Obj.second.isInvalid())
return StmtError();
OverloadedOperatorKind OO = FD->getOverloadedOperator();
BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
ExprResult Op;
if (Type->isOverloadableType())
Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
Obj.second.get(), true,
true, FD);
else
Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
if (Op.isInvalid())
return StmtError();
switch (DCK) {
case DefaultedComparisonKind::None:
llvm_unreachable("not a defaulted comparison");
case DefaultedComparisonKind::Equal:
Op = S.PerformContextuallyConvertToBool(Op.get());
if (Op.isInvalid())
return StmtError();
return Op.get();
case DefaultedComparisonKind::ThreeWay: {
QualType R = FD->getReturnType();
Op = buildStaticCastToR(Op.get());
if (Op.isInvalid())
return StmtError();
IdentifierInfo *Name = &S.Context.Idents.get("cmp");
VarDecl *VD =
VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
S.AddInitializerToDecl(VD, Op.get(), false);
Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
ExprResult VDRef = getDecl(VD);
if (VDRef.isInvalid())
return StmtError();
llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
Expr *Zero =
IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
ExprResult Comp;
if (VDRef.get()->getType()->isOverloadableType())
Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
true, FD);
else
Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
if (Comp.isInvalid())
return StmtError();
Sema::ConditionResult Cond = S.ActOnCondition(
nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
if (Cond.isInvalid())
return StmtError();
VDRef = getDecl(VD);
if (VDRef.isInvalid())
return StmtError();
StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
if (ReturnStmt.isInvalid())
return StmtError();
return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
Loc, ReturnStmt.get(),
SourceLocation(), nullptr);
}
case DefaultedComparisonKind::NotEqual:
case DefaultedComparisonKind::Relational:
return Op.get();
}
llvm_unreachable("");
}
ExprResult buildStaticCastToR(Expr *E) {
QualType R = FD->getReturnType();
assert(!R->isUndeducedType() && "type should have been deduced already");
if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
return E;
return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
S.Context.getTrivialTypeSourceInfo(R, Loc), E,
SourceRange(Loc, Loc), SourceRange(Loc, Loc));
}
};
}
static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
UnresolvedSetImpl &Operators,
OverloadedOperatorKind Op) {
auto Lookup = [&](OverloadedOperatorKind OO) {
Self.LookupOverloadedOperatorName(OO, S, Operators);
};
Lookup(Op);
if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
Lookup(ExtraOp);
if (Op == OO_Spaceship) {
Lookup(OO_ExclaimEqual);
Lookup(OO_Less);
Lookup(OO_EqualEqual);
}
}
bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
DefaultedComparisonKind DCK) {
assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
if (S) {
UnresolvedSet<32> Operators;
lookupOperatorsForDefaultedComparison(*this, S, Operators,
FD->getOverloadedOperator());
FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
Context, Operators.pairs()));
}
CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
bool IsMethod = isa<CXXMethodDecl>(FD);
if (IsMethod) {
auto *MD = cast<CXXMethodDecl>(FD);
assert(!MD->isStatic() && "comparison function cannot be a static member");
if (!RD)
RD = MD->getParent();
if (!MD->isConst()) {
SourceLocation InsertLoc;
if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
if (!MD->isImplicit()) {
Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
<< (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
}
const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
EPI.TypeQuals.addConst();
MD->setType(Context.getFunctionType(FPT->getReturnType(),
FPT->getParamTypes(), EPI));
}
}
if (FD->getNumParams() != (IsMethod ? 1 : 2)) {
Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
<< int(IsMethod) << int(DCK);
return true;
}
const ParmVarDecl *KnownParm = nullptr;
for (const ParmVarDecl *Param : FD->parameters()) {
QualType ParmTy = Param->getType();
if (ParmTy->isDependentType())
continue;
if (!KnownParm) {
auto CTy = ParmTy;
bool Ok = !IsMethod;
QualType ExpectedTy;
if (RD)
ExpectedTy = Context.getRecordType(RD);
if (auto *Ref = CTy->getAs<ReferenceType>()) {
CTy = Ref->getPointeeType();
if (RD)
ExpectedTy.addConst();
Ok = true;
}
if (!Ok) {
} else if (RD) {
if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
Ok = false;
} else if (auto *CRD = CTy->getAsRecordDecl()) {
RD = cast<CXXRecordDecl>(CRD);
} else {
Ok = false;
}
if (Ok) {
KnownParm = Param;
} else {
if (!FD->isImplicit()) {
if (RD) {
QualType PlainTy = Context.getRecordType(RD);
QualType RefTy =
Context.getLValueReferenceType(PlainTy.withConst());
Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
<< int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
<< Param->getSourceRange();
} else {
assert(!IsMethod && "should know expected type for method");
Diag(FD->getLocation(),
diag::err_defaulted_comparison_param_unknown)
<< int(DCK) << ParmTy << Param->getSourceRange();
}
}
return true;
}
} else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
<< int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
<< ParmTy << Param->getSourceRange();
return true;
}
}
assert(RD && "must have determined class");
if (IsMethod) {
} else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
assert(FD->getFriendObjectKind() && "expected a friend declaration");
} else {
if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
diag::err_defaulted_comparison_not_friend, int(DCK),
int(1)))
return true;
if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
return FD->getCanonicalDecl() ==
F->getFriendDecl()->getCanonicalDecl();
})) {
Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
<< int(DCK) << int(0) << RD;
Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
return true;
}
}
if (DCK != DefaultedComparisonKind::ThreeWay &&
!FD->getDeclaredReturnType()->isDependentType() &&
!Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
<< (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
<< FD->getReturnTypeSourceRange();
return true;
}
if (DCK == DefaultedComparisonKind::ThreeWay &&
FD->getDeclaredReturnType()->getContainedDeducedType() &&
!Context.hasSameType(FD->getDeclaredReturnType(),
Context.getAutoDeductType())) {
Diag(FD->getLocation(),
diag::err_defaulted_comparison_deduced_return_type_not_auto)
<< (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
<< FD->getReturnTypeSourceRange();
return true;
}
if (RD->isDependentType())
return false;
DefaultedComparisonInfo Info =
DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
bool First = FD == FD->getCanonicalDecl();
if (Info.Deleted) {
if (!First) {
Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
<< FD->isImplicit() << (int)DCK;
DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
DefaultedComparisonAnalyzer::ExplainDeleted)
.visit();
return true;
}
SetDeclDeleted(FD, FD->getLocation());
if (!inTemplateInstantiation() && !FD->isImplicit()) {
Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
<< (int)DCK;
DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
DefaultedComparisonAnalyzer::ExplainDeleted)
.visit();
}
return false;
}
if (DCK == DefaultedComparisonKind::ThreeWay &&
FD->getDeclaredReturnType()->isUndeducedAutoType()) {
SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
if (RetLoc.isInvalid())
RetLoc = FD->getBeginLoc();
QualType Cat = CheckComparisonCategoryType(
Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
if (Cat.isNull())
return true;
Context.adjustDeducedFunctionResultType(
FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
}
if (FD->isConstexpr()) {
if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
!Info.Constexpr) {
Diag(FD->getBeginLoc(),
diag::err_incorrect_defaulted_comparison_constexpr)
<< FD->isImplicit() << (int)DCK << FD->isConsteval();
DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
DefaultedComparisonAnalyzer::ExplainConstexpr)
.visit();
}
}
if (First && !FD->isConstexpr() && Info.Constexpr)
FD->setConstexprKind(ConstexprSpecKind::Constexpr);
if (FD->getExceptionSpecType() == EST_None) {
auto *FPT = FD->getType()->castAs<FunctionProtoType>();
FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
EPI.ExceptionSpec.Type = EST_Unevaluated;
EPI.ExceptionSpec.SourceDecl = FD;
FD->setType(Context.getFunctionType(FPT->getReturnType(),
FPT->getParamTypes(), EPI));
}
return false;
}
void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
FunctionDecl *Spaceship) {
Sema::CodeSynthesisContext Ctx;
Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
Ctx.PointOfInstantiation = Spaceship->getEndLoc();
Ctx.Entity = Spaceship;
pushCodeSynthesisContext(Ctx);
if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
EqualEqual->setImplicit();
popCodeSynthesisContext();
}
void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
DefaultedComparisonKind DCK) {
assert(FD->isDefaulted() && !FD->isDeleted() &&
!FD->doesThisDeclarationHaveABody());
if (FD->willHaveBody() || FD->isInvalidDecl())
return;
SynthesizedFunctionScope Scope(*this, FD);
Scope.addContextNote(UseLoc);
{
auto PT = FD->getParamDecl(0)->getType();
CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
SourceLocation BodyLoc =
FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
StmtResult Body =
DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
if (Body.isInvalid()) {
FD->setInvalidDecl();
return;
}
FD->setBody(Body.get());
FD->markUsed(Context);
}
ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
if (ASTMutationListener *L = getASTMutationListener())
L->CompletedImplicitDefinition(FD);
}
static Sema::ImplicitExceptionSpecification
ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
FunctionDecl *FD,
Sema::DefaultedComparisonKind DCK) {
ComputingExceptionSpec CES(S, FD, Loc);
Sema::ImplicitExceptionSpecification ExceptSpec(S);
if (FD->isInvalidDecl())
return ExceptSpec;
if (FD->hasBody()) {
ExceptSpec.CalledStmt(FD->getBody());
} else {
Sema::SynthesizedFunctionScope Scope(S, FD);
EnterExpressionEvaluationContext Context(
S, Sema::ExpressionEvaluationContext::Unevaluated);
CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
SourceLocation BodyLoc =
FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
StmtResult Body =
DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
if (!Body.isInvalid())
ExceptSpec.CalledStmt(Body.get());
}
return ExceptSpec;
}
void Sema::CheckDelayedMemberExceptionSpecs() {
decltype(DelayedOverridingExceptionSpecChecks) Overriding;
decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
for (auto &Check : Overriding)
CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
for (auto &Check : Equivalent)
CheckEquivalentExceptionSpec(Check.second, Check.first);
}
namespace {
template<typename Derived>
struct SpecialMemberVisitor {
Sema &S;
CXXMethodDecl *MD;
Sema::CXXSpecialMember CSM;
Sema::InheritedConstructorInfo *ICI;
bool IsConstructor = false, IsAssignment = false, ConstArg = false;
SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
Sema::InheritedConstructorInfo *ICI)
: S(S), MD(MD), CSM(CSM), ICI(ICI) {
switch (CSM) {
case Sema::CXXDefaultConstructor:
case Sema::CXXCopyConstructor:
case Sema::CXXMoveConstructor:
IsConstructor = true;
break;
case Sema::CXXCopyAssignment:
case Sema::CXXMoveAssignment:
IsAssignment = true;
break;
case Sema::CXXDestructor:
break;
case Sema::CXXInvalid:
llvm_unreachable("invalid special member kind");
}
if (MD->getNumParams()) {
if (const ReferenceType *RT =
MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
ConstArg = RT->getPointeeType().isConstQualified();
}
}
Derived &getDerived() { return static_cast<Derived&>(*this); }
bool isMove() const {
return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
}
Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
unsigned Quals, bool IsMutable) {
return lookupCallFromSpecialMember(S, Class, CSM, Quals,
ConstArg && !IsMutable);
}
Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
if (!ICI)
return {};
assert(CSM == Sema::CXXDefaultConstructor);
auto *BaseCtor =
cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
return MD;
return {};
}
typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
static SourceLocation getSubobjectLoc(Subobject Subobj) {
if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
return B->getBaseTypeLoc();
else
return Subobj.get<FieldDecl*>()->getLocation();
}
enum BasesToVisit {
VisitNonVirtualBases,
VisitDirectBases,
VisitPotentiallyConstructedBases,
VisitAllBases
};
bool visit(BasesToVisit Bases) {
CXXRecordDecl *RD = MD->getParent();
if (Bases == VisitPotentiallyConstructedBases)
Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
for (auto &B : RD->bases())
if ((Bases == VisitDirectBases || !B.isVirtual()) &&
getDerived().visitBase(&B))
return true;
if (Bases == VisitAllBases)
for (auto &B : RD->vbases())
if (getDerived().visitBase(&B))
return true;
for (auto *F : RD->fields())
if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
getDerived().visitField(F))
return true;
return false;
}
};
}
namespace {
struct SpecialMemberDeletionInfo
: SpecialMemberVisitor<SpecialMemberDeletionInfo> {
bool Diagnose;
SourceLocation Loc;
bool AllFieldsAreConst;
SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Sema::CXXSpecialMember CSM,
Sema::InheritedConstructorInfo *ICI, bool Diagnose)
: SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
Loc(MD->getLocation()), AllFieldsAreConst(true) {}
bool inUnion() const { return MD->getParent()->isUnion(); }
Sema::CXXSpecialMember getEffectiveCSM() {
return ICI ? Sema::CXXInvalid : CSM;
}
bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
bool shouldDeleteForBase(CXXBaseSpecifier *Base);
bool shouldDeleteForField(FieldDecl *FD);
bool shouldDeleteForAllConstMembers();
bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
unsigned Quals);
bool shouldDeleteForSubobjectCall(Subobject Subobj,
Sema::SpecialMemberOverloadResult SMOR,
bool IsDtorCallInCtor);
bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
};
}
bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
CXXMethodDecl *target) {
QualType objectTy;
AccessSpecifier access = target->getAccess();
if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
objectTy = S.Context.getTypeDeclType(MD->getParent());
access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
} else {
objectTy = S.Context.getTypeDeclType(target->getParent());
}
return S.isMemberAccessibleForDeletion(
target->getParent(), DeclAccessPair::make(target, access), objectTy);
}
bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
bool IsDtorCallInCtor) {
CXXMethodDecl *Decl = SMOR.getMethod();
FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
int DiagKind = -1;
if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
DiagKind = !Decl ? 0 : 1;
else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
DiagKind = 2;
else if (!isAccessible(Subobj, Decl))
DiagKind = 3;
else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
!Decl->isTrivial()) {
DiagKind = 4;
}
if (DiagKind == -1)
return false;
if (Diagnose) {
if (Field) {
S.Diag(Field->getLocation(),
diag::note_deleted_special_member_class_subobject)
<< getEffectiveCSM() << MD->getParent() << true
<< Field << DiagKind << IsDtorCallInCtor << false;
} else {
CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
S.Diag(Base->getBeginLoc(),
diag::note_deleted_special_member_class_subobject)
<< getEffectiveCSM() << MD->getParent() << false
<< Base->getType() << DiagKind << IsDtorCallInCtor
<< false;
}
if (DiagKind == 1)
S.NoteDeletedFunction(Decl);
}
return true;
}
bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
bool IsMutable = Field && Field->isMutable();
if (!(CSM == Sema::CXXDefaultConstructor &&
Field && Field->hasInClassInitializer()) &&
shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
false))
return true;
if (IsConstructor) {
Sema::SpecialMemberOverloadResult SMOR =
S.LookupSpecialMember(Class, Sema::CXXDestructor,
false, false, false, false, false);
if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
return true;
}
return false;
}
bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
FieldDecl *FD, QualType FieldType) {
if (!FieldType.hasNonTrivialObjCLifetime())
return false;
if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
return false;
if (Diagnose) {
auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
S.Diag(FD->getLocation(),
diag::note_deleted_special_member_class_subobject)
<< getEffectiveCSM() << ParentClass << true
<< FD << 4 << false << true;
}
return true;
}
bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
if (!BaseClass)
return false;
Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
if (auto *BaseCtor = SMOR.getMethod()) {
if (BaseCtor->isDeleted() && Diagnose) {
S.Diag(Base->getBeginLoc(),
diag::note_deleted_special_member_class_subobject)
<< getEffectiveCSM() << MD->getParent() << false
<< Base->getType() << 1 << false
<< false;
S.NoteDeletedFunction(BaseCtor);
}
return BaseCtor->isDeleted();
}
return shouldDeleteForClassSubobject(BaseClass, Base, 0);
}
bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
QualType FieldType = S.Context.getBaseElementType(FD->getType());
CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
return true;
if (CSM == Sema::CXXDefaultConstructor) {
if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
if (Diagnose)
S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
<< !!ICI << MD->getParent() << FD << FieldType << 0;
return true;
}
if (!inUnion() && FieldType.isConstQualified() &&
!FD->hasInClassInitializer() &&
(!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
if (Diagnose)
S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
<< !!ICI << MD->getParent() << FD << FD->getType() << 1;
return true;
}
if (inUnion() && !FieldType.isConstQualified())
AllFieldsAreConst = false;
} else if (CSM == Sema::CXXCopyConstructor) {
if (FieldType->isRValueReferenceType()) {
if (Diagnose)
S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
<< MD->getParent() << FD << FieldType;
return true;
}
} else if (IsAssignment) {
if (FieldType->isReferenceType()) {
if (Diagnose)
S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
<< isMove() << MD->getParent() << FD << FieldType << 0;
return true;
}
if (!FieldRecord && FieldType.isConstQualified()) {
if (Diagnose)
S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
<< isMove() << MD->getParent() << FD << FD->getType() << 1;
return true;
}
}
if (FieldRecord) {
if (!inUnion() && FieldRecord->isUnion() &&
FieldRecord->isAnonymousStructOrUnion()) {
bool AllVariantFieldsAreConst = true;
for (auto *UI : FieldRecord->fields()) {
QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
return true;
if (!UnionFieldType.isConstQualified())
AllVariantFieldsAreConst = false;
CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
if (UnionFieldRecord &&
shouldDeleteForClassSubobject(UnionFieldRecord, UI,
UnionFieldType.getCVRQualifiers()))
return true;
}
if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
!FieldRecord->field_empty()) {
if (Diagnose)
S.Diag(FieldRecord->getLocation(),
diag::note_deleted_default_ctor_all_const)
<< !!ICI << MD->getParent() << 1;
return true;
}
return false;
}
if (shouldDeleteForClassSubobject(FieldRecord, FD,
FieldType.getCVRQualifiers()))
return true;
}
return false;
}
bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
bool AnyFields = false;
for (auto *F : MD->getParent()->fields())
if ((AnyFields = !F->isUnnamedBitfield()))
break;
if (!AnyFields)
return false;
if (Diagnose)
S.Diag(MD->getParent()->getLocation(),
diag::note_deleted_default_ctor_all_const)
<< !!ICI << MD->getParent() << 0;
return true;
}
return false;
}
bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
InheritedConstructorInfo *ICI,
bool Diagnose) {
if (MD->isInvalidDecl())
return false;
CXXRecordDecl *RD = MD->getParent();
assert(!RD->isDependentType() && "do deletion after instantiation");
if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
return false;
if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
(CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
if (Diagnose)
Diag(RD->getLocation(), diag::note_lambda_decl);
return true;
}
if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
RD->isAnonymousStructOrUnion())
return false;
if (MD->isImplicit() &&
(CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
CXXMethodDecl *UserDeclaredMove = nullptr;
bool DeletesOnlyMatchingCopy =
getLangOpts().MSVCCompat &&
!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
if (RD->hasUserDeclaredMoveConstructor() &&
(!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
if (!Diagnose) return true;
for (auto *I : RD->ctors()) {
if (I->isMoveConstructor()) {
UserDeclaredMove = I;
break;
}
}
assert(UserDeclaredMove);
} else if (RD->hasUserDeclaredMoveAssignment() &&
(!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
if (!Diagnose) return true;
for (auto *I : RD->methods()) {
if (I->isMoveAssignmentOperator()) {
UserDeclaredMove = I;
break;
}
}
assert(UserDeclaredMove);
}
if (UserDeclaredMove) {
Diag(UserDeclaredMove->getLocation(),
diag::note_deleted_copy_user_declared_move)
<< (CSM == CXXCopyAssignment) << RD
<< UserDeclaredMove->isMoveAssignmentOperator();
return true;
}
}
ContextRAII MethodContext(*this, MD);
if (CSM == CXXDestructor && MD->isVirtual()) {
FunctionDecl *OperatorDelete = nullptr;
DeclarationName Name =
Context.DeclarationNames.getCXXOperatorName(OO_Delete);
if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
OperatorDelete, false)) {
if (Diagnose)
Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
return true;
}
}
SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
: SMI.VisitPotentiallyConstructedBases))
return true;
if (SMI.shouldDeleteForAllConstMembers())
return true;
if (getLangOpts().CUDA) {
assert(ICI || CSM == getSpecialMember(MD));
auto RealCSM = CSM;
if (ICI)
RealCSM = getSpecialMember(MD);
return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
SMI.ConstArg, Diagnose);
}
return false;
}
void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
assert(DFK && "not a defaultable function");
assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
if (DFK.isSpecialMember()) {
ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
nullptr, true);
} else {
DefaultedComparisonAnalyzer(
*this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
.visit();
}
}
static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
Sema::CXXSpecialMember CSM, unsigned Quals,
bool ConstRHS,
Sema::TrivialABIHandling TAH,
CXXMethodDecl **Selected) {
if (Selected)
*Selected = nullptr;
switch (CSM) {
case Sema::CXXInvalid:
llvm_unreachable("not a special member");
case Sema::CXXDefaultConstructor:
if (RD->hasTrivialDefaultConstructor())
return true;
if (Selected) {
CXXConstructorDecl *DefCtor = nullptr;
if (RD->needsImplicitDefaultConstructor())
S.DeclareImplicitDefaultConstructor(RD);
for (auto *CI : RD->ctors()) {
if (!CI->isDefaultConstructor())
continue;
DefCtor = CI;
if (!DefCtor->isUserProvided())
break;
}
*Selected = DefCtor;
}
return false;
case Sema::CXXDestructor:
if (RD->hasTrivialDestructor() ||
(TAH == Sema::TAH_ConsiderTrivialABI &&
RD->hasTrivialDestructorForCall()))
return true;
if (Selected) {
if (RD->needsImplicitDestructor())
S.DeclareImplicitDestructor(RD);
*Selected = RD->getDestructor();
}
return false;
case Sema::CXXCopyConstructor:
if (RD->hasTrivialCopyConstructor() ||
(TAH == Sema::TAH_ConsiderTrivialABI &&
RD->hasTrivialCopyConstructorForCall())) {
if (Quals == Qualifiers::Const)
return true;
} else if (!Selected) {
return false;
}
goto NeedOverloadResolution;
case Sema::CXXCopyAssignment:
if (RD->hasTrivialCopyAssignment()) {
if (Quals == Qualifiers::Const)
return true;
} else if (!Selected) {
return false;
}
goto NeedOverloadResolution;
case Sema::CXXMoveConstructor:
case Sema::CXXMoveAssignment:
NeedOverloadResolution:
Sema::SpecialMemberOverloadResult SMOR =
lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
return true;
if (!SMOR.getMethod()) {
assert(SMOR.getKind() ==
Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
return false;
}
if (Selected)
*Selected = SMOR.getMethod();
if (TAH == Sema::TAH_ConsiderTrivialABI &&
(CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
return SMOR.getMethod()->isTrivialForCall();
return SMOR.getMethod()->isTrivial();
}
llvm_unreachable("unknown special method kind");
}
static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
for (auto *CI : RD->ctors())
if (!CI->isImplicit())
return CI;
typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
if (CXXConstructorDecl *CD =
dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
return CD;
}
return nullptr;
}
enum TrivialSubobjectKind {
TSK_BaseClass,
TSK_Field,
TSK_CompleteObject
};
static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
QualType SubType, bool ConstRHS,
Sema::CXXSpecialMember CSM,
TrivialSubobjectKind Kind,
Sema::TrivialABIHandling TAH, bool Diagnose) {
CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
if (!SubRD)
return true;
CXXMethodDecl *Selected;
if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
ConstRHS, TAH, Diagnose ? &Selected : nullptr))
return true;
if (Diagnose) {
if (ConstRHS)
SubType.addConst();
if (!Selected && CSM == Sema::CXXDefaultConstructor) {
S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
<< Kind << SubType.getUnqualifiedType();
if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
} else if (!Selected)
S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
<< Kind << SubType.getUnqualifiedType() << CSM << SubType;
else if (Selected->isUserProvided()) {
if (Kind == TSK_CompleteObject)
S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
<< Kind << SubType.getUnqualifiedType() << CSM;
else {
S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
<< Kind << SubType.getUnqualifiedType() << CSM;
S.Diag(Selected->getLocation(), diag::note_declared_at);
}
} else {
if (Kind != TSK_CompleteObject)
S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
<< Kind << SubType.getUnqualifiedType() << CSM;
S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
Diagnose);
}
}
return false;
}
static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
Sema::CXXSpecialMember CSM,
bool ConstArg,
Sema::TrivialABIHandling TAH,
bool Diagnose) {
for (const auto *FI : RD->fields()) {
if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
continue;
QualType FieldType = S.Context.getBaseElementType(FI->getType());
if (FI->isAnonymousStructOrUnion()) {
if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
CSM, ConstArg, TAH, Diagnose))
return false;
continue;
}
if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
if (Diagnose)
S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
<< FI;
return false;
}
if (FieldType.hasNonTrivialObjCLifetime()) {
if (Diagnose)
S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
<< RD << FieldType.getObjCLifetime();
return false;
}
bool ConstRHS = ConstArg && !FI->isMutable();
if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
CSM, TSK_Field, TAH, Diagnose))
return false;
}
return true;
}
void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
QualType Ty = Context.getRecordType(RD);
bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
TSK_CompleteObject, TAH_IgnoreTrivialABI,
true);
}
bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
TrivialABIHandling TAH, bool Diagnose) {
assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
CXXRecordDecl *RD = MD->getParent();
bool ConstArg = false;
switch (CSM) {
case CXXDefaultConstructor:
case CXXDestructor:
break;
case CXXCopyConstructor:
case CXXCopyAssignment: {
const ParmVarDecl *Param0 = MD->getParamDecl(0);
const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
LangOptions::ClangABI::Ver14;
if (!RT ||
((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
ClangABICompat14)) {
if (Diagnose)
Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
<< Param0->getSourceRange() << Param0->getType()
<< Context.getLValueReferenceType(
Context.getRecordType(RD).withConst());
return false;
}
ConstArg = RT->getPointeeType().isConstQualified();
break;
}
case CXXMoveConstructor:
case CXXMoveAssignment: {
const ParmVarDecl *Param0 = MD->getParamDecl(0);
const RValueReferenceType *RT =
Param0->getType()->getAs<RValueReferenceType>();
if (!RT || RT->getPointeeType().getCVRQualifiers()) {
if (Diagnose)
Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
<< Param0->getSourceRange() << Param0->getType()
<< Context.getRValueReferenceType(Context.getRecordType(RD));
return false;
}
break;
}
case CXXInvalid:
llvm_unreachable("not a special member");
}
if (MD->getMinRequiredArguments() < MD->getNumParams()) {
if (Diagnose)
Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
diag::note_nontrivial_default_arg)
<< MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
return false;
}
if (MD->isVariadic()) {
if (Diagnose)
Diag(MD->getLocation(), diag::note_nontrivial_variadic);
return false;
}
for (const auto &BI : RD->bases())
if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
return false;
if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
return false;
if (CSM == CXXDestructor && MD->isVirtual()) {
if (Diagnose)
Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
return false;
}
if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
if (!Diagnose)
return false;
if (RD->getNumVBases()) {
CXXBaseSpecifier &BS = *RD->vbases_begin();
assert(BS.isVirtual());
Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
return false;
}
for (const auto *MI : RD->methods()) {
if (MI->isVirtual()) {
SourceLocation MLoc = MI->getBeginLoc();
Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
return false;
}
}
llvm_unreachable("dynamic class with no vbases and no virtual functions");
}
return true;
}
namespace {
struct FindHiddenVirtualMethod {
Sema *S;
CXXMethodDecl *Method;
llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
private:
static bool CheckMostOverridenMethods(
const CXXMethodDecl *MD,
const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
if (MD->size_overridden_methods() == 0)
return Methods.count(MD->getCanonicalDecl());
for (const CXXMethodDecl *O : MD->overridden_methods())
if (CheckMostOverridenMethods(O, Methods))
return true;
return false;
}
public:
bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
RecordDecl *BaseRecord =
Specifier->getType()->castAs<RecordType>()->getDecl();
DeclarationName Name = Method->getDeclName();
assert(Name.getNameKind() == DeclarationName::Identifier);
bool foundSameNameMethod = false;
SmallVector<CXXMethodDecl *, 8> overloadedMethods;
for (Path.Decls = BaseRecord->lookup(Name).begin();
Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
NamedDecl *D = *Path.Decls;
if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
MD = MD->getCanonicalDecl();
foundSameNameMethod = true;
if (!MD->isVirtual())
continue;
if (!S->IsOverload(Method, MD, false))
return true;
if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
overloadedMethods.push_back(MD);
}
}
if (foundSameNameMethod)
OverloadedMethods.append(overloadedMethods.begin(),
overloadedMethods.end());
return foundSameNameMethod;
}
};
}
static void AddMostOverridenMethods(const CXXMethodDecl *MD,
llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
if (MD->size_overridden_methods() == 0)
Methods.insert(MD->getCanonicalDecl());
else
for (const CXXMethodDecl *O : MD->overridden_methods())
AddMostOverridenMethods(O, Methods);
}
void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
if (!MD->getDeclName().isIdentifier())
return;
CXXBasePaths Paths(true, false,
false);
FindHiddenVirtualMethod FHVM;
FHVM.Method = MD;
FHVM.S = this;
CXXRecordDecl *DC = MD->getParent();
DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
NamedDecl *ND = *I;
if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
ND = shad->getTargetDecl();
if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
}
if (DC->lookupInBases(FHVM, Paths))
OverloadedMethods = FHVM.OverloadedMethods;
}
void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
CXXMethodDecl *overloadedMD = OverloadedMethods[i];
PartialDiagnostic PD = PDiag(
diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
Diag(overloadedMD->getLocation(), PD);
}
}
void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
if (MD->isInvalidDecl())
return;
if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
return;
SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
FindHiddenVirtualMethods(MD, OverloadedMethods);
if (!OverloadedMethods.empty()) {
Diag(MD->getLocation(), diag::warn_overloaded_virtual)
<< MD << (OverloadedMethods.size() > 1);
NoteHiddenVirtualMethods(MD, OverloadedMethods);
}
}
void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
auto PrintDiagAndRemoveAttr = [&](unsigned N) {
if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
diag::ext_cannot_use_trivial_abi) << &RD;
Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
diag::note_cannot_use_trivial_abi_reason) << &RD << N;
}
RD.dropAttr<TrivialABIAttr>();
};
auto HasNonDeletedCopyOrMoveConstructor = [&]() {
if (RD.isDependentType())
return true;
if (RD.needsImplicitCopyConstructor() &&
!RD.defaultedCopyConstructorIsDeleted())
return true;
if (RD.needsImplicitMoveConstructor() &&
!RD.defaultedMoveConstructorIsDeleted())
return true;
for (const CXXConstructorDecl *CD : RD.ctors())
if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
return true;
return false;
};
if (!HasNonDeletedCopyOrMoveConstructor()) {
PrintDiagAndRemoveAttr(0);
return;
}
if (RD.isPolymorphic()) {
PrintDiagAndRemoveAttr(1);
return;
}
for (const auto &B : RD.bases()) {
if (!B.getType()->isDependentType() &&
!B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
PrintDiagAndRemoveAttr(2);
return;
}
if (B.isVirtual()) {
PrintDiagAndRemoveAttr(3);
return;
}
}
for (const auto *FD : RD.fields()) {
QualType FT = FD->getType();
if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
PrintDiagAndRemoveAttr(4);
return;
}
if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
if (!RT->isDependentType() &&
!cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
PrintDiagAndRemoveAttr(5);
return;
}
}
}
void Sema::ActOnFinishCXXMemberSpecification(
Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
SourceLocation RBrac, const ParsedAttributesView &AttrList) {
if (!TagDecl)
return;
AdjustDeclIfTemplate(TagDecl);
for (const ParsedAttr &AL : AttrList) {
if (AL.getKind() != ParsedAttr::AT_Visibility)
continue;
AL.setInvalid();
Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
}
ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
}
static void findImplicitlyDeclaredEqualityComparisons(
ASTContext &Ctx, CXXRecordDecl *RD,
llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
if (!RD->lookup(EqEq).empty())
return;
for (FriendDecl *Friend : RD->friends()) {
FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
if (!FD) continue;
if (FD->getOverloadedOperator() == OO_EqualEqual) {
Spaceships.clear();
return;
}
if (FD->getOverloadedOperator() == OO_Spaceship &&
FD->isExplicitlyDefaulted())
Spaceships.push_back(FD);
}
DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
for (NamedDecl *ND : RD->lookup(Cmp)) {
if (auto *FD = dyn_cast<FunctionDecl>(ND))
if (FD->isExplicitlyDefaulted())
Spaceships.push_back(FD);
}
}
void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
if (!ClassDecl->isDependentType()) {
if (ClassDecl->needsImplicitDefaultConstructor()) {
++getASTContext().NumImplicitDefaultConstructors;
if (ClassDecl->hasInheritedConstructor())
DeclareImplicitDefaultConstructor(ClassDecl);
}
if (ClassDecl->needsImplicitCopyConstructor()) {
++getASTContext().NumImplicitCopyConstructors;
if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
ClassDecl->hasInheritedConstructor())
DeclareImplicitCopyConstructor(ClassDecl);
else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
(ClassDecl->hasUserDeclaredMoveConstructor() ||
ClassDecl->needsOverloadResolutionForMoveConstructor() ||
ClassDecl->hasUserDeclaredMoveAssignment() ||
ClassDecl->needsOverloadResolutionForMoveAssignment()))
DeclareImplicitCopyConstructor(ClassDecl);
}
if (getLangOpts().CPlusPlus11 &&
ClassDecl->needsImplicitMoveConstructor()) {
++getASTContext().NumImplicitMoveConstructors;
if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
ClassDecl->hasInheritedConstructor())
DeclareImplicitMoveConstructor(ClassDecl);
}
if (ClassDecl->needsImplicitCopyAssignment()) {
++getASTContext().NumImplicitCopyAssignmentOperators;
if (ClassDecl->isDynamicClass() ||
ClassDecl->needsOverloadResolutionForCopyAssignment() ||
ClassDecl->hasInheritedAssignment())
DeclareImplicitCopyAssignment(ClassDecl);
}
if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
++getASTContext().NumImplicitMoveAssignmentOperators;
if (ClassDecl->isDynamicClass() ||
ClassDecl->needsOverloadResolutionForMoveAssignment() ||
ClassDecl->hasInheritedAssignment())
DeclareImplicitMoveAssignment(ClassDecl);
}
if (ClassDecl->needsImplicitDestructor()) {
++getASTContext().NumImplicitDestructors;
if (ClassDecl->isDynamicClass() ||
ClassDecl->needsOverloadResolutionForDestructor())
DeclareImplicitDestructor(ClassDecl);
}
}
if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
DefaultedSpaceships);
for (auto *FD : DefaultedSpaceships)
DeclareImplicitEqualityComparison(ClassDecl, FD);
}
}
unsigned
Sema::ActOnReenterTemplateScope(Decl *D,
llvm::function_ref<Scope *()> EnterScope) {
if (!D)
return 0;
AdjustDeclIfTemplate(D);
SmallVector<TemplateParameterList *, 4> ParameterLists;
DeclContext *LookupDC = dyn_cast<DeclContext>(D);
if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
ParameterLists.push_back(DD->getTemplateParameterList(i));
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
ParameterLists.push_back(FTD->getTemplateParameters());
} else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
LookupDC = VD->getDeclContext();
if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
ParameterLists.push_back(VTD->getTemplateParameters());
else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
ParameterLists.push_back(PSD->getTemplateParameters());
}
} else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
ParameterLists.push_back(TD->getTemplateParameterList(i));
if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
ParameterLists.push_back(CTD->getTemplateParameters());
else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
ParameterLists.push_back(PSD->getTemplateParameters());
}
}
unsigned Count = 0;
Scope *InnermostTemplateScope = nullptr;
for (TemplateParameterList *Params : ParameterLists) {
if (Params->size() == 0)
continue;
InnermostTemplateScope = EnterScope();
for (NamedDecl *Param : *Params) {
if (Param->getDeclName()) {
InnermostTemplateScope->AddDecl(Param);
IdResolver.AddDecl(Param);
}
}
++Count;
}
if (InnermostTemplateScope) {
assert(LookupDC && "no enclosing DeclContext for template lookup");
EnterTemplatedContext(InnermostTemplateScope, LookupDC);
}
return Count;
}
void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
if (!RecordD) return;
AdjustDeclIfTemplate(RecordD);
CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
PushDeclContext(S, Record);
}
void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
if (!RecordD) return;
PopDeclContext();
}
void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
if (!Param)
return;
S->AddDecl(Param);
if (Param->getDeclName())
IdResolver.AddDecl(Param);
}
void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
}
void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
if (!ParamD)
return;
ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
S->AddDecl(Param);
if (Param->getDeclName())
IdResolver.AddDecl(Param);
}
void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
if (!MethodD)
return;
AdjustDeclIfTemplate(MethodD);
FunctionDecl *Method = cast<FunctionDecl>(MethodD);
if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
CheckConstructor(Constructor);
if (!Method->isInvalidDecl())
CheckCXXDefaultArguments(Method);
}
static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
bool DiagOccured = false;
FTI.MethodQualifiers->forEachQualifier(
[DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
SourceLocation SL) {
S.Diag(SL, DiagID) << QualName << SourceRange(SL);
DiagOccured = true;
});
if (DiagOccured)
D.setInvalidType();
}
}
QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
StorageClass &SC) {
bool isVirtual = D.getDeclSpec().isVirtualSpecified();
if (isVirtual) {
if (!D.isInvalidType())
Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
<< "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
<< SourceRange(D.getIdentifierLoc());
D.setInvalidType();
}
if (SC == SC_Static) {
if (!D.isInvalidType())
Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
<< "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
<< SourceRange(D.getIdentifierLoc());
D.setInvalidType();
SC = SC_None;
}
if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
diagnoseIgnoredQualifiers(
diag::err_constructor_return_type, TypeQuals, SourceLocation(),
D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
D.getDeclSpec().getRestrictSpecLoc(),
D.getDeclSpec().getAtomicSpecLoc());
D.setInvalidType();
}
checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
if (FTI.hasRefQualifier()) {
Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
<< FTI.RefQualifierIsLValueRef
<< FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
D.setInvalidType();
}
const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
return R;
FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
EPI.TypeQuals = Qualifiers();
EPI.RefQualifier = RQ_None;
return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
}
void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
CXXRecordDecl *ClassDecl
= dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
if (!ClassDecl)
return Constructor->setInvalidDecl();
if (!Constructor->isInvalidDecl() &&
Constructor->hasOneParamOrDefaultArgs() &&
Constructor->getTemplateSpecializationKind() !=
TSK_ImplicitInstantiation) {
QualType ParamType = Constructor->getParamDecl(0)->getType();
QualType ClassTy = Context.getTagDeclType(ClassDecl);
if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
const char *ConstRef
= Constructor->getParamDecl(0)->getIdentifier() ? "const &"
: " const &";
Diag(ParamLoc, diag::err_constructor_byvalue_arg)
<< FixItHint::CreateInsertion(ParamLoc, ConstRef);
Constructor->setInvalidDecl();
}
}
}
bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
CXXRecordDecl *RD = Destructor->getParent();
if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
SourceLocation Loc;
if (!Destructor->isImplicit())
Loc = Destructor->getLocation();
else
Loc = RD->getLocation();
if (FunctionDecl *OperatorDelete =
FindDeallocationFunctionForDestructor(Loc, RD)) {
Expr *ThisArg = nullptr;
if (OperatorDelete->isDestroyingOperatorDelete()) {
QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
ContextRAII SwitchContext(*this, Destructor);
ExprResult This =
ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
if (This.isInvalid()) {
Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
return true;
}
ThisArg = This.get();
}
}
DiagnoseUseOfDecl(OperatorDelete, Loc);
MarkFunctionReferenced(Loc, OperatorDelete);
Destructor->setOperatorDelete(OperatorDelete, ThisArg);
}
}
return false;
}
QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
StorageClass& SC) {
QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
<< DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
else if (const TemplateSpecializationType *TST =
DeclaratorType->getAs<TemplateSpecializationType>())
if (TST->isTypeAlias())
Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
<< DeclaratorType << 1;
if (SC == SC_Static) {
if (!D.isInvalidType())
Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
<< "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
<< SourceRange(D.getIdentifierLoc())
<< FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
SC = SC_None;
}
if (!D.isInvalidType()) {
if (D.getDeclSpec().hasTypeSpecifier())
Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
<< SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
<< SourceRange(D.getIdentifierLoc());
else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
SourceLocation(),
D.getDeclSpec().getConstSpecLoc(),
D.getDeclSpec().getVolatileSpecLoc(),
D.getDeclSpec().getRestrictSpecLoc(),
D.getDeclSpec().getAtomicSpecLoc());
D.setInvalidType();
}
}
checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
if (FTI.hasRefQualifier()) {
Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
<< FTI.RefQualifierIsLValueRef
<< FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
D.setInvalidType();
}
if (FTIHasNonVoidParameters(FTI)) {
Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
FTI.freeParams();
D.setInvalidType();
}
if (FTI.isVariadic) {
Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
D.setInvalidType();
}
if (!D.isInvalidType())
return R;
const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
EPI.Variadic = false;
EPI.TypeQuals = Qualifiers();
EPI.RefQualifier = RQ_None;
return Context.getFunctionType(Context.VoidTy, None, EPI);
}
static void extendLeft(SourceRange &R, SourceRange Before) {
if (Before.isInvalid())
return;
R.setBegin(Before.getBegin());
if (R.getEnd().isInvalid())
R.setEnd(Before.getEnd());
}
static void extendRight(SourceRange &R, SourceRange After) {
if (After.isInvalid())
return;
if (R.getBegin().isInvalid())
R.setBegin(After.getBegin());
R.setEnd(After.getEnd());
}
void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
StorageClass& SC) {
if (SC == SC_Static) {
if (!D.isInvalidType())
Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
<< SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
<< D.getName().getSourceRange();
D.setInvalidType();
SC = SC_None;
}
TypeSourceInfo *ConvTSI = nullptr;
QualType ConvType =
GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
const DeclSpec &DS = D.getDeclSpec();
if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
<< SourceRange(DS.getTypeSpecTypeLoc())
<< SourceRange(D.getIdentifierLoc());
D.setInvalidType();
} else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
<< SourceRange(D.getIdentifierLoc()) << 0;
D.setInvalidType();
}
const auto *Proto = R->castAs<FunctionProtoType>();
if (Proto->getNumParams() > 0) {
Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
D.getFunctionTypeInfo().freeParams();
D.setInvalidType();
} else if (Proto->isVariadic()) {
Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
D.setInvalidType();
}
if (Proto->getReturnType() != ConvType) {
bool NeedsTypedef = false;
SourceRange Before, After;
bool PastFunctionChunk = false;
for (auto &Chunk : D.type_objects()) {
switch (Chunk.Kind) {
case DeclaratorChunk::Function:
if (!PastFunctionChunk) {
if (Chunk.Fun.HasTrailingReturnType) {
TypeSourceInfo *TRT = nullptr;
GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
}
PastFunctionChunk = true;
break;
}
LLVM_FALLTHROUGH;
case DeclaratorChunk::Array:
NeedsTypedef = true;
extendRight(After, Chunk.getSourceRange());
break;
case DeclaratorChunk::Pointer:
case DeclaratorChunk::BlockPointer:
case DeclaratorChunk::Reference:
case DeclaratorChunk::MemberPointer:
case DeclaratorChunk::Pipe:
extendLeft(Before, Chunk.getSourceRange());
break;
case DeclaratorChunk::Paren:
extendLeft(Before, Chunk.Loc);
extendRight(After, Chunk.EndLoc);
break;
}
}
SourceLocation Loc = Before.isValid() ? Before.getBegin() :
After.isValid() ? After.getBegin() :
D.getIdentifierLoc();
auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
DB << Before << After;
if (!NeedsTypedef) {
DB << 0;
if (After.isInvalid() && ConvTSI) {
SourceLocation InsertLoc =
getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
DB << FixItHint::CreateInsertion(InsertLoc, " ")
<< FixItHint::CreateInsertionFromRange(
InsertLoc, CharSourceRange::getTokenRange(Before))
<< FixItHint::CreateRemoval(Before);
}
} else if (!Proto->getReturnType()->isDependentType()) {
DB << 1 << Proto->getReturnType();
} else if (getLangOpts().CPlusPlus11) {
DB << 2 << Proto->getReturnType();
} else {
DB << 3;
}
ConvType = Proto->getReturnType();
}
if (ConvType->isArrayType()) {
Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
ConvType = Context.getPointerType(ConvType);
D.setInvalidType();
} else if (ConvType->isFunctionType()) {
Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
ConvType = Context.getPointerType(ConvType);
D.setInvalidType();
}
if (D.isInvalidType())
R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
Diag(DS.getExplicitSpecLoc(),
getLangOpts().CPlusPlus11
? diag::warn_cxx98_compat_explicit_conversion_functions
: diag::ext_explicit_conversion_functions)
<< SourceRange(DS.getExplicitSpecRange());
}
Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
assert(Conversion && "Expected to receive a conversion function declaration");
CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
QualType ClassType
= Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
ConvType = ConvTypeRef->getPointeeType();
if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
;
else if (Conversion->size_overridden_methods() != 0)
;
else if (ConvType->isRecordType()) {
ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
if (ConvType == ClassType)
Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
<< ClassType;
else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
<< ClassType << ConvType;
} else if (ConvType->isVoidType()) {
Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
<< ClassType << ConvType;
}
if (FunctionTemplateDecl *ConversionTemplate
= Conversion->getDescribedFunctionTemplate())
return ConversionTemplate;
return Conversion;
}
namespace {
struct BadSpecifierDiagnoser {
BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
: S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
~BadSpecifierDiagnoser() {
Diagnostic << Specifiers;
}
template<typename T> void check(SourceLocation SpecLoc, T Spec) {
return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
}
void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
return check(SpecLoc,
DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
}
void check(SourceLocation SpecLoc, const char *Spec) {
if (SpecLoc.isInvalid()) return;
Diagnostic << SourceRange(SpecLoc, SpecLoc);
if (!Specifiers.empty()) Specifiers += " ";
Specifiers += Spec;
}
Sema &S;
Sema::SemaDiagnosticBuilder Diagnostic;
std::string Specifiers;
};
}
void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
StorageClass &SC) {
TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
assert(GuidedTemplateDecl && "missing template decl for deduction guide");
if (!CurContext->getRedeclContext()->Equals(
GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
<< GuidedTemplateDecl;
Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
}
auto &DS = D.getMutableDeclSpec();
if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
BadSpecifierDiagnoser Diagnoser(
*this, D.getIdentifierLoc(),
diag::err_deduction_guide_invalid_specifier);
Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
DS.ClearStorageClassSpecs();
SC = SC_None;
Diagnoser.check(DS.getInlineSpecLoc(), "inline");
Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
DS.ClearConstexprSpec();
Diagnoser.check(DS.getConstSpecLoc(), "const");
Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
DS.ClearTypeQualifiers();
Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
DS.ClearTypeSpecType();
}
if (D.isInvalidType())
return;
bool FoundFunction = false;
for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
if (Chunk.Kind == DeclaratorChunk::Paren)
continue;
if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
Diag(D.getDeclSpec().getBeginLoc(),
diag::err_deduction_guide_with_complex_decl)
<< D.getSourceRange();
break;
}
if (!Chunk.Fun.hasTrailingReturnType()) {
Diag(D.getName().getBeginLoc(),
diag::err_deduction_guide_no_trailing_return_type);
break;
}
ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
TypeSourceInfo *TSI = nullptr;
QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
assert(TSI && "deduction guide has valid type but invalid return type?");
bool AcceptableReturnType = false;
bool MightInstantiateToSpecialization = false;
if (auto RetTST =
TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
bool TemplateMatches =
Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
AcceptableReturnType = true;
else {
auto *TD = SpecifiedName.getAsTemplateDecl();
MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
!TemplateMatches);
}
} else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
MightInstantiateToSpecialization = true;
}
if (!AcceptableReturnType) {
Diag(TSI->getTypeLoc().getBeginLoc(),
diag::err_deduction_guide_bad_trailing_return_type)
<< GuidedTemplate << TSI->getType()
<< MightInstantiateToSpecialization
<< TSI->getTypeLoc().getSourceRange();
}
FoundFunction = true;
}
if (D.isFunctionDefinition())
Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
}
static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
SourceLocation Loc,
IdentifierInfo *II, bool *IsInline,
NamespaceDecl *PrevNS) {
assert(*IsInline != PrevNS->isInline());
PrevNS = PrevNS->getFirstDecl();
if (PrevNS->isInline())
S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
<< FixItHint::CreateInsertion(KeywordLoc, "inline ");
else
S.Diag(Loc, diag::err_inline_namespace_mismatch);
S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
*IsInline = PrevNS->isInline();
}
Decl *Sema::ActOnStartNamespaceDef(
Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
SourceLocation Loc = II ? IdentLoc : LBrace;
bool IsInline = InlineLoc.isValid();
bool IsInvalid = false;
bool IsStd = false;
bool AddToKnown = false;
Scope *DeclRegionScope = NamespcScope->getParent();
NamespaceDecl *PrevNS = nullptr;
if (II) {
LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
ForExternalRedeclaration);
LookupQualifiedName(R, CurContext->getRedeclContext());
NamedDecl *PrevDecl =
R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
if (PrevNS) {
if (IsInline != PrevNS->isInline())
DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
&IsInline, PrevNS);
} else if (PrevDecl) {
Diag(Loc, diag::err_redefinition_different_kind)
<< II;
Diag(PrevDecl->getLocation(), diag::note_previous_definition);
IsInvalid = true;
} else if (II->isStr("std") &&
CurContext->getRedeclContext()->isTranslationUnit()) {
PrevNS = getStdNamespace();
IsStd = true;
AddToKnown = !IsInline;
} else {
AddToKnown = !IsInline;
}
} else {
DeclContext *Parent = CurContext->getRedeclContext();
if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
PrevNS = TU->getAnonymousNamespace();
} else {
NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
PrevNS = ND->getAnonymousNamespace();
}
if (PrevNS && IsInline != PrevNS->isInline())
DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
&IsInline, PrevNS);
}
NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
StartLoc, Loc, II, PrevNS);
if (IsInvalid)
Namespc->setInvalidDecl();
ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
AddPragmaAttributes(DeclRegionScope, Namespc);
if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
PushNamespaceVisibilityAttr(Attr, Loc);
if (IsStd)
StdNamespace = Namespc;
if (AddToKnown)
KnownNamespaces[Namespc] = false;
if (II) {
PushOnScopeChains(Namespc, DeclRegionScope);
} else {
DeclContext *Parent = CurContext->getRedeclContext();
if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
TU->setAnonymousNamespace(Namespc);
} else {
cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
}
CurContext->addDecl(Namespc);
if (!PrevNS) {
UD = UsingDirectiveDecl::Create(Context, Parent,
LBrace,
SourceLocation(),
NestedNameSpecifierLoc(),
SourceLocation(),
Namespc,
Parent);
UD->setImplicit();
Parent->addDecl(UD);
}
}
ActOnDocumentableDecl(Namespc);
PushDeclContext(NamespcScope, Namespc);
return Namespc;
}
static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
return AD->getNamespace();
return dyn_cast_or_null<NamespaceDecl>(D);
}
void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Namespc->setRBraceLoc(RBrace);
PopDeclContext();
if (Namespc->hasAttr<VisibilityAttr>())
PopPragmaVisibility(true, RBrace);
if (DeferredExportedNamespaces.erase(Namespc))
Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
}
CXXRecordDecl *Sema::getStdBadAlloc() const {
return cast_or_null<CXXRecordDecl>(
StdBadAlloc.get(Context.getExternalSource()));
}
EnumDecl *Sema::getStdAlignValT() const {
return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
}
NamespaceDecl *Sema::getStdNamespace() const {
return cast_or_null<NamespaceDecl>(
StdNamespace.get(Context.getExternalSource()));
}
NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
if (!StdExperimentalNamespaceCache) {
if (auto Std = getStdNamespace()) {
LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
SourceLocation(), LookupNamespaceName);
if (!LookupQualifiedName(Result, Std) ||
!(StdExperimentalNamespaceCache =
Result.getAsSingle<NamespaceDecl>()))
Result.suppressDiagnostics();
}
}
return StdExperimentalNamespaceCache;
}
namespace {
enum UnsupportedSTLSelect {
USS_InvalidMember,
USS_MissingMember,
USS_NonTrivial,
USS_Other
};
struct InvalidSTLDiagnoser {
Sema &S;
SourceLocation Loc;
QualType TyForDiags;
QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
const VarDecl *VD = nullptr) {
{
auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
<< TyForDiags << ((int)Sel);
if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
assert(!Name.empty());
D << Name;
}
}
if (Sel == USS_InvalidMember) {
S.Diag(VD->getLocation(), diag::note_var_declared_here)
<< VD << VD->getSourceRange();
}
return QualType();
}
};
}
QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
SourceLocation Loc,
ComparisonCategoryUsage Usage) {
assert(getLangOpts().CPlusPlus &&
"Looking for comparison category type outside of C++.");
auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
auto *NNS =
NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
return Context.getElaboratedType(ETK_None, NNS, Info->getType());
};
ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
return QualType();
return Info->getType();
}
if (!Info) {
std::string NameForDiags = "std::";
NameForDiags += ComparisonCategories::getCategoryString(Kind);
Diag(Loc, diag::err_implied_comparison_category_type_not_found)
<< NameForDiags << (int)Usage;
return QualType();
}
assert(Info->Kind == Kind);
assert(Info->Record);
if (Info->Record->hasDefinition())
Info->Record = Info->Record->getDefinition();
if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
return QualType();
InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
if (!Info->Record->isTriviallyCopyable())
return UnsupportedSTLError(USS_NonTrivial);
for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
if (Base->isEmpty())
continue;
return UnsupportedSTLError();
}
auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
if (std::distance(FIt, FEnd) != 1 ||
!FIt->getType()->isIntegralOrEnumerationType()) {
return UnsupportedSTLError();
}
for (ComparisonCategoryResult CCR :
ComparisonCategories::getPossibleResultsForType(Kind)) {
StringRef MemName = ComparisonCategories::getResultString(CCR);
ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
if (!ValInfo)
return UnsupportedSTLError(USS_MissingMember, MemName);
VarDecl *VD = ValInfo->VD;
assert(VD && "should not be null!");
if (!VD->isStaticDataMember() ||
!VD->isUsableInConstantExpressions(Context))
return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
if (!ValInfo->hasValidIntValue())
return UnsupportedSTLError();
MarkVariableReferenced(Loc, VD);
}
FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
return Info->getType();
}
NamespaceDecl *Sema::getOrCreateStdNamespace() {
if (!StdNamespace) {
StdNamespace = NamespaceDecl::Create(Context,
Context.getTranslationUnitDecl(),
false,
SourceLocation(), SourceLocation(),
&PP.getIdentifierTable().get("std"),
nullptr);
getStdNamespace()->setImplicit(true);
}
return getStdNamespace();
}
bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
assert(getLangOpts().CPlusPlus &&
"Looking for std::initializer_list outside of C++.");
if (!StdNamespace) return false;
ClassTemplateDecl *Template = nullptr;
const TemplateArgument *Arguments = nullptr;
if (const RecordType *RT = Ty->getAs<RecordType>()) {
ClassTemplateSpecializationDecl *Specialization =
dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
if (!Specialization)
return false;
Template = Specialization->getSpecializedTemplate();
Arguments = Specialization->getTemplateArgs().data();
} else if (const TemplateSpecializationType *TST =
Ty->getAs<TemplateSpecializationType>()) {
Template = dyn_cast_or_null<ClassTemplateDecl>(
TST->getTemplateName().getAsTemplateDecl());
Arguments = TST->getArgs();
}
if (!Template)
return false;
if (!StdInitializerList) {
CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
if (TemplateClass->getIdentifier() !=
&PP.getIdentifierTable().get("initializer_list") ||
!getStdNamespace()->InEnclosingNamespaceSetOf(
TemplateClass->getDeclContext()))
return false;
TemplateParameterList *Params = Template->getTemplateParameters();
if (Params->getMinRequiredArguments() != 1)
return false;
if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
return false;
StdInitializerList = Template;
}
if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
return false;
if (Element)
*Element = Arguments[0].getAsType();
return true;
}
static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
NamespaceDecl *Std = S.getStdNamespace();
if (!Std) {
S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
return nullptr;
}
LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
Loc, Sema::LookupOrdinaryName);
if (!S.LookupQualifiedName(Result, Std)) {
S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
return nullptr;
}
ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
if (!Template) {
Result.suppressDiagnostics();
NamedDecl *Found = *Result.begin();
S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
return nullptr;
}
TemplateParameterList *Params = Template->getTemplateParameters();
if (Params->getMinRequiredArguments() != 1 ||
!isa<TemplateTypeParmDecl>(Params->getParam(0))) {
S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
return nullptr;
}
return Template;
}
QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
if (!StdInitializerList) {
StdInitializerList = LookupStdInitializerList(*this, Loc);
if (!StdInitializerList)
return QualType();
}
TemplateArgumentListInfo Args(Loc, Loc);
Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
Context.getTrivialTypeSourceInfo(Element,
Loc)));
return Context.getCanonicalType(
CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
}
bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
if (!Ctor->hasOneParamOrDefaultArgs())
return false;
QualType ArgType = Ctor->getParamDecl(0)->getType();
if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
ArgType = RT->getPointeeType().getUnqualifiedType();
return isStdInitializerList(ArgType, nullptr);
}
static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
switch (CurContext->getDeclKind()) {
case Decl::TranslationUnit:
return true;
case Decl::LinkageSpec:
return IsUsingDirectiveInToplevelContext(CurContext->getParent());
default:
return false;
}
}
namespace {
class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
public:
bool ValidateCandidate(const TypoCorrection &candidate) override {
if (NamedDecl *ND = candidate.getCorrectionDecl())
return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
return false;
}
std::unique_ptr<CorrectionCandidateCallback> clone() override {
return std::make_unique<NamespaceValidatorCCC>(*this);
}
};
}
static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *Ident) {
R.clear();
NamespaceValidatorCCC CCC{};
if (TypoCorrection Corrected =
S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
Sema::CTK_ErrorRecovery)) {
if (DeclContext *DC = S.computeDeclContext(SS, false)) {
std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Ident->getName().equals(CorrectedStr);
S.diagnoseTypo(Corrected,
S.PDiag(diag::err_using_directive_member_suggest)
<< Ident << DC << DroppedSpecifier << SS.getRange(),
S.PDiag(diag::note_namespace_defined_here));
} else {
S.diagnoseTypo(Corrected,
S.PDiag(diag::err_using_directive_suggest) << Ident,
S.PDiag(diag::note_namespace_defined_here));
}
R.addDecl(Corrected.getFoundDecl());
return true;
}
return false;
}
Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
SourceLocation NamespcLoc, CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *NamespcName,
const ParsedAttributesView &AttrList) {
assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
assert(NamespcName && "Invalid NamespcName.");
assert(IdentLoc.isValid() && "Invalid NamespceName location.");
while (S->isTemplateParamScope())
S = S->getParent();
assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
UsingDirectiveDecl *UDir = nullptr;
NestedNameSpecifier *Qualifier = nullptr;
if (SS.isSet())
Qualifier = SS.getScopeRep();
LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
LookupParsedName(R, S, &SS);
if (R.isAmbiguous())
return nullptr;
if (R.empty()) {
R.clear();
if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
NamespcName->isStr("std")) {
Diag(IdentLoc, diag::ext_using_undefined_std);
R.addDecl(getOrCreateStdNamespace());
R.resolveKind();
}
else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
}
if (!R.empty()) {
NamedDecl *Named = R.getRepresentativeDecl();
NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
assert(NS && "expected namespace decl");
DiagnoseUseOfDecl(Named, IdentLoc);
DeclContext *CommonAncestor = NS;
while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
CommonAncestor = CommonAncestor->getParent();
UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
SS.getWithLocInContext(Context),
IdentLoc, Named, CommonAncestor);
if (IsUsingDirectiveInToplevelContext(CurContext) &&
!SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Diag(IdentLoc, diag::warn_using_directive_in_header);
}
PushUsingDirective(S, UDir);
} else {
Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
}
if (UDir)
ProcessDeclAttributeList(S, UDir, AttrList);
return UDir;
}
void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
DeclContext *Ctx = S->getEntity();
if (Ctx && !Ctx->isFunctionOrMethod())
Ctx->addDecl(UDir);
else
S->PushUsingDirective(UDir);
}
Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
SourceLocation UsingLoc,
SourceLocation TypenameLoc, CXXScopeSpec &SS,
UnqualifiedId &Name,
SourceLocation EllipsisLoc,
const ParsedAttributesView &AttrList) {
assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
if (SS.isEmpty()) {
Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
return nullptr;
}
switch (Name.getKind()) {
case UnqualifiedIdKind::IK_ImplicitSelfParam:
case UnqualifiedIdKind::IK_Identifier:
case UnqualifiedIdKind::IK_OperatorFunctionId:
case UnqualifiedIdKind::IK_LiteralOperatorId:
case UnqualifiedIdKind::IK_ConversionFunctionId:
break;
case UnqualifiedIdKind::IK_ConstructorName:
case UnqualifiedIdKind::IK_ConstructorTemplateId:
Diag(Name.getBeginLoc(),
getLangOpts().CPlusPlus11
? diag::warn_cxx98_compat_using_decl_constructor
: diag::err_using_decl_constructor)
<< SS.getRange();
if (getLangOpts().CPlusPlus11) break;
return nullptr;
case UnqualifiedIdKind::IK_DestructorName:
Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
return nullptr;
case UnqualifiedIdKind::IK_TemplateId:
Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
<< SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
return nullptr;
case UnqualifiedIdKind::IK_DeductionGuideName:
llvm_unreachable("cannot parse qualified deduction guide name");
}
DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
DeclarationName TargetName = TargetNameInfo.getName();
if (!TargetName)
return nullptr;
if (UsingLoc.isInvalid()) {
Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
? diag::err_access_decl
: diag::warn_access_decl_deprecated)
<< FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
}
if (EllipsisLoc.isInvalid()) {
if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
return nullptr;
} else {
if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
!TargetNameInfo.containsUnexpandedParameterPack()) {
Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
<< SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
EllipsisLoc = SourceLocation();
}
}
NamedDecl *UD =
BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
SS, TargetNameInfo, EllipsisLoc, AttrList,
false,
AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
if (UD)
PushOnScopeChains(UD, S, false);
return UD;
}
Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
SourceLocation UsingLoc,
SourceLocation EnumLoc,
const DeclSpec &DS) {
switch (DS.getTypeSpecType()) {
case DeclSpec::TST_error:
return nullptr;
case DeclSpec::TST_enum:
break;
case DeclSpec::TST_typename:
Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent);
return nullptr;
default:
llvm_unreachable("unexpected DeclSpec type");
}
auto *Enum = cast<EnumDecl>(DS.getRepAsDecl());
if (auto *Def = Enum->getDefinition())
Enum = Def;
auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc,
DS.getTypeSpecTypeNameLoc(), Enum);
if (UD)
PushOnScopeChains(UD, S, false);
return UD;
}
static bool
IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
return true;
if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
return Context.hasSameType(TD1->getUnderlyingType(),
TD2->getUnderlyingType());
if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
isa<UnresolvedUsingIfExistsDecl>(D2))
return true;
return false;
}
bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
const LookupResult &Previous,
UsingShadowDecl *&PrevShadow) {
if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
DeclContext *OrigDC = Orig->getDeclContext();
if (isa<EnumDecl>(OrigDC))
OrigDC = OrigDC->getParent();
CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
while (OrigRec->isAnonymousStructOrUnion())
OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
if (OrigDC == CurContext) {
Diag(Using->getLocation(),
diag::err_using_decl_nested_name_specifier_is_current_class)
<< Using->getQualifierLoc().getSourceRange();
Diag(Orig->getLocation(), diag::note_using_decl_target);
Using->setInvalidDecl();
return true;
}
Diag(Using->getQualifierLoc().getBeginLoc(),
diag::err_using_decl_nested_name_specifier_is_not_base_class)
<< Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
<< Using->getQualifierLoc().getSourceRange();
Diag(Orig->getLocation(), diag::note_using_decl_target);
Using->setInvalidDecl();
return true;
}
}
if (Previous.empty()) return false;
NamedDecl *Target = Orig;
if (isa<UsingShadowDecl>(Target))
Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
NamedDecl *NonTag = nullptr, *Tag = nullptr;
bool FoundEquivalentDecl = false;
for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
I != E; ++I) {
NamedDecl *D = (*I)->getUnderlyingDecl();
if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
continue;
if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
!isa<IndirectFieldDecl>(Target) &&
!isa<UnresolvedUsingValueDecl>(Target) &&
DiagnoseClassNameShadow(
CurContext,
DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
return true;
}
if (IsEquivalentForUsingDecl(Context, D, Target)) {
if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
PrevShadow = Shadow;
FoundEquivalentDecl = true;
} else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
FoundEquivalentDecl = true;
}
if (isVisible(D))
(isa<TagDecl>(D) ? Tag : NonTag) = D;
}
if (FoundEquivalentDecl)
return false;
if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
(isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
if (!NonTag && !Tag)
return false;
Diag(BUD->getLocation(), diag::err_using_decl_conflict);
Diag(Target->getLocation(), diag::note_using_decl_target);
Diag((NonTag ? NonTag : Tag)->getLocation(),
diag::note_using_decl_conflict);
BUD->setInvalidDecl();
return true;
}
if (FunctionDecl *FD = Target->getAsFunction()) {
NamedDecl *OldDecl = nullptr;
switch (CheckOverload(nullptr, FD, Previous, OldDecl,
true)) {
case Ovl_Overload:
return false;
case Ovl_NonFunction:
Diag(BUD->getLocation(), diag::err_using_decl_conflict);
break;
case Ovl_Match:
if (CurContext->isRecord())
return true;
Diag(BUD->getLocation(), diag::err_using_decl_conflict);
break;
}
Diag(Target->getLocation(), diag::note_using_decl_target);
Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
BUD->setInvalidDecl();
return true;
}
if (isa<TagDecl>(Target)) {
if (!Tag) return false;
Diag(BUD->getLocation(), diag::err_using_decl_conflict);
Diag(Target->getLocation(), diag::note_using_decl_target);
Diag(Tag->getLocation(), diag::note_using_decl_conflict);
BUD->setInvalidDecl();
return true;
}
if (!NonTag) return false;
Diag(BUD->getLocation(), diag::err_using_decl_conflict);
Diag(Target->getLocation(), diag::note_using_decl_target);
Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
BUD->setInvalidDecl();
return true;
}
static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
if (!Derived->getNumVBases())
return false;
for (auto &B : Derived->bases())
if (B.getType()->getAsCXXRecordDecl() == Base)
return B.isVirtual();
llvm_unreachable("not a direct base class");
}
UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
NamedDecl *Orig,
UsingShadowDecl *PrevDecl) {
NamedDecl *Target = Orig;
if (isa<UsingShadowDecl>(Target)) {
Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
}
NamedDecl *NonTemplateTarget = Target;
if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
NonTemplateTarget = TargetTD->getTemplatedDecl();
UsingShadowDecl *Shadow;
if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
UsingDecl *Using = cast<UsingDecl>(BUD);
bool IsVirtualBase =
isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
Using->getQualifier()->getAsRecordDecl());
Shadow = ConstructorUsingShadowDecl::Create(
Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
} else {
Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
Target->getDeclName(), BUD, Target);
}
BUD->addShadowDecl(Shadow);
Shadow->setAccess(BUD->getAccess());
if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
Shadow->setInvalidDecl();
Shadow->setPreviousDecl(PrevDecl);
if (S)
PushOnScopeChains(Shadow, S);
else
CurContext->addDecl(Shadow);
return Shadow;
}
void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
if (Shadow->getDeclName().getNameKind() ==
DeclarationName::CXXConversionFunctionName)
cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
Shadow->getDeclContext()->removeDecl(Shadow);
if (S) {
S->RemoveDecl(Shadow);
IdResolver.RemoveDecl(Shadow);
}
Shadow->getIntroducer()->removeShadowDecl(Shadow);
}
static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
QualType DesiredBase,
bool &AnyDependentBases) {
CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
.getUnqualifiedType();
for (auto &Base : Derived->bases()) {
CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
if (CanonicalDesiredBase == BaseType)
return &Base;
if (BaseType->isDependentType())
AnyDependentBases = true;
}
return nullptr;
}
namespace {
class UsingValidatorCCC final : public CorrectionCandidateCallback {
public:
UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
: HasTypenameKeyword(HasTypenameKeyword),
IsInstantiation(IsInstantiation), OldNNS(NNS),
RequireMemberOf(RequireMemberOf) {}
bool ValidateCandidate(const TypoCorrection &Candidate) override {
NamedDecl *ND = Candidate.getCorrectionDecl();
if (!ND || isa<NamespaceDecl>(ND))
return false;
if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
return false;
if (RequireMemberOf) {
auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
if (FoundRecord && FoundRecord->isInjectedClassName()) {
ASTContext &Ctx = ND->getASTContext();
if (!Ctx.getLangOpts().CPlusPlus11)
return false;
QualType FoundType = Ctx.getRecordType(FoundRecord);
NestedNameSpecifier *Specifier =
Candidate.WillReplaceSpecifier()
? Candidate.getCorrectionSpecifier()
: OldNNS;
if (!Specifier->getAsType() ||
!Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
return false;
bool AnyDependentBases = false;
if (!findDirectBaseWithType(RequireMemberOf,
Ctx.getRecordType(FoundRecord),
AnyDependentBases) &&
!AnyDependentBases)
return false;
} else {
auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
return false;
}
} else {
auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
if (FoundRecord && FoundRecord->isInjectedClassName())
return false;
}
if (isa<TypeDecl>(ND))
return HasTypenameKeyword || !IsInstantiation;
return !HasTypenameKeyword;
}
std::unique_ptr<CorrectionCandidateCallback> clone() override {
return std::make_unique<UsingValidatorCCC>(*this);
}
private:
bool HasTypenameKeyword;
bool IsInstantiation;
NestedNameSpecifier *OldNNS;
CXXRecordDecl *RequireMemberOf;
};
}
void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
LookupResult::Filter F = Previous.makeFilter();
while (F.hasNext()) {
NamedDecl *D = F.next();
if (!isDeclInScope(D, CurContext, S))
F.erase();
else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
!(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
F.erase();
}
F.done();
}
NamedDecl *Sema::BuildUsingDeclaration(
Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
const ParsedAttributesView &AttrList, bool IsInstantiation,
bool IsUsingIfExists) {
assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
SourceLocation IdentLoc = NameInfo.getLoc();
assert(IdentLoc.isValid() && "Invalid TargetName location.");
DeclarationNameInfo UsingName = NameInfo;
if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
Context.getCanonicalType(Context.getRecordType(RD))));
LookupResult Previous(*this, UsingName, LookupUsingDeclName,
ForVisibleRedeclaration);
Previous.setHideTags(false);
if (S) {
LookupName(Previous, S);
FilterUsingLookup(S, Previous);
} else {
assert(IsInstantiation && "no scope in non-instantiation");
if (CurContext->isRecord())
LookupQualifiedName(Previous, CurContext);
else {
}
}
if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
SS, IdentLoc, Previous))
return nullptr;
if (IsUsingIfExists && UsingName.getName().getNameKind() ==
DeclarationName::CXXConstructorName) {
Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
return nullptr;
}
DeclContext *LookupContext = computeDeclContext(SS);
NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
if (!LookupContext || EllipsisLoc.isValid()) {
NamedDecl *D;
if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
SS, NameInfo, IdentLoc))
return nullptr;
if (HasTypenameKeyword) {
D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
UsingLoc, TypenameLoc,
QualifierLoc,
IdentLoc, NameInfo.getName(),
EllipsisLoc);
} else {
D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
QualifierLoc, NameInfo, EllipsisLoc);
}
D->setAccess(AS);
CurContext->addDecl(D);
ProcessDeclAttributeList(S, D, AttrList);
return D;
}
auto Build = [&](bool Invalid) {
UsingDecl *UD =
UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
UsingName, HasTypenameKeyword);
UD->setAccess(AS);
CurContext->addDecl(UD);
ProcessDeclAttributeList(S, UD, AttrList);
UD->setInvalidDecl(Invalid);
return UD;
};
auto BuildInvalid = [&]{ return Build(true); };
auto BuildValid = [&]{ return Build(false); };
if (RequireCompleteDeclContext(SS, LookupContext))
return BuildInvalid();
LookupResult R(*this, NameInfo, LookupOrdinaryName);
if (!IsInstantiation)
R.setHideTags(false);
if (CurContext->isRecord()) {
R.setBaseObjectType(
Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
}
LookupQualifiedName(R, LookupContext);
if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
IdentLoc, &R))
return nullptr;
if (R.empty() && IsUsingIfExists)
R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
UsingName.getName()),
AS_public);
if (R.empty() &&
NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
auto *II = NameInfo.getName().getAsIdentifierInfo();
if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
CurContext->isStdNamespace() &&
isa<TranslationUnitDecl>(LookupContext) &&
getSourceManager().isInSystemHeader(UsingLoc))
return nullptr;
UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
dyn_cast<CXXRecordDecl>(CurContext));
if (TypoCorrection Corrected =
CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
CTK_ErrorRecovery)) {
diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
<< NameInfo.getName() << LookupContext << 0
<< SS.getRange());
NamedDecl *ND = Corrected.getCorrectionDecl();
if (!ND)
return BuildInvalid();
auto *RD = dyn_cast<CXXRecordDecl>(ND);
if (RD && RD->isInjectedClassName()) {
RD = cast<CXXRecordDecl>(RD->getParent());
if (Corrected.WillReplaceSpecifier()) {
NestedNameSpecifierLocBuilder Builder;
Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
QualifierLoc.getSourceRange());
QualifierLoc = Builder.getWithLocInContext(Context);
}
auto *CurClass = cast<CXXRecordDecl>(CurContext);
UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
Context.getCanonicalType(Context.getRecordType(CurClass))));
UsingName.setNamedTypeInfo(nullptr);
for (auto *Ctor : LookupConstructors(RD))
R.addDecl(Ctor);
R.resolveKind();
} else {
UsingName.setName(ND->getDeclName());
R.addDecl(ND);
}
} else {
Diag(IdentLoc, diag::err_no_member)
<< NameInfo.getName() << LookupContext << SS.getRange();
return BuildInvalid();
}
}
if (R.isAmbiguous())
return BuildInvalid();
if (HasTypenameKeyword) {
if (!R.getAsSingle<TypeDecl>() &&
!R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
Diag(IdentLoc, diag::err_using_typename_non_type);
for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
Diag((*I)->getUnderlyingDecl()->getLocation(),
diag::note_using_decl_target);
return BuildInvalid();
}
} else {
if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
Diag(IdentLoc, diag::err_using_dependent_value_is_type);
Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
return BuildInvalid();
}
}
if (R.getAsSingle<NamespaceDecl>()) {
Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
<< SS.getRange();
return BuildInvalid();
}
UsingDecl *UD = BuildValid();
if (UsingName.getName().getNameKind() ==
DeclarationName::CXXConstructorName) {
R.suppressDiagnostics();
if (CheckInheritingConstructorUsingDecl(UD))
return UD;
}
for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
UsingShadowDecl *PrevDecl = nullptr;
if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
BuildUsingShadowDecl(S, UD, *I, PrevDecl);
}
return UD;
}
NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
SourceLocation UsingLoc,
SourceLocation EnumLoc,
SourceLocation NameLoc,
EnumDecl *ED) {
bool Invalid = false;
if (CurContext->getRedeclContext()->isRecord()) {
DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
ForVisibleRedeclaration);
LookupName(Previous, S);
for (NamedDecl *D : Previous)
if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
if (UED->getEnumDecl() == ED) {
Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
<< SourceRange(EnumLoc, NameLoc);
Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
Invalid = true;
break;
}
}
if (RequireCompleteEnumDecl(ED, NameLoc))
Invalid = true;
UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
EnumLoc, NameLoc, ED);
UD->setAccess(AS);
CurContext->addDecl(UD);
if (Invalid) {
UD->setInvalidDecl();
return UD;
}
for (EnumConstantDecl *EC : ED->enumerators()) {
UsingShadowDecl *PrevDecl = nullptr;
DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
LookupResult Previous(*this, DNI, LookupOrdinaryName,
ForVisibleRedeclaration);
LookupName(Previous, S);
FilterUsingLookup(S, Previous);
if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
BuildUsingShadowDecl(S, UD, EC, PrevDecl);
}
return UD;
}
NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
ArrayRef<NamedDecl *> Expansions) {
assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
isa<UsingPackDecl>(InstantiatedFrom));
auto *UPD =
UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
UPD->setAccess(InstantiatedFrom->getAccess());
CurContext->addDecl(UPD);
return UPD;
}
bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
assert(!UD->hasTypename() && "expecting a constructor name");
const Type *SourceType = UD->getQualifier()->getAsType();
assert(SourceType &&
"Using decl naming constructor doesn't have type in scope spec.");
CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
bool AnyDependentBases = false;
auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
AnyDependentBases);
if (!Base && !AnyDependentBases) {
Diag(UD->getUsingLoc(),
diag::err_using_decl_constructor_not_in_direct_base)
<< UD->getNameInfo().getSourceRange()
<< QualType(SourceType, 0) << TargetClass;
UD->setInvalidDecl();
return true;
}
if (Base)
Base->setInheritConstructors();
return false;
}
bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
bool HasTypenameKeyword,
const CXXScopeSpec &SS,
SourceLocation NameLoc,
const LookupResult &Prev) {
NestedNameSpecifier *Qual = SS.getScopeRep();
if (!CurContext->getRedeclContext()->isRecord()) {
if (Qual->isDependent() && !HasTypenameKeyword) {
for (auto *D : Prev) {
if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
bool OldCouldBeEnumerator =
isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
Diag(NameLoc,
OldCouldBeEnumerator ? diag::err_redefinition
: diag::err_redefinition_different_kind)
<< Prev.getLookupName();
Diag(D->getLocation(), diag::note_previous_definition);
return true;
}
}
}
return false;
}
const NestedNameSpecifier *CNNS =
Context.getCanonicalNestedNameSpecifier(Qual);
for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
NamedDecl *D = *I;
bool DTypename;
NestedNameSpecifier *DQual;
if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
DTypename = UD->hasTypename();
DQual = UD->getQualifier();
} else if (UnresolvedUsingValueDecl *UD
= dyn_cast<UnresolvedUsingValueDecl>(D)) {
DTypename = false;
DQual = UD->getQualifier();
} else if (UnresolvedUsingTypenameDecl *UD
= dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
DTypename = true;
DQual = UD->getQualifier();
} else continue;
if (HasTypenameKeyword != DTypename) continue;
if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
continue;
Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
Diag(D->getLocation(), diag::note_using_decl) << 1;
return true;
}
return false;
}
bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
SourceLocation NameLoc,
const LookupResult *R, const UsingDecl *UD) {
DeclContext *NamedContext = computeDeclContext(SS);
assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
"resolvable context must have exactly one set of decls");
bool Cxx20Enumerator = false;
if (NamedContext) {
EnumConstantDecl *EC = nullptr;
if (R)
EC = R->getAsSingle<EnumConstantDecl>();
else if (UD && UD->shadow_size() == 1)
EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
if (EC)
Cxx20Enumerator = getLangOpts().CPlusPlus20;
if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
if (EC && R && ED->isScoped())
Diag(SS.getBeginLoc(),
getLangOpts().CPlusPlus20
? diag::warn_cxx17_compat_using_decl_scoped_enumerator
: diag::ext_using_decl_scoped_enumerator)
<< SS.getRange();
NamedContext = ED->getDeclContext();
}
}
if (!CurContext->isRecord()) {
if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
: !HasTypename)
return false;
Diag(NameLoc,
Cxx20Enumerator
? diag::warn_cxx17_compat_using_decl_class_member_enumerator
: diag::err_using_decl_can_not_refer_to_class_member)
<< SS.getRange();
if (Cxx20Enumerator)
return false;
auto *RD = NamedContext
? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
: nullptr;
if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
if (!R) {
} else if (R->getAsSingle<TypeDecl>()) {
if (getLangOpts().CPlusPlus11) {
Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
<< 0 << FixItHint::CreateInsertion(SS.getBeginLoc(),
NameInfo.getName().getAsString() +
" = ");
} else {
SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
<< 1 << FixItHint::CreateReplacement(UsingLoc, "typedef")
<< FixItHint::CreateInsertion(
InsertLoc, " " + NameInfo.getName().getAsString());
}
} else if (R->getAsSingle<VarDecl>()) {
FixItHint FixIt;
if (getLangOpts().CPlusPlus11) {
FixIt = FixItHint::CreateReplacement(
UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
}
Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
<< 2 << FixIt;
} else if (R->getAsSingle<EnumConstantDecl>()) {
FixItHint FixIt;
if (getLangOpts().CPlusPlus11) {
FixIt = FixItHint::CreateReplacement(
UsingLoc,
"constexpr auto " + NameInfo.getName().getAsString() + " = ");
}
Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
<< (getLangOpts().CPlusPlus11 ? 4 : 3) << FixIt;
}
}
return true; }
if (!NamedContext) {
return false;
}
if (!NamedContext->isRecord()) {
Diag(SS.getBeginLoc(),
Cxx20Enumerator
? diag::warn_cxx17_compat_using_decl_non_member_enumerator
: diag::err_using_decl_nested_name_specifier_is_not_class)
<< SS.getScopeRep() << SS.getRange();
if (Cxx20Enumerator)
return false;
return true;
}
if (!NamedContext->isDependentContext() &&
RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
return true;
if (getLangOpts().CPlusPlus11) {
if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
cast<CXXRecordDecl>(NamedContext))) {
if (Cxx20Enumerator) {
Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
<< SS.getRange();
return false;
}
if (CurContext == NamedContext) {
Diag(SS.getBeginLoc(),
diag::err_using_decl_nested_name_specifier_is_current_class)
<< SS.getRange();
return !getLangOpts().CPlusPlus20;
}
if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
Diag(SS.getBeginLoc(),
diag::err_using_decl_nested_name_specifier_is_not_base_class)
<< SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
<< SS.getRange();
}
return true;
}
return false;
}
llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
auto Collect = [&Bases](const CXXRecordDecl *Base) {
Bases.insert(Base);
return true;
};
if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
return false;
auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
return !Bases.count(Base);
};
if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
!cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
return false;
Diag(SS.getRange().getBegin(),
diag::err_using_decl_nested_name_specifier_is_not_base_class)
<< SS.getScopeRep()
<< cast<CXXRecordDecl>(CurContext)
<< SS.getRange();
return true;
}
Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
MultiTemplateParamsArg TemplateParamLists,
SourceLocation UsingLoc, UnqualifiedId &Name,
const ParsedAttributesView &AttrList,
TypeResult Type, Decl *DeclFromDeclSpec) {
while (S->isTemplateParamScope())
S = S->getParent();
assert((S->getFlags() & Scope::DeclScope) &&
"got alias-declaration outside of declaration scope");
if (Type.isInvalid())
return nullptr;
bool Invalid = false;
DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
TypeSourceInfo *TInfo = nullptr;
GetTypeFromParser(Type.get(), &TInfo);
if (DiagnoseClassNameShadow(CurContext, NameInfo))
return nullptr;
if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
UPPC_DeclarationType)) {
Invalid = true;
TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
TInfo->getTypeLoc().getBeginLoc());
}
LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
TemplateParamLists.size()
? forRedeclarationInCurContext()
: ForVisibleRedeclaration);
LookupName(Previous, S);
if (Previous.isSingleResult() &&
Previous.getFoundDecl()->isTemplateParameter()) {
DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Previous.clear();
}
assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
"name in alias declaration must be an identifier");
TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
Name.StartLocation,
Name.Identifier, TInfo);
NewTD->setAccess(AS);
if (Invalid)
NewTD->setInvalidDecl();
ProcessDeclAttributeList(S, NewTD, AttrList);
AddPragmaAttributes(S, NewTD);
CheckTypedefForVariablyModifiedType(S, NewTD);
Invalid |= NewTD->isInvalidDecl();
bool Redeclaration = false;
NamedDecl *NewND;
if (TemplateParamLists.size()) {
TypeAliasTemplateDecl *OldDecl = nullptr;
TemplateParameterList *OldTemplateParams = nullptr;
if (TemplateParamLists.size() != 1) {
Diag(UsingLoc, diag::err_alias_template_extra_headers)
<< SourceRange(TemplateParamLists[1]->getTemplateLoc(),
TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
}
TemplateParameterList *TemplateParams = TemplateParamLists[0];
if (CheckTemplateDeclScope(S, TemplateParams))
return nullptr;
FilterLookupForScope(Previous, CurContext, S, false,
false);
if (!Previous.empty()) {
Redeclaration = true;
OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
if (!OldDecl && !Invalid) {
Diag(UsingLoc, diag::err_redefinition_different_kind)
<< Name.Identifier;
NamedDecl *OldD = Previous.getRepresentativeDecl();
if (OldD->getLocation().isValid())
Diag(OldD->getLocation(), diag::note_previous_definition);
Invalid = true;
}
if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
if (TemplateParameterListsAreEqual(TemplateParams,
OldDecl->getTemplateParameters(),
true,
TPL_TemplateMatch))
OldTemplateParams =
OldDecl->getMostRecentDecl()->getTemplateParameters();
else
Invalid = true;
TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
if (!Invalid &&
!Context.hasSameType(OldTD->getUnderlyingType(),
NewTD->getUnderlyingType())) {
Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
<< 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
if (OldTD->getLocation().isValid())
Diag(OldTD->getLocation(), diag::note_previous_definition);
Invalid = true;
}
}
}
if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
TPC_TypeAliasTemplate))
return nullptr;
TypeAliasTemplateDecl *NewDecl =
TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
Name.Identifier, TemplateParams,
NewTD);
NewTD->setDescribedAliasTemplate(NewDecl);
NewDecl->setAccess(AS);
if (Invalid)
NewDecl->setInvalidDecl();
else if (OldDecl) {
NewDecl->setPreviousDecl(OldDecl);
CheckRedeclarationInModule(NewDecl, OldDecl);
}
NewND = NewDecl;
} else {
if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
setTagNameForLinkagePurposes(TD, NewTD);
handleTagNumbering(TD, S);
}
ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
NewND = NewTD;
}
PushOnScopeChains(NewND, S);
ActOnDocumentableDecl(NewND);
return NewND;
}
Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
SourceLocation AliasLoc,
IdentifierInfo *Alias, CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *Ident) {
LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
LookupParsedName(R, S, &SS);
if (R.isAmbiguous())
return nullptr;
if (R.empty()) {
if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
return nullptr;
}
}
assert(!R.isAmbiguous() && !R.empty());
NamedDecl *ND = R.getRepresentativeDecl();
LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
ForVisibleRedeclaration);
LookupName(PrevR, S);
if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
PrevR.clear();
}
FilterLookupForScope(PrevR, CurContext, S, false,
false);
NamespaceAliasDecl *Prev = nullptr;
if (PrevR.isSingleResult()) {
NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
Prev = AD;
} else if (isVisible(PrevDecl)) {
Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
<< Alias;
Diag(AD->getLocation(), diag::note_previous_namespace_alias)
<< AD->getNamespace();
return nullptr;
}
} else if (isVisible(PrevDecl)) {
unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
? diag::err_redefinition
: diag::err_redefinition_different_kind;
Diag(AliasLoc, DiagID) << Alias;
Diag(PrevDecl->getLocation(), diag::note_previous_definition);
return nullptr;
}
}
DiagnoseUseOfDecl(ND, IdentLoc);
NamespaceAliasDecl *AliasDecl =
NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Alias, SS.getWithLocInContext(Context),
IdentLoc, ND);
if (Prev)
AliasDecl->setPreviousDecl(Prev);
PushOnScopeChains(AliasDecl, S);
return AliasDecl;
}
namespace {
struct SpecialMemberExceptionSpecInfo
: SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
SourceLocation Loc;
Sema::ImplicitExceptionSpecification ExceptSpec;
SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
Sema::CXXSpecialMember CSM,
Sema::InheritedConstructorInfo *ICI,
SourceLocation Loc)
: SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
bool visitBase(CXXBaseSpecifier *Base);
bool visitField(FieldDecl *FD);
void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
unsigned Quals);
void visitSubobjectCall(Subobject Subobj,
Sema::SpecialMemberOverloadResult SMOR);
};
}
bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
auto *RT = Base->getType()->getAs<RecordType>();
if (!RT)
return false;
auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
if (auto *BaseCtor = SMOR.getMethod()) {
visitSubobjectCall(Base, BaseCtor);
return false;
}
visitClassSubobject(BaseClass, Base, 0);
return false;
}
bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
Expr *E = FD->getInClassInitializer();
if (!E)
E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
if (E)
ExceptSpec.CalledExpr(E);
} else if (auto *RT = S.Context.getBaseElementType(FD->getType())
->getAs<RecordType>()) {
visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
FD->getType().getCVRQualifiers());
}
return false;
}
void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
Subobject Subobj,
unsigned Quals) {
FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
bool IsMutable = Field && Field->isMutable();
visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
}
void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
if (CXXMethodDecl *MD = SMOR.getMethod())
ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
}
bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
llvm::APSInt Result;
ExprResult Converted = CheckConvertedConstantExpression(
ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
ExplicitSpec.setExpr(Converted.get());
if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
ExplicitSpec.setKind(Result.getBoolValue()
? ExplicitSpecKind::ResolvedTrue
: ExplicitSpecKind::ResolvedFalse);
return true;
}
ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
return false;
}
ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
if (!ExplicitExpr->isTypeDependent())
tryResolveExplicitSpecifier(ES);
return ES;
}
static Sema::ImplicitExceptionSpecification
ComputeDefaultedSpecialMemberExceptionSpec(
Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
Sema::InheritedConstructorInfo *ICI) {
ComputingExceptionSpec CES(S, MD, Loc);
CXXRecordDecl *ClassDecl = MD->getParent();
SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
if (ClassDecl->isInvalidDecl())
return Info.ExceptSpec;
if (S.RequireCompleteType(MD->getLocation(),
S.Context.getRecordType(ClassDecl),
diag::err_exception_spec_incomplete_type))
return Info.ExceptSpec;
Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
: Info.VisitAllBases);
return Info.ExceptSpec;
}
namespace {
struct DeclaringSpecialMember {
Sema &S;
Sema::SpecialMemberDecl D;
Sema::ContextRAII SavedContext;
bool WasAlreadyBeingDeclared;
DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
: S(S), D(RD, CSM), SavedContext(S, RD) {
WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
if (WasAlreadyBeingDeclared)
S.SpecialMemberCache.clear();
else {
Sema::CodeSynthesisContext Ctx;
Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
Ctx.PointOfInstantiation = RD->getLocation();
Ctx.Entity = RD;
Ctx.SpecialMember = CSM;
S.pushCodeSynthesisContext(Ctx);
}
}
~DeclaringSpecialMember() {
if (!WasAlreadyBeingDeclared) {
S.SpecialMembersBeingDeclared.erase(D);
S.popCodeSynthesisContext();
}
}
bool isAlreadyBeingDeclared() const {
return WasAlreadyBeingDeclared;
}
};
}
void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
DeclarationName Name = FD->getDeclName();
LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
ForExternalRedeclaration);
for (auto *D : FD->getParent()->lookup(Name))
if (auto *Acceptable = R.getAcceptableDecl(D))
R.addDecl(Acceptable);
R.resolveKind();
R.suppressDiagnostics();
CheckFunctionDeclaration(S, FD, R, false,
FD->isThisDeclarationADefinition());
}
void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
QualType ResultTy,
ArrayRef<QualType> Args) {
FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
LangAS AS = getDefaultCXXMethodAddrSpace();
if (AS != LangAS::Default) {
EPI.TypeQuals.addAddressSpace(AS);
}
auto QT = Context.getFunctionType(ResultTy, Args, EPI);
SpecialMem->setType(QT);
if (inTemplateInstantiation() &&
cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
TypeSourceInfo *TSI =
Context.getTrivialTypeSourceInfo(SpecialMem->getType());
SpecialMem->setTypeSourceInfo(TSI);
}
}
CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
CXXRecordDecl *ClassDecl) {
assert(ClassDecl->needsImplicitDefaultConstructor() &&
"Should not build implicit default constructor!");
DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
if (DSM.isAlreadyBeingDeclared())
return nullptr;
bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
CXXDefaultConstructor,
false);
CanQualType ClassType
= Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
SourceLocation ClassLoc = ClassDecl->getLocation();
DeclarationName Name
= Context.DeclarationNames.getCXXConstructorName(ClassType);
DeclarationNameInfo NameInfo(Name, ClassLoc);
CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Context, ClassDecl, ClassLoc, NameInfo, QualType(),
nullptr, ExplicitSpecifier(),
getCurFPFeatures().isFPConstrained(),
true, true,
Constexpr ? ConstexprSpecKind::Constexpr
: ConstexprSpecKind::Unspecified);
DefaultCon->setAccess(AS_public);
DefaultCon->setDefaulted();
setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
if (getLangOpts().CUDA)
inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
DefaultCon,
false,
false);
DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
++getASTContext().NumImplicitDefaultConstructorsDeclared;
Scope *S = getScopeForContext(ClassDecl);
CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
SetDeclDeleted(DefaultCon, ClassLoc);
if (S)
PushOnScopeChains(DefaultCon, S, false);
ClassDecl->addDecl(DefaultCon);
return DefaultCon;
}
void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor) {
assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
!Constructor->doesThisDeclarationHaveABody() &&
!Constructor->isDeleted()) &&
"DefineImplicitDefaultConstructor - call it for implicit default ctor");
if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
return;
CXXRecordDecl *ClassDecl = Constructor->getParent();
assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
SynthesizedFunctionScope Scope(*this, Constructor);
ResolveExceptionSpec(CurrentLocation,
Constructor->getType()->castAs<FunctionProtoType>());
MarkVTableUsed(CurrentLocation, ClassDecl);
Scope.addContextNote(CurrentLocation);
if (SetCtorInitializers(Constructor, false)) {
Constructor->setInvalidDecl();
return;
}
SourceLocation Loc = Constructor->getEndLoc().isValid()
? Constructor->getEndLoc()
: Constructor->getLocation();
Constructor->setBody(new (Context) CompoundStmt(Loc));
Constructor->markUsed(Context);
if (ASTMutationListener *L = getASTMutationListener()) {
L->CompletedImplicitDefinition(Constructor);
}
DiagnoseUninitializedFields(*this, Constructor);
}
void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
CheckDelayedMemberExceptionSpecs();
}
CXXConstructorDecl *
Sema::findInheritingConstructor(SourceLocation Loc,
CXXConstructorDecl *BaseCtor,
ConstructorUsingShadowDecl *Shadow) {
CXXRecordDecl *Derived = Shadow->getParent();
SourceLocation UsingLoc = Shadow->getLocation();
DeclarationName Name = BaseCtor->getDeclName();
for (NamedDecl *Ctor : Derived->lookup(Name))
if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
->getInheritedConstructor()
.getConstructor(),
BaseCtor))
return cast<CXXConstructorDecl>(Ctor);
DeclarationNameInfo NameInfo(Name, UsingLoc);
TypeSourceInfo *TInfo =
Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
FunctionProtoTypeLoc ProtoLoc =
TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
InheritedConstructorInfo ICI(*this, Loc, Shadow);
bool Constexpr =
BaseCtor->isConstexpr() &&
defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
false, BaseCtor, &ICI);
CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
true,
true,
Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
InheritedConstructor(Shadow, BaseCtor),
BaseCtor->getTrailingRequiresClause());
if (Shadow->isInvalidDecl())
DerivedCtor->setInvalidDecl();
const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
EPI.ExceptionSpec.Type = EST_Unevaluated;
EPI.ExceptionSpec.SourceDecl = DerivedCtor;
DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
FPT->getParamTypes(), EPI));
SmallVector<ParmVarDecl *, 16> ParamDecls;
for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
TypeSourceInfo *TInfo =
Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
ParmVarDecl *PD = ParmVarDecl::Create(
Context, DerivedCtor, UsingLoc, UsingLoc, nullptr,
FPT->getParamType(I), TInfo, SC_None, nullptr);
PD->setScopeInfo(0, I);
PD->setImplicit();
mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
ParamDecls.push_back(PD);
ProtoLoc.setParam(I, PD);
}
assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
DerivedCtor->setAccess(BaseCtor->getAccess());
DerivedCtor->setParams(ParamDecls);
Derived->addDecl(DerivedCtor);
if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
SetDeclDeleted(DerivedCtor, UsingLoc);
return DerivedCtor;
}
void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
Ctor->getInheritedConstructor().getShadowDecl());
ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
true);
}
void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor) {
CXXRecordDecl *ClassDecl = Constructor->getParent();
assert(Constructor->getInheritedConstructor() &&
!Constructor->doesThisDeclarationHaveABody() &&
!Constructor->isDeleted());
if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
return;
SynthesizedFunctionScope Scope(*this, Constructor);
ResolveExceptionSpec(CurrentLocation,
Constructor->getType()->castAs<FunctionProtoType>());
MarkVTableUsed(CurrentLocation, ClassDecl);
Scope.addContextNote(CurrentLocation);
ConstructorUsingShadowDecl *Shadow =
Constructor->getInheritedConstructor().getShadowDecl();
CXXConstructorDecl *InheritedCtor =
Constructor->getInheritedConstructor().getConstructor();
InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
CXXRecordDecl *RD = Shadow->getParent();
SourceLocation InitLoc = Shadow->getLocation();
SmallVector<CXXCtorInitializer*, 8> Inits;
for (bool VBase : {false, true}) {
for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
if (B.isVirtual() != VBase)
continue;
auto *BaseRD = B.getType()->getAsCXXRecordDecl();
if (!BaseRD)
continue;
auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
if (!BaseCtor.first)
continue;
MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
Inits.push_back(new (Context) CXXCtorInitializer(
Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
SourceLocation()));
}
}
if (SetCtorInitializers(Constructor, false, Inits)) {
Constructor->setInvalidDecl();
return;
}
Constructor->setBody(new (Context) CompoundStmt(InitLoc));
Constructor->markUsed(Context);
if (ASTMutationListener *L = getASTMutationListener()) {
L->CompletedImplicitDefinition(Constructor);
}
DiagnoseUninitializedFields(*this, Constructor);
}
CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
assert(ClassDecl->needsImplicitDestructor());
DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
if (DSM.isAlreadyBeingDeclared())
return nullptr;
bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
CXXDestructor,
false);
CanQualType ClassType
= Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
SourceLocation ClassLoc = ClassDecl->getLocation();
DeclarationName Name
= Context.DeclarationNames.getCXXDestructorName(ClassType);
DeclarationNameInfo NameInfo(Name, ClassLoc);
CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
getCurFPFeatures().isFPConstrained(),
true,
true,
Constexpr ? ConstexprSpecKind::Constexpr
: ConstexprSpecKind::Unspecified);
Destructor->setAccess(AS_public);
Destructor->setDefaulted();
setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
if (getLangOpts().CUDA)
inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
Destructor,
false,
false);
Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
ClassDecl->hasTrivialDestructorForCall());
++getASTContext().NumImplicitDestructorsDeclared;
Scope *S = getScopeForContext(ClassDecl);
CheckImplicitSpecialMemberDeclaration(S, Destructor);
if (ClassDecl->isCompleteDefinition() &&
ShouldDeleteSpecialMember(Destructor, CXXDestructor))
SetDeclDeleted(Destructor, ClassLoc);
if (S)
PushOnScopeChains(Destructor, S, false);
ClassDecl->addDecl(Destructor);
return Destructor;
}
void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
CXXDestructorDecl *Destructor) {
assert((Destructor->isDefaulted() &&
!Destructor->doesThisDeclarationHaveABody() &&
!Destructor->isDeleted()) &&
"DefineImplicitDestructor - call it for implicit default dtor");
if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
return;
CXXRecordDecl *ClassDecl = Destructor->getParent();
assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
SynthesizedFunctionScope Scope(*this, Destructor);
ResolveExceptionSpec(CurrentLocation,
Destructor->getType()->castAs<FunctionProtoType>());
MarkVTableUsed(CurrentLocation, ClassDecl);
Scope.addContextNote(CurrentLocation);
MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
Destructor->getParent());
if (CheckDestructor(Destructor)) {
Destructor->setInvalidDecl();
return;
}
SourceLocation Loc = Destructor->getEndLoc().isValid()
? Destructor->getEndLoc()
: Destructor->getLocation();
Destructor->setBody(new (Context) CompoundStmt(Loc));
Destructor->markUsed(Context);
if (ASTMutationListener *L = getASTMutationListener()) {
L->CompletedImplicitDefinition(Destructor);
}
}
void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
CXXDestructorDecl *Destructor) {
if (Destructor->isInvalidDecl())
return;
CXXRecordDecl *ClassDecl = Destructor->getParent();
assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
"implicit complete dtors unneeded outside MS ABI");
assert(ClassDecl->getNumVBases() > 0 &&
"complete dtor only exists for classes with vbases");
SynthesizedFunctionScope Scope(*this, Destructor);
Scope.addContextNote(CurrentLocation);
MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
}
void Sema::ActOnFinishCXXMemberDecls() {
if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
if (Record->isInvalidDecl()) {
DelayedOverridingExceptionSpecChecks.clear();
DelayedEquivalentExceptionSpecChecks.clear();
return;
}
checkForMultipleExportedDefaultConstructors(*this, Record);
}
}
void Sema::ActOnFinishCXXNonNestedClass() {
referenceDLLExportedClassMethods();
if (!DelayedDllExportMemberFunctions.empty()) {
SmallVector<CXXMethodDecl*, 4> WorkList;
std::swap(DelayedDllExportMemberFunctions, WorkList);
for (CXXMethodDecl *M : WorkList) {
DefineDefaultedFunction(*this, M, M->getLocation());
if (M->getParent()->getTemplateSpecializationKind() !=
TSK_ExplicitInstantiationDefinition)
ActOnFinishInlineFunctionDef(M);
}
}
}
void Sema::referenceDLLExportedClassMethods() {
if (!DelayedDllExportClasses.empty()) {
SmallVector<CXXRecordDecl *, 4> WorkList;
std::swap(DelayedDllExportClasses, WorkList);
for (CXXRecordDecl *Class : WorkList)
ReferenceDllExportedMembers(*this, Class);
}
}
void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
assert(getLangOpts().CPlusPlus11 &&
"adjusting dtor exception specs was introduced in c++11");
if (Destructor->isDependentContext())
return;
const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
if (DtorType->hasExceptionSpec())
return;
FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
EPI.ExceptionSpec.Type = EST_Unevaluated;
EPI.ExceptionSpec.SourceDecl = Destructor;
Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
}
namespace {
class ExprBuilder {
ExprBuilder(const ExprBuilder&) = delete;
ExprBuilder &operator=(const ExprBuilder&) = delete;
protected:
static Expr *assertNotNull(Expr *E) {
assert(E && "Expression construction must not fail.");
return E;
}
public:
ExprBuilder() {}
virtual ~ExprBuilder() {}
virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
};
class RefBuilder: public ExprBuilder {
VarDecl *Var;
QualType VarType;
public:
Expr *build(Sema &S, SourceLocation Loc) const override {
return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
}
RefBuilder(VarDecl *Var, QualType VarType)
: Var(Var), VarType(VarType) {}
};
class ThisBuilder: public ExprBuilder {
public:
Expr *build(Sema &S, SourceLocation Loc) const override {
return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
}
};
class CastBuilder: public ExprBuilder {
const ExprBuilder &Builder;
QualType Type;
ExprValueKind Kind;
const CXXCastPath &Path;
public:
Expr *build(Sema &S, SourceLocation Loc) const override {
return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
CK_UncheckedDerivedToBase, Kind,
&Path).get());
}
CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
const CXXCastPath &Path)
: Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
};
class DerefBuilder: public ExprBuilder {
const ExprBuilder &Builder;
public:
Expr *build(Sema &S, SourceLocation Loc) const override {
return assertNotNull(
S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
}
DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
};
class MemberBuilder: public ExprBuilder {
const ExprBuilder &Builder;
QualType Type;
CXXScopeSpec SS;
bool IsArrow;
LookupResult &MemberLookup;
public:
Expr *build(Sema &S, SourceLocation Loc) const override {
return assertNotNull(S.BuildMemberReferenceExpr(
Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
nullptr, MemberLookup, nullptr, nullptr).get());
}
MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
LookupResult &MemberLookup)
: Builder(Builder), Type(Type), IsArrow(IsArrow),
MemberLookup(MemberLookup) {}
};
class MoveCastBuilder: public ExprBuilder {
const ExprBuilder &Builder;
public:
Expr *build(Sema &S, SourceLocation Loc) const override {
return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
}
MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
};
class LvalueConvBuilder: public ExprBuilder {
const ExprBuilder &Builder;
public:
Expr *build(Sema &S, SourceLocation Loc) const override {
return assertNotNull(
S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
}
LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
};
class SubscriptBuilder: public ExprBuilder {
const ExprBuilder &Base;
const ExprBuilder &Index;
public:
Expr *build(Sema &S, SourceLocation Loc) const override {
return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
}
SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
: Base(Base), Index(Index) {}
};
}
static StmtResult
buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
const ExprBuilder &ToB, const ExprBuilder &FromB) {
QualType SizeType = S.Context.getSizeType();
llvm::APInt Size(S.Context.getTypeSize(SizeType),
S.Context.getTypeSizeInChars(T).getQuantity());
Expr *From = FromB.build(S, Loc);
From = UnaryOperator::Create(
S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
Expr *To = ToB.build(S, Loc);
To = UnaryOperator::Create(
S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
const Type *E = T->getBaseElementTypeUnsafe();
bool NeedsCollectableMemCpy =
E->isRecordType() &&
E->castAs<RecordType>()->getDecl()->hasObjectMember();
StringRef MemCpyName = NeedsCollectableMemCpy ?
"__builtin_objc_memmove_collectable" :
"__builtin_memcpy";
LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
Sema::LookupOrdinaryName);
S.LookupName(R, S.TUScope, true);
FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
if (!MemCpy)
return StmtError();
ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
VK_PRValue, Loc, nullptr);
assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
Expr *CallArgs[] = {
To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
};
ExprResult Call = S.BuildCallExpr(nullptr, MemCpyRef.get(),
Loc, CallArgs, Loc);
assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
return Call.getAs<Stmt>();
}
static StmtResult
buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
const ExprBuilder &To, const ExprBuilder &From,
bool CopyingBaseSubobject, bool Copying,
unsigned Depth = 0) {
if (const RecordType *RecordTy = T->getAs<RecordType>()) {
CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
DeclarationName Name
= S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
S.LookupQualifiedName(OpLookup, ClassDecl, false);
if (!S.getLangOpts().CPlusPlus11) {
LookupResult::Filter F = OpLookup.makeFilter();
while (F.hasNext()) {
NamedDecl *D = F.next();
if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
if (Method->isCopyAssignmentOperator() ||
(!Copying && Method->isMoveAssignmentOperator()))
continue;
F.erase();
}
F.done();
}
if (CopyingBaseSubobject) {
for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
L != LEnd; ++L) {
if (L.getAccess() == AS_protected)
L.setAccess(AS_public);
}
}
CXXScopeSpec SS;
const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
SS.MakeTrivial(S.Context,
NestedNameSpecifier::Create(S.Context, nullptr, false,
CanonicalT),
Loc);
ExprResult OpEqualRef
= S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, false,
SS, SourceLocation(),
nullptr,
OpLookup,
nullptr, nullptr,
true);
if (OpEqualRef.isInvalid())
return StmtError();
Expr *FromInst = From.build(S, Loc);
ExprResult Call = S.BuildCallToMemberFunction(nullptr,
OpEqualRef.getAs<Expr>(),
Loc, FromInst, Loc);
if (Call.isInvalid())
return StmtError();
CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
if (CE && CE->getMethodDecl()->isTrivial() && Depth)
return StmtResult((Stmt*)nullptr);
return S.ActOnExprStmt(Call);
}
const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
if (!ArrayTy) {
ExprResult Assignment = S.CreateBuiltinBinOp(
Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
if (Assignment.isInvalid())
return StmtError();
return S.ActOnExprStmt(Assignment);
}
QualType SizeType = S.Context.getSizeType();
IdentifierInfo *IterationVarName = nullptr;
{
SmallString<8> Str;
llvm::raw_svector_ostream OS(Str);
OS << "__i" << Depth;
IterationVarName = &S.Context.Idents.get(OS.str());
}
VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
IterationVarName, SizeType,
S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
SC_None);
llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
RefBuilder IterationVarRef(IterationVar, SizeType);
LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
MoveCastBuilder FromIndexMove(FromIndexCopy);
const ExprBuilder *FromIndex;
if (Copying)
FromIndex = &FromIndexCopy;
else
FromIndex = &FromIndexMove;
SubscriptBuilder ToIndex(To, IterationVarRefRVal);
StmtResult Copy =
buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
ToIndex, *FromIndex, CopyingBaseSubobject,
Copying, Depth + 1);
if (Copy.isInvalid() || !Copy.get())
return Copy;
llvm::APInt Upper
= ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
Expr *Comparison = BinaryOperator::Create(
S.Context, IterationVarRefRVal.build(S, Loc),
IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
S.CurFPFeatureOverrides());
Expr *Increment = UnaryOperator::Create(
S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
return S.ActOnForStmt(
Loc, Loc, InitStmt,
S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
}
static StmtResult
buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
const ExprBuilder &To, const ExprBuilder &From,
bool CopyingBaseSubobject, bool Copying) {
if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
T.isTriviallyCopyableType(S.Context))
return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
CopyingBaseSubobject,
Copying, 0));
if (!Result.isInvalid() && !Result.get())
return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
return Result;
}
CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
assert(ClassDecl->needsImplicitCopyAssignment());
DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
if (DSM.isAlreadyBeingDeclared())
return nullptr;
QualType ArgType = Context.getTypeDeclType(ClassDecl);
LangAS AS = getDefaultCXXMethodAddrSpace();
if (AS != LangAS::Default)
ArgType = Context.getAddrSpaceQualType(ArgType, AS);
QualType RetType = Context.getLValueReferenceType(ArgType);
bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
if (Const)
ArgType = ArgType.withConst();
ArgType = Context.getLValueReferenceType(ArgType);
bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
CXXCopyAssignment,
Const);
DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
SourceLocation ClassLoc = ClassDecl->getLocation();
DeclarationNameInfo NameInfo(Name, ClassLoc);
CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
Context, ClassDecl, ClassLoc, NameInfo, QualType(),
nullptr, SC_None,
getCurFPFeatures().isFPConstrained(),
true,
Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
SourceLocation());
CopyAssignment->setAccess(AS_public);
CopyAssignment->setDefaulted();
CopyAssignment->setImplicit();
setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
if (getLangOpts().CUDA)
inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
CopyAssignment,
Const,
false);
ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
ClassLoc, ClassLoc,
nullptr, ArgType,
nullptr, SC_None,
nullptr);
CopyAssignment->setParams(FromParam);
CopyAssignment->setTrivial(
ClassDecl->needsOverloadResolutionForCopyAssignment()
? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
: ClassDecl->hasTrivialCopyAssignment());
++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
Scope *S = getScopeForContext(ClassDecl);
CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
ClassDecl->setImplicitCopyAssignmentIsDeleted();
SetDeclDeleted(CopyAssignment, ClassLoc);
}
if (S)
PushOnScopeChains(CopyAssignment, S, false);
ClassDecl->addDecl(CopyAssignment);
return CopyAssignment;
}
static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
assert(CopyOp->isImplicit());
CXXRecordDecl *RD = CopyOp->getParent();
CXXMethodDecl *UserDeclaredOperation = nullptr;
if (RD->hasUserDeclaredDestructor()) {
UserDeclaredOperation = RD->getDestructor();
} else if (!isa<CXXConstructorDecl>(CopyOp) &&
RD->hasUserDeclaredCopyConstructor() &&
!S.getLangOpts().MSVCCompat) {
for (auto *I : RD->ctors()) {
if (I->isCopyConstructor()) {
UserDeclaredOperation = I;
break;
}
}
assert(UserDeclaredOperation);
} else if (isa<CXXConstructorDecl>(CopyOp) &&
RD->hasUserDeclaredCopyAssignment() &&
!S.getLangOpts().MSVCCompat) {
for (auto *I : RD->methods()) {
if (I->isCopyAssignmentOperator()) {
UserDeclaredOperation = I;
break;
}
}
assert(UserDeclaredOperation);
}
if (UserDeclaredOperation) {
bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
unsigned DiagID =
(UDOIsUserProvided && UDOIsDestructor)
? diag::warn_deprecated_copy_with_user_provided_dtor
: (UDOIsUserProvided && !UDOIsDestructor)
? diag::warn_deprecated_copy_with_user_provided_copy
: (!UDOIsUserProvided && UDOIsDestructor)
? diag::warn_deprecated_copy_with_dtor
: diag::warn_deprecated_copy;
S.Diag(UserDeclaredOperation->getLocation(), DiagID)
<< RD << IsCopyAssignment;
}
}
void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *CopyAssignOperator) {
assert((CopyAssignOperator->isDefaulted() &&
CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) &&
"DefineImplicitCopyAssignment called for wrong function");
if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
return;
CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
if (ClassDecl->isInvalidDecl()) {
CopyAssignOperator->setInvalidDecl();
return;
}
SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
ResolveExceptionSpec(CurrentLocation,
CopyAssignOperator->getType()->castAs<FunctionProtoType>());
Scope.addContextNote(CurrentLocation);
if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
SmallVector<Stmt*, 8> Statements;
ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
Qualifiers OtherQuals = Other->getType().getQualifiers();
QualType OtherRefType = Other->getType();
if (const LValueReferenceType *OtherRef
= OtherRefType->getAs<LValueReferenceType>()) {
OtherRefType = OtherRef->getPointeeType();
OtherQuals = OtherRefType.getQualifiers();
}
SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
? CopyAssignOperator->getEndLoc()
: CopyAssignOperator->getLocation();
RefBuilder OtherRef(Other, OtherRefType);
ThisBuilder This;
bool Invalid = false;
for (auto &Base : ClassDecl->bases()) {
QualType BaseType = Base.getType().getUnqualifiedType();
if (!BaseType->isRecordType()) {
Invalid = true;
continue;
}
CXXCastPath BasePath;
BasePath.push_back(&Base);
CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
VK_LValue, BasePath);
DerefBuilder DerefThis(This);
CastBuilder To(DerefThis,
Context.getQualifiedType(
BaseType, CopyAssignOperator->getMethodQualifiers()),
VK_LValue, BasePath);
StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
To, From,
true,
true);
if (Copy.isInvalid()) {
CopyAssignOperator->setInvalidDecl();
return;
}
Statements.push_back(Copy.getAs<Expr>());
}
for (auto *Field : ClassDecl->fields()) {
if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
continue;
if (Field->isInvalidDecl()) {
Invalid = true;
continue;
}
if (Field->getType()->isReferenceType()) {
Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
<< Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
Diag(Field->getLocation(), diag::note_declared_at);
Invalid = true;
continue;
}
QualType BaseType = Context.getBaseElementType(Field->getType());
if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
<< Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
Diag(Field->getLocation(), diag::note_declared_at);
Invalid = true;
continue;
}
if (Field->isZeroLengthBitField(Context))
continue;
QualType FieldType = Field->getType().getNonReferenceType();
if (FieldType->isIncompleteArrayType()) {
assert(ClassDecl->hasFlexibleArrayMember() &&
"Incomplete array type is not valid");
continue;
}
CXXScopeSpec SS; LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
LookupMemberName);
MemberLookup.addDecl(Field);
MemberLookup.resolveKind();
MemberBuilder From(OtherRef, OtherRefType, false, MemberLookup);
MemberBuilder To(This, getCurrentThisType(), true, MemberLookup);
StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
To, From,
false,
true);
if (Copy.isInvalid()) {
CopyAssignOperator->setInvalidDecl();
return;
}
Statements.push_back(Copy.getAs<Stmt>());
}
if (!Invalid) {
ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
if (Return.isInvalid())
Invalid = true;
else
Statements.push_back(Return.getAs<Stmt>());
}
if (Invalid) {
CopyAssignOperator->setInvalidDecl();
return;
}
StmtResult Body;
{
CompoundScopeRAII CompoundScope(*this);
Body = ActOnCompoundStmt(Loc, Loc, Statements,
false);
assert(!Body.isInvalid() && "Compound statement creation cannot fail");
}
CopyAssignOperator->setBody(Body.getAs<Stmt>());
CopyAssignOperator->markUsed(Context);
if (ASTMutationListener *L = getASTMutationListener()) {
L->CompletedImplicitDefinition(CopyAssignOperator);
}
}
CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
assert(ClassDecl->needsImplicitMoveAssignment());
DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
if (DSM.isAlreadyBeingDeclared())
return nullptr;
QualType ArgType = Context.getTypeDeclType(ClassDecl);
LangAS AS = getDefaultCXXMethodAddrSpace();
if (AS != LangAS::Default)
ArgType = Context.getAddrSpaceQualType(ArgType, AS);
QualType RetType = Context.getLValueReferenceType(ArgType);
ArgType = Context.getRValueReferenceType(ArgType);
bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
CXXMoveAssignment,
false);
DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
SourceLocation ClassLoc = ClassDecl->getLocation();
DeclarationNameInfo NameInfo(Name, ClassLoc);
CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
Context, ClassDecl, ClassLoc, NameInfo, QualType(),
nullptr, SC_None,
getCurFPFeatures().isFPConstrained(),
true,
Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
SourceLocation());
MoveAssignment->setAccess(AS_public);
MoveAssignment->setDefaulted();
MoveAssignment->setImplicit();
setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
if (getLangOpts().CUDA)
inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
MoveAssignment,
false,
false);
ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
ClassLoc, ClassLoc,
nullptr, ArgType,
nullptr, SC_None,
nullptr);
MoveAssignment->setParams(FromParam);
MoveAssignment->setTrivial(
ClassDecl->needsOverloadResolutionForMoveAssignment()
? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
: ClassDecl->hasTrivialMoveAssignment());
++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
Scope *S = getScopeForContext(ClassDecl);
CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
ClassDecl->setImplicitMoveAssignmentIsDeleted();
SetDeclDeleted(MoveAssignment, ClassLoc);
}
if (S)
PushOnScopeChains(MoveAssignment, S, false);
ClassDecl->addDecl(MoveAssignment);
return MoveAssignment;
}
static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
SourceLocation CurrentLocation) {
assert(!Class->isDependentContext() && "should not define dependent move");
if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
Class->getNumBases() < 2)
return;
llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
VBaseMap VBases;
for (auto &BI : Class->bases()) {
Worklist.push_back(&BI);
while (!Worklist.empty()) {
CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
if (!Base->hasNonTrivialMoveAssignment())
continue;
if (!BaseSpec->isVirtual() && !Base->getNumVBases())
continue;
Sema::SpecialMemberOverloadResult SMOR =
S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
false, false,
true, false,
false);
if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
!SMOR.getMethod()->isMoveAssignmentOperator())
continue;
if (BaseSpec->isVirtual()) {
CXXBaseSpecifier *&Existing =
VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
.first->second;
if (Existing && Existing != &BI) {
S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
<< Class << Base;
S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
<< (Base->getCanonicalDecl() ==
Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
<< Base << Existing->getType() << Existing->getSourceRange();
S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
<< (Base->getCanonicalDecl() ==
BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
<< Base << BI.getType() << BaseSpec->getSourceRange();
Existing = nullptr;
}
} else {
if (!SMOR.getMethod()->isDefaulted())
continue;
llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
}
}
}
}
void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MoveAssignOperator) {
assert((MoveAssignOperator->isDefaulted() &&
MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) &&
"DefineImplicitMoveAssignment called for wrong function");
if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
return;
CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
if (ClassDecl->isInvalidDecl()) {
MoveAssignOperator->setInvalidDecl();
return;
}
checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
ResolveExceptionSpec(CurrentLocation,
MoveAssignOperator->getType()->castAs<FunctionProtoType>());
Scope.addContextNote(CurrentLocation);
SmallVector<Stmt*, 8> Statements;
ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
QualType OtherRefType =
Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
? MoveAssignOperator->getEndLoc()
: MoveAssignOperator->getLocation();
RefBuilder OtherRef(Other, OtherRefType);
MoveCastBuilder MoveOther(OtherRef);
ThisBuilder This;
bool Invalid = false;
for (auto &Base : ClassDecl->bases()) {
QualType BaseType = Base.getType().getUnqualifiedType();
if (!BaseType->isRecordType()) {
Invalid = true;
continue;
}
CXXCastPath BasePath;
BasePath.push_back(&Base);
CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
DerefBuilder DerefThis(This);
CastBuilder To(DerefThis,
Context.getQualifiedType(
BaseType, MoveAssignOperator->getMethodQualifiers()),
VK_LValue, BasePath);
StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
To, From,
true,
false);
if (Move.isInvalid()) {
MoveAssignOperator->setInvalidDecl();
return;
}
Statements.push_back(Move.getAs<Expr>());
}
for (auto *Field : ClassDecl->fields()) {
if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
continue;
if (Field->isInvalidDecl()) {
Invalid = true;
continue;
}
if (Field->getType()->isReferenceType()) {
Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
<< Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
Diag(Field->getLocation(), diag::note_declared_at);
Invalid = true;
continue;
}
QualType BaseType = Context.getBaseElementType(Field->getType());
if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
<< Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
Diag(Field->getLocation(), diag::note_declared_at);
Invalid = true;
continue;
}
if (Field->isZeroLengthBitField(Context))
continue;
QualType FieldType = Field->getType().getNonReferenceType();
if (FieldType->isIncompleteArrayType()) {
assert(ClassDecl->hasFlexibleArrayMember() &&
"Incomplete array type is not valid");
continue;
}
LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
LookupMemberName);
MemberLookup.addDecl(Field);
MemberLookup.resolveKind();
MemberBuilder From(MoveOther, OtherRefType,
false, MemberLookup);
MemberBuilder To(This, getCurrentThisType(),
true, MemberLookup);
assert(!From.build(*this, Loc)->isLValue() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.");
StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
To, From,
false,
false);
if (Move.isInvalid()) {
MoveAssignOperator->setInvalidDecl();
return;
}
Statements.push_back(Move.getAs<Stmt>());
}
if (!Invalid) {
ExprResult ThisObj =
CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
if (Return.isInvalid())
Invalid = true;
else
Statements.push_back(Return.getAs<Stmt>());
}
if (Invalid) {
MoveAssignOperator->setInvalidDecl();
return;
}
StmtResult Body;
{
CompoundScopeRAII CompoundScope(*this);
Body = ActOnCompoundStmt(Loc, Loc, Statements,
false);
assert(!Body.isInvalid() && "Compound statement creation cannot fail");
}
MoveAssignOperator->setBody(Body.getAs<Stmt>());
MoveAssignOperator->markUsed(Context);
if (ASTMutationListener *L = getASTMutationListener()) {
L->CompletedImplicitDefinition(MoveAssignOperator);
}
}
CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
CXXRecordDecl *ClassDecl) {
assert(ClassDecl->needsImplicitCopyConstructor());
DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
if (DSM.isAlreadyBeingDeclared())
return nullptr;
QualType ClassType = Context.getTypeDeclType(ClassDecl);
QualType ArgType = ClassType;
bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
if (Const)
ArgType = ArgType.withConst();
LangAS AS = getDefaultCXXMethodAddrSpace();
if (AS != LangAS::Default)
ArgType = Context.getAddrSpaceQualType(ArgType, AS);
ArgType = Context.getLValueReferenceType(ArgType);
bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
CXXCopyConstructor,
Const);
DeclarationName Name
= Context.DeclarationNames.getCXXConstructorName(
Context.getCanonicalType(ClassType));
SourceLocation ClassLoc = ClassDecl->getLocation();
DeclarationNameInfo NameInfo(Name, ClassLoc);
CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
true,
true,
Constexpr ? ConstexprSpecKind::Constexpr
: ConstexprSpecKind::Unspecified);
CopyConstructor->setAccess(AS_public);
CopyConstructor->setDefaulted();
setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
if (getLangOpts().CUDA)
inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
CopyConstructor,
Const,
false);
TypeSourceInfo *TSI = nullptr;
if (inTemplateInstantiation() && ClassDecl->isLambda())
TSI = Context.getTrivialTypeSourceInfo(ArgType);
ParmVarDecl *FromParam =
ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
nullptr, ArgType,
TSI, SC_None, nullptr);
CopyConstructor->setParams(FromParam);
CopyConstructor->setTrivial(
ClassDecl->needsOverloadResolutionForCopyConstructor()
? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
: ClassDecl->hasTrivialCopyConstructor());
CopyConstructor->setTrivialForCall(
ClassDecl->hasAttr<TrivialABIAttr>() ||
(ClassDecl->needsOverloadResolutionForCopyConstructor()
? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
TAH_ConsiderTrivialABI)
: ClassDecl->hasTrivialCopyConstructorForCall()));
++getASTContext().NumImplicitCopyConstructorsDeclared;
Scope *S = getScopeForContext(ClassDecl);
CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
ClassDecl->setImplicitCopyConstructorIsDeleted();
SetDeclDeleted(CopyConstructor, ClassLoc);
}
if (S)
PushOnScopeChains(CopyConstructor, S, false);
ClassDecl->addDecl(CopyConstructor);
return CopyConstructor;
}
void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *CopyConstructor) {
assert((CopyConstructor->isDefaulted() &&
CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) &&
"DefineImplicitCopyConstructor - call it for implicit copy ctor");
if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
return;
CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
SynthesizedFunctionScope Scope(*this, CopyConstructor);
ResolveExceptionSpec(CurrentLocation,
CopyConstructor->getType()->castAs<FunctionProtoType>());
MarkVTableUsed(CurrentLocation, ClassDecl);
Scope.addContextNote(CurrentLocation);
if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
if (SetCtorInitializers(CopyConstructor, false)) {
CopyConstructor->setInvalidDecl();
} else {
SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
? CopyConstructor->getEndLoc()
: CopyConstructor->getLocation();
Sema::CompoundScopeRAII CompoundScope(*this);
CopyConstructor->setBody(
ActOnCompoundStmt(Loc, Loc, None, false).getAs<Stmt>());
CopyConstructor->markUsed(Context);
}
if (ASTMutationListener *L = getASTMutationListener()) {
L->CompletedImplicitDefinition(CopyConstructor);
}
}
CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
CXXRecordDecl *ClassDecl) {
assert(ClassDecl->needsImplicitMoveConstructor());
DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
if (DSM.isAlreadyBeingDeclared())
return nullptr;
QualType ClassType = Context.getTypeDeclType(ClassDecl);
QualType ArgType = ClassType;
LangAS AS = getDefaultCXXMethodAddrSpace();
if (AS != LangAS::Default)
ArgType = Context.getAddrSpaceQualType(ClassType, AS);
ArgType = Context.getRValueReferenceType(ArgType);
bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
CXXMoveConstructor,
false);
DeclarationName Name
= Context.DeclarationNames.getCXXConstructorName(
Context.getCanonicalType(ClassType));
SourceLocation ClassLoc = ClassDecl->getLocation();
DeclarationNameInfo NameInfo(Name, ClassLoc);
CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
true,
true,
Constexpr ? ConstexprSpecKind::Constexpr
: ConstexprSpecKind::Unspecified);
MoveConstructor->setAccess(AS_public);
MoveConstructor->setDefaulted();
setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
if (getLangOpts().CUDA)
inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
MoveConstructor,
false,
false);
ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
ClassLoc, ClassLoc,
nullptr,
ArgType, nullptr,
SC_None, nullptr);
MoveConstructor->setParams(FromParam);
MoveConstructor->setTrivial(
ClassDecl->needsOverloadResolutionForMoveConstructor()
? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
: ClassDecl->hasTrivialMoveConstructor());
MoveConstructor->setTrivialForCall(
ClassDecl->hasAttr<TrivialABIAttr>() ||
(ClassDecl->needsOverloadResolutionForMoveConstructor()
? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
TAH_ConsiderTrivialABI)
: ClassDecl->hasTrivialMoveConstructorForCall()));
++getASTContext().NumImplicitMoveConstructorsDeclared;
Scope *S = getScopeForContext(ClassDecl);
CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
ClassDecl->setImplicitMoveConstructorIsDeleted();
SetDeclDeleted(MoveConstructor, ClassLoc);
}
if (S)
PushOnScopeChains(MoveConstructor, S, false);
ClassDecl->addDecl(MoveConstructor);
return MoveConstructor;
}
void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *MoveConstructor) {
assert((MoveConstructor->isDefaulted() &&
MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) &&
"DefineImplicitMoveConstructor - call it for implicit move ctor");
if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
return;
CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
SynthesizedFunctionScope Scope(*this, MoveConstructor);
ResolveExceptionSpec(CurrentLocation,
MoveConstructor->getType()->castAs<FunctionProtoType>());
MarkVTableUsed(CurrentLocation, ClassDecl);
Scope.addContextNote(CurrentLocation);
if (SetCtorInitializers(MoveConstructor, false)) {
MoveConstructor->setInvalidDecl();
} else {
SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
? MoveConstructor->getEndLoc()
: MoveConstructor->getLocation();
Sema::CompoundScopeRAII CompoundScope(*this);
MoveConstructor->setBody(ActOnCompoundStmt(
Loc, Loc, None, false).getAs<Stmt>());
MoveConstructor->markUsed(Context);
}
if (ASTMutationListener *L = getASTMutationListener()) {
L->CompletedImplicitDefinition(MoveConstructor);
}
}
bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
}
void Sema::DefineImplicitLambdaToFunctionPointerConversion(
SourceLocation CurrentLocation,
CXXConversionDecl *Conv) {
SynthesizedFunctionScope Scope(*this, Conv);
assert(!Conv->getReturnType()->isUndeducedType());
QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
CallingConv CC =
ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
CXXRecordDecl *Lambda = Conv->getParent();
FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
CallOp = InstantiateFunctionDeclaration(
CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
if (!CallOp)
return;
Invoker = InstantiateFunctionDeclaration(
Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
if (!Invoker)
return;
}
if (CallOp->isInvalidDecl())
return;
MarkFunctionReferenced(CurrentLocation, CallOp);
Invoker->markUsed(Context);
Invoker->setReferenced();
Invoker->setType(Conv->getReturnType()->getPointeeType());
Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
VK_LValue, Conv->getLocation());
assert(FunctionRef && "Can't refer to __invoke function?");
Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Conv->setBody(CompoundStmt::Create(Context, Return, FPOptionsOverride(),
Conv->getLocation(), Conv->getLocation()));
Conv->markUsed(Context);
Conv->setReferenced();
if (ASTMutationListener *L = getASTMutationListener()) {
L->CompletedImplicitDefinition(Conv);
L->CompletedImplicitDefinition(Invoker);
}
}
void Sema::DefineImplicitLambdaToBlockPointerConversion(
SourceLocation CurrentLocation,
CXXConversionDecl *Conv)
{
assert(!Conv->getParent()->isGenericLambda());
SynthesizedFunctionScope Scope(*this, Conv);
Expr *This = ActOnCXXThis(CurrentLocation).get();
Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
Conv->getLocation(),
Conv, DerefThis);
if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
BuildBlock = ImplicitCastExpr::Create(
Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
if (BuildBlock.isInvalid()) {
Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Conv->setInvalidDecl();
return;
}
StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
if (Return.isInvalid()) {
Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Conv->setInvalidDecl();
return;
}
Stmt *ReturnS = Return.get();
Conv->setBody(CompoundStmt::Create(Context, ReturnS, FPOptionsOverride(),
Conv->getLocation(), Conv->getLocation()));
Conv->markUsed(Context);
if (ASTMutationListener *L = getASTMutationListener()) {
L->CompletedImplicitDefinition(Conv);
}
}
static bool hasOneRealArgument(MultiExprArg Args) {
switch (Args.size()) {
case 0:
return false;
default:
if (!Args[1]->isDefaultArgument())
return false;
LLVM_FALLTHROUGH;
case 1:
return !Args[0]->isDefaultArgument();
}
return false;
}
ExprResult
Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
NamedDecl *FoundDecl,
CXXConstructorDecl *Constructor,
MultiExprArg ExprArgs,
bool HadMultipleCandidates,
bool IsListInitialization,
bool IsStdInitListInitialization,
bool RequiresZeroInit,
unsigned ConstructKind,
SourceRange ParenRange) {
bool Elidable = false;
if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Expr *SubExpr = ExprArgs[0];
Elidable = SubExpr->isTemporaryObject(
Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
}
return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
FoundDecl, Constructor,
Elidable, ExprArgs, HadMultipleCandidates,
IsListInitialization,
IsStdInitListInitialization, RequiresZeroInit,
ConstructKind, ParenRange);
}
ExprResult
Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
NamedDecl *FoundDecl,
CXXConstructorDecl *Constructor,
bool Elidable,
MultiExprArg ExprArgs,
bool HadMultipleCandidates,
bool IsListInitialization,
bool IsStdInitListInitialization,
bool RequiresZeroInit,
unsigned ConstructKind,
SourceRange ParenRange) {
if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
return ExprError();
}
return BuildCXXConstructExpr(
ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
RequiresZeroInit, ConstructKind, ParenRange);
}
ExprResult
Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
CXXConstructorDecl *Constructor,
bool Elidable,
MultiExprArg ExprArgs,
bool HadMultipleCandidates,
bool IsListInitialization,
bool IsStdInitListInitialization,
bool RequiresZeroInit,
unsigned ConstructKind,
SourceRange ParenRange) {
assert(declaresSameEntity(
Constructor->getParent(),
DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
"given constructor for wrong type");
MarkFunctionReferenced(ConstructLoc, Constructor);
if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
return ExprError();
if (getLangOpts().SYCLIsDevice &&
!checkSYCLDeviceFunction(ConstructLoc, Constructor))
return ExprError();
return CheckForImmediateInvocation(
CXXConstructExpr::Create(
Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
HadMultipleCandidates, IsListInitialization,
IsStdInitListInitialization, RequiresZeroInit,
static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
ParenRange),
Constructor);
}
ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
assert(Field->hasInClassInitializer());
if (Field->getInClassInitializer())
return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
if (Field->isInvalidDecl())
return ExprError();
CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
DeclContext::lookup_result Lookup =
ClassPattern->lookup(Field->getDeclName());
FieldDecl *Pattern = nullptr;
for (auto L : Lookup) {
if (isa<FieldDecl>(L)) {
Pattern = cast<FieldDecl>(L);
break;
}
}
assert(Pattern && "We must have set the Pattern!");
if (!Pattern->hasInClassInitializer() ||
InstantiateInClassInitializer(Loc, Field, Pattern,
getTemplateInstantiationArgs(Field))) {
Field->setInvalidDecl();
return ExprError();
}
return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
}
RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
<< OutermostClass << Field;
Diag(Field->getEndLoc(),
diag::note_default_member_initializer_not_yet_parsed);
if (!isSFINAEContext())
Field->setInvalidDecl();
return ExprError();
}
void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
if (VD->isInvalidDecl()) return;
if (VD->getInit() && VD->getInit()->containsErrors())
return;
CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
if (ClassDecl->isInvalidDecl()) return;
if (ClassDecl->hasIrrelevantDestructor()) return;
if (ClassDecl->isDependentContext()) return;
if (VD->isNoDestroy(getASTContext()))
return;
CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
if (!VD->getType()->isArrayType()) {
MarkFunctionReferenced(VD->getLocation(), Destructor);
CheckDestructorAccess(VD->getLocation(), Destructor,
PDiag(diag::err_access_dtor_var)
<< VD->getDeclName() << VD->getType());
DiagnoseUseOfDecl(Destructor, VD->getLocation());
}
if (Destructor->isTrivial()) return;
if (Destructor->isConstexpr()) {
bool HasConstantInit = false;
if (VD->getInit() && !VD->getInit()->isValueDependent())
HasConstantInit = VD->evaluateValue();
SmallVector<PartialDiagnosticAt, 8> Notes;
if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
HasConstantInit) {
Diag(VD->getLocation(),
diag::err_constexpr_var_requires_const_destruction) << VD;
for (unsigned I = 0, N = Notes.size(); I != N; ++I)
Diag(Notes[I].first, Notes[I].second);
}
}
if (!VD->hasGlobalStorage()) return;
Diag(VD->getLocation(), diag::warn_exit_time_destructor);
if (!VD->isStaticLocal())
Diag(VD->getLocation(), diag::warn_global_destructor);
}
bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
QualType DeclInitType, MultiExprArg ArgsPtr,
SourceLocation Loc,
SmallVectorImpl<Expr *> &ConvertedArgs,
bool AllowExplicit,
bool IsListInitialization) {
unsigned NumArgs = ArgsPtr.size();
Expr **Args = ArgsPtr.data();
const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
unsigned NumParams = Proto->getNumParams();
if (NumArgs < NumParams)
ConvertedArgs.reserve(NumParams);
else
ConvertedArgs.reserve(NumArgs);
VariadicCallType CallType =
Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
SmallVector<Expr *, 8> AllArgs;
bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Proto, 0,
llvm::makeArrayRef(Args, NumArgs),
AllArgs,
CallType, AllowExplicit,
IsListInitialization);
ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
CheckConstructorCall(Constructor, DeclInitType,
llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Proto, Loc);
return Invalid;
}
static inline bool
CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
const FunctionDecl *FnDecl) {
const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
if (isa<NamespaceDecl>(DC)) {
return SemaRef.Diag(FnDecl->getLocation(),
diag::err_operator_new_delete_declared_in_namespace)
<< FnDecl->getDeclName();
}
if (isa<TranslationUnitDecl>(DC) &&
FnDecl->getStorageClass() == SC_Static) {
return SemaRef.Diag(FnDecl->getLocation(),
diag::err_operator_new_delete_declared_static)
<< FnDecl->getDeclName();
}
return false;
}
static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
const PointerType *PtrTy) {
auto &Ctx = SemaRef.Context;
Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
PtrQuals.removeAddressSpace();
return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
}
static inline bool
CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
CanQualType ExpectedResultType,
CanQualType ExpectedFirstParamType,
unsigned DependentParamTypeDiag,
unsigned InvalidParamTypeDiag) {
QualType ResultType =
FnDecl->getType()->castAs<FunctionType>()->getReturnType();
if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
if (const auto *PtrTy = ResultType->getAs<PointerType>())
ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
}
if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
return SemaRef.Diag(
FnDecl->getLocation(),
ResultType->isDependentType()
? diag::err_operator_new_delete_dependent_result_type
: diag::err_operator_new_delete_invalid_result_type)
<< FnDecl->getDeclName() << ExpectedResultType;
}
if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
return SemaRef.Diag(FnDecl->getLocation(),
diag::err_operator_new_delete_template_too_few_parameters)
<< FnDecl->getDeclName();
if (FnDecl->getNumParams() == 0)
return SemaRef.Diag(FnDecl->getLocation(),
diag::err_operator_new_delete_too_few_parameters)
<< FnDecl->getDeclName();
QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
if (const auto *PtrTy =
FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
ExpectedFirstParamType =
RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
}
if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
ExpectedFirstParamType) {
return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
? DependentParamTypeDiag
: InvalidParamTypeDiag)
<< FnDecl->getDeclName() << ExpectedFirstParamType;
}
return false;
}
static bool
CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
return true;
CanQualType SizeTy =
SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
SizeTy,
diag::err_operator_new_dependent_param_type,
diag::err_operator_new_param_type))
return true;
if (FnDecl->getParamDecl(0)->hasDefaultArg())
return SemaRef.Diag(FnDecl->getLocation(),
diag::err_operator_new_default_arg)
<< FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
return false;
}
static bool
CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
return true;
auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
CanQualType ExpectedFirstParamType =
MD && MD->isDestroyingOperatorDelete()
? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
SemaRef.Context.getRecordType(MD->getParent())))
: SemaRef.Context.VoidPtrTy;
if (CheckOperatorNewDeleteTypes(
SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
diag::err_operator_delete_dependent_param_type,
diag::err_operator_delete_param_type))
return true;
if (MD && !MD->getParent()->isDependentContext() &&
MD->isDestroyingOperatorDelete() &&
!SemaRef.isUsualDeallocationFunction(MD)) {
SemaRef.Diag(MD->getLocation(),
diag::err_destroying_operator_delete_not_usual);
return true;
}
return false;
}
bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
assert(FnDecl && FnDecl->isOverloadedOperator() &&
"Expected an overloaded operator declaration");
OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
if (Op == OO_Delete || Op == OO_Array_Delete)
return CheckOperatorDeleteDeclaration(*this, FnDecl);
if (Op == OO_New || Op == OO_Array_New)
return CheckOperatorNewDeclaration(*this, FnDecl);
if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
if (MethodDecl->isStatic())
return Diag(FnDecl->getLocation(),
diag::err_operator_overload_static) << FnDecl->getDeclName();
} else {
bool ClassOrEnumParam = false;
for (auto Param : FnDecl->parameters()) {
QualType ParamType = Param->getType().getNonReferenceType();
if (ParamType->isDependentType() || ParamType->isRecordType() ||
ParamType->isEnumeralType()) {
ClassOrEnumParam = true;
break;
}
}
if (!ClassOrEnumParam)
return Diag(FnDecl->getLocation(),
diag::err_operator_overload_needs_class_or_enum)
<< FnDecl->getDeclName();
}
if (Op != OO_Call) {
ParmVarDecl *FirstDefaultedParam = nullptr;
for (auto Param : FnDecl->parameters()) {
if (Param->hasDefaultArg()) {
FirstDefaultedParam = Param;
break;
}
}
if (FirstDefaultedParam) {
if (Op == OO_Subscript) {
Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
? diag::ext_subscript_overload
: diag::error_subscript_overload)
<< FnDecl->getDeclName() << 1
<< FirstDefaultedParam->getDefaultArgRange();
} else {
return Diag(FirstDefaultedParam->getLocation(),
diag::err_operator_overload_default_arg)
<< FnDecl->getDeclName()
<< FirstDefaultedParam->getDefaultArgRange();
}
}
}
static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
{ false, false, false }
#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
, { Unary, Binary, MemberOnly }
#include "clang/Basic/OperatorKinds.def"
};
bool CanBeUnaryOperator = OperatorUses[Op][0];
bool CanBeBinaryOperator = OperatorUses[Op][1];
bool MustBeMemberOperator = OperatorUses[Op][2];
unsigned NumParams = FnDecl->getNumParams()
+ (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
if (Op != OO_Call && Op != OO_Subscript &&
((NumParams == 1 && !CanBeUnaryOperator) ||
(NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
(NumParams > 2))) {
unsigned ErrorKind;
if (CanBeUnaryOperator && CanBeBinaryOperator) {
ErrorKind = 2; } else if (CanBeUnaryOperator) {
ErrorKind = 0; } else {
assert(CanBeBinaryOperator &&
"All non-call overloaded operators are unary or binary!");
ErrorKind = 1; }
return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
<< FnDecl->getDeclName() << NumParams << ErrorKind;
}
if (Op == OO_Subscript && NumParams != 2) {
Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
? diag::ext_subscript_overload
: diag::error_subscript_overload)
<< FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
}
if (Op != OO_Call &&
FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
<< FnDecl->getDeclName();
}
if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
return Diag(FnDecl->getLocation(),
diag::err_operator_overload_must_be_member)
<< FnDecl->getDeclName();
}
if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
QualType ParamType = LastParam->getType();
if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
!ParamType->isDependentType())
return Diag(LastParam->getLocation(),
diag::err_operator_overload_post_incdec_must_be_int)
<< LastParam->getType() << (Op == OO_MinusMinus);
}
return false;
}
static bool
checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
FunctionTemplateDecl *TpDecl) {
TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
if (TemplateParams->size() == 1) {
NonTypeTemplateParmDecl *PmDecl =
dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
if (PmDecl && PmDecl->isTemplateParameterPack() &&
SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
return false;
if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
!PmDecl->isTemplateParameterPack() &&
(PmDecl->getType()->isRecordType() ||
PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
return false;
} else if (TemplateParams->size() == 2) {
TemplateTypeParmDecl *PmType =
dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
NonTypeTemplateParmDecl *PmArgs =
dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
PmArgs->isTemplateParameterPack()) {
const TemplateTypeParmType *TArgs =
PmArgs->getType()->getAs<TemplateTypeParmType>();
if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
TArgs->getIndex() == PmType->getIndex()) {
if (!SemaRef.inTemplateInstantiation())
SemaRef.Diag(TpDecl->getLocation(),
diag::ext_string_literal_operator_template);
return false;
}
}
}
SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
diag::err_literal_operator_template)
<< TpDecl->getTemplateParameters()->getSourceRange();
return true;
}
bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
if (isa<CXXMethodDecl>(FnDecl)) {
Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
<< FnDecl->getDeclName();
return true;
}
if (FnDecl->isExternC()) {
Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
if (const LinkageSpecDecl *LSD =
FnDecl->getDeclContext()->getExternCContext())
Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
return true;
}
FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
if (!TpDecl)
TpDecl = FnDecl->getPrimaryTemplate();
if (TpDecl) {
if (FnDecl->param_size() != 0) {
Diag(FnDecl->getLocation(),
diag::err_literal_operator_template_with_params);
return true;
}
if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
return true;
} else if (FnDecl->param_size() == 1) {
const ParmVarDecl *Param = FnDecl->getParamDecl(0);
QualType ParamType = Param->getType().getUnqualifiedType();
if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
Context.hasSameType(ParamType, Context.CharTy) ||
Context.hasSameType(ParamType, Context.WideCharTy) ||
Context.hasSameType(ParamType, Context.Char8Ty) ||
Context.hasSameType(ParamType, Context.Char16Ty) ||
Context.hasSameType(ParamType, Context.Char32Ty)) {
} else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
QualType InnerType = Ptr->getPointeeType();
if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
Context.CharTy) &&
InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
Diag(Param->getSourceRange().getBegin(),
diag::err_literal_operator_param)
<< ParamType << "'const char *'" << Param->getSourceRange();
return true;
}
} else if (ParamType->isRealFloatingType()) {
Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
<< ParamType << Context.LongDoubleTy << Param->getSourceRange();
return true;
} else if (ParamType->isIntegerType()) {
Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
<< ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
return true;
} else {
Diag(Param->getSourceRange().getBegin(),
diag::err_literal_operator_invalid_param)
<< ParamType << Param->getSourceRange();
return true;
}
} else if (FnDecl->param_size() == 2) {
FunctionDecl::param_iterator Param = FnDecl->param_begin();
QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
const PointerType *PT = FirstParamType->getAs<PointerType>();
if (!PT) {
Diag((*Param)->getSourceRange().getBegin(),
diag::err_literal_operator_param)
<< FirstParamType << "'const char *'" << (*Param)->getSourceRange();
return true;
}
QualType PointeeType = PT->getPointeeType();
if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
Diag((*Param)->getSourceRange().getBegin(),
diag::err_literal_operator_param)
<< FirstParamType << "'const char *'" << (*Param)->getSourceRange();
return true;
}
QualType InnerType = PointeeType.getUnqualifiedType();
if (!(Context.hasSameType(InnerType, Context.CharTy) ||
Context.hasSameType(InnerType, Context.WideCharTy) ||
Context.hasSameType(InnerType, Context.Char8Ty) ||
Context.hasSameType(InnerType, Context.Char16Ty) ||
Context.hasSameType(InnerType, Context.Char32Ty))) {
Diag((*Param)->getSourceRange().getBegin(),
diag::err_literal_operator_param)
<< FirstParamType << "'const char *'" << (*Param)->getSourceRange();
return true;
}
++Param;
QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
Diag((*Param)->getSourceRange().getBegin(),
diag::err_literal_operator_param)
<< SecondParamType << Context.getSizeType()
<< (*Param)->getSourceRange();
return true;
}
} else {
Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
return true;
}
for (auto Param : FnDecl->parameters()) {
if (Param->hasDefaultArg()) {
Diag(Param->getDefaultArgRange().getBegin(),
diag::err_literal_operator_default_argument)
<< Param->getDefaultArgRange();
break;
}
}
StringRef LiteralName
= FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
if (LiteralName[0] != '_' &&
!getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
<< StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
}
return false;
}
Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Expr *LangStr,
SourceLocation LBraceLoc) {
StringLiteral *Lit = cast<StringLiteral>(LangStr);
if (!Lit->isOrdinary()) {
Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
<< LangStr->getSourceRange();
return nullptr;
}
StringRef Lang = Lit->getString();
LinkageSpecDecl::LanguageIDs Language;
if (Lang == "C")
Language = LinkageSpecDecl::lang_c;
else if (Lang == "C++")
Language = LinkageSpecDecl::lang_cxx;
else {
Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
<< LangStr->getSourceRange();
return nullptr;
}
LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
LangStr->getExprLoc(), Language,
LBraceLoc.isValid());
if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
Module *GlobalModule =
PushGlobalModuleFragment(ExternLoc, true);
D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
D->setLocalOwningModule(GlobalModule);
}
CurContext->addDecl(D);
PushDeclContext(S, D);
return D;
}
Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Decl *LinkageSpec,
SourceLocation RBraceLoc) {
if (RBraceLoc.isValid()) {
LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
LSDecl->setRBraceLoc(RBraceLoc);
}
if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent)
PopGlobalModuleFragment();
PopDeclContext();
return LinkageSpec;
}
Decl *Sema::ActOnEmptyDeclaration(Scope *S,
const ParsedAttributesView &AttrList,
SourceLocation SemiLoc) {
Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
ProcessDeclAttributeList(S, ED, AttrList);
CurContext->addDecl(ED);
return ED;
}
VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
TypeSourceInfo *TInfo,
SourceLocation StartLoc,
SourceLocation Loc,
IdentifierInfo *Name) {
bool Invalid = false;
QualType ExDeclType = TInfo->getType();
if (ExDeclType->isArrayType())
ExDeclType = Context.getArrayDecayedType(ExDeclType);
else if (ExDeclType->isFunctionType())
ExDeclType = Context.getPointerType(ExDeclType);
if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Diag(Loc, diag::err_catch_rvalue_ref);
Invalid = true;
}
if (ExDeclType->isVariablyModifiedType()) {
Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
Invalid = true;
}
QualType BaseType = ExDeclType;
int Mode = 0; unsigned DK = diag::err_catch_incomplete;
if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
BaseType = Ptr->getPointeeType();
Mode = 1;
DK = diag::err_catch_incomplete_ptr;
} else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
BaseType = Ref->getPointeeType();
Mode = 2;
DK = diag::err_catch_incomplete_ref;
}
if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
!BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Invalid = true;
if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
Invalid = true;
}
if (!Invalid && !ExDeclType->isDependentType() &&
RequireNonAbstractType(Loc, ExDeclType,
diag::err_abstract_type_in_decl,
AbstractVariableType))
Invalid = true;
if (!Invalid && getLangOpts().ObjC) {
QualType T = ExDeclType;
if (const ReferenceType *RT = T->getAs<ReferenceType>())
T = RT->getPointeeType();
if (T->isObjCObjectType()) {
Diag(Loc, diag::err_objc_object_catch);
Invalid = true;
} else if (T->isObjCObjectPointerType()) {
if (getLangOpts().ObjCRuntime.isFragile())
Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
}
}
VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
ExDeclType, TInfo, SC_None);
ExDecl->setExceptionVariable(true);
if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Invalid = true;
if (!Invalid && !ExDeclType->isDependentType()) {
if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
EnterExpressionEvaluationContext scope(
*this, ExpressionEvaluationContext::PotentiallyEvaluated);
QualType initType = Context.getExceptionObjectType(ExDeclType);
InitializedEntity entity =
InitializedEntity::InitializeVariable(ExDecl);
InitializationKind initKind =
InitializationKind::CreateCopy(Loc, SourceLocation());
Expr *opaqueValue =
new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
InitializationSequence sequence(*this, entity, initKind, opaqueValue);
ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
if (result.isInvalid())
Invalid = true;
else {
CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
if (!construct->getConstructor()->isTrivial()) {
Expr *init = MaybeCreateExprWithCleanups(construct);
ExDecl->setInit(init);
}
FinalizeVarWithDestructor(ExDecl, recordType);
}
}
}
if (Invalid)
ExDecl->setInvalidDecl();
return ExDecl;
}
Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
bool Invalid = D.isInvalidType();
if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
UPPC_ExceptionType)) {
TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
D.getIdentifierLoc());
Invalid = true;
}
IdentifierInfo *II = D.getIdentifier();
if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
LookupOrdinaryName,
ForVisibleRedeclaration)) {
assert(!S->isDeclScope(PrevDecl));
if (isDeclInScope(PrevDecl, CurContext, S)) {
Diag(D.getIdentifierLoc(), diag::err_redefinition)
<< D.getIdentifier();
Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Invalid = true;
} else if (PrevDecl->isTemplateParameter())
DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
}
if (D.getCXXScopeSpec().isSet() && !Invalid) {
Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
<< D.getCXXScopeSpec().getRange();
Invalid = true;
}
VarDecl *ExDecl = BuildExceptionDeclaration(
S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
if (Invalid)
ExDecl->setInvalidDecl();
if (II)
PushOnScopeChains(ExDecl, S);
else
CurContext->addDecl(ExDecl);
ProcessDeclAttributes(S, ExDecl, D);
return ExDecl;
}
Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
Expr *AssertExpr,
Expr *AssertMessageExpr,
SourceLocation RParenLoc) {
StringLiteral *AssertMessage =
AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
return nullptr;
return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
AssertMessage, RParenLoc, false);
}
Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
Expr *AssertExpr,
StringLiteral *AssertMessage,
SourceLocation RParenLoc,
bool Failed) {
assert(AssertExpr != nullptr && "Expected non-null condition");
if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
!Failed) {
ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
if (Converted.isInvalid())
Failed = true;
ExprResult FullAssertExpr =
ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
false,
true);
if (FullAssertExpr.isInvalid())
Failed = true;
else
AssertExpr = FullAssertExpr.get();
llvm::APSInt Cond;
if (!Failed && VerifyIntegerConstantExpression(
AssertExpr, &Cond,
diag::err_static_assert_expression_is_not_constant)
.isInvalid())
Failed = true;
if (!Failed && !Cond) {
SmallString<256> MsgBuffer;
llvm::raw_svector_ostream Msg(MsgBuffer);
if (AssertMessage) {
const auto *MsgStr = cast<StringLiteral>(AssertMessage);
if (MsgStr->isOrdinary())
Msg << MsgStr->getString();
else
MsgStr->printPretty(Msg, nullptr, getPrintingPolicy());
}
Expr *InnerCond = nullptr;
std::string InnerCondDescription;
std::tie(InnerCond, InnerCondDescription) =
findFailedBooleanCondition(Converted.get());
if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
Diag(StaticAssertLoc, diag::err_static_assert_failed)
<< !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
ConstraintSatisfaction Satisfaction;
if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
DiagnoseUnsatisfiedConstraint(Satisfaction);
} else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
&& !isa<IntegerLiteral>(InnerCond)) {
Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
<< InnerCondDescription << !AssertMessage
<< Msg.str() << InnerCond->getSourceRange();
} else {
Diag(StaticAssertLoc, diag::err_static_assert_failed)
<< !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
}
Failed = true;
}
} else {
ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
false,
true);
if (FullAssertExpr.isInvalid())
Failed = true;
else
AssertExpr = FullAssertExpr.get();
}
Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
AssertExpr, AssertMessage, RParenLoc,
Failed);
CurContext->addDecl(Decl);
return Decl;
}
FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
SourceLocation FriendLoc,
TypeSourceInfo *TSInfo) {
assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
QualType T = TSInfo->getType();
SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
if (!CodeSynthesisContexts.empty()) {
} else {
if (!T->isElaboratedTypeSpecifier()) {
if (const RecordType *RT = T->getAs<RecordType>()) {
RecordDecl *RD = RT->getDecl();
SmallString<16> InsertionText(" ");
InsertionText += RD->getKindName();
Diag(TypeRange.getBegin(),
getLangOpts().CPlusPlus11 ?
diag::warn_cxx98_compat_unelaborated_friend_type :
diag::ext_unelaborated_friend_type)
<< (unsigned) RD->getTagKind()
<< T
<< FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
InsertionText);
} else {
Diag(FriendLoc,
getLangOpts().CPlusPlus11 ?
diag::warn_cxx98_compat_nonclass_type_friend :
diag::ext_nonclass_type_friend)
<< T
<< TypeRange;
}
} else if (T->getAs<EnumType>()) {
Diag(FriendLoc,
getLangOpts().CPlusPlus11 ?
diag::warn_cxx98_compat_enum_friend :
diag::ext_enum_friend)
<< T
<< TypeRange;
}
if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
}
return FriendDecl::Create(Context, CurContext,
TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
FriendLoc);
}
Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
unsigned TagSpec, SourceLocation TagLoc,
CXXScopeSpec &SS, IdentifierInfo *Name,
SourceLocation NameLoc,
const ParsedAttributesView &Attr,
MultiTemplateParamsArg TempParamLists) {
TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
bool IsMemberSpecialization = false;
bool Invalid = false;
if (TemplateParameterList *TemplateParams =
MatchTemplateParametersToScopeSpecifier(
TagLoc, NameLoc, SS, nullptr, TempParamLists, true,
IsMemberSpecialization, Invalid)) {
if (TemplateParams->size() > 0) {
if (Invalid)
return nullptr;
return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
NameLoc, Attr, TemplateParams, AS_public,
SourceLocation(),
FriendLoc, TempParamLists.size() - 1,
TempParamLists.data()).get();
} else {
Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
<< TypeWithKeyword::getTagTypeKindName(Kind) << Name;
IsMemberSpecialization = true;
}
}
if (Invalid) return nullptr;
bool isAllExplicitSpecializations = true;
for (unsigned I = TempParamLists.size(); I-- > 0; ) {
if (TempParamLists[I]->size()) {
isAllExplicitSpecializations = false;
break;
}
}
if (isAllExplicitSpecializations) {
if (SS.isEmpty()) {
bool Owned = false;
bool IsDependent = false;
return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Attr, AS_public,
SourceLocation(),
MultiTemplateParamsArg(), Owned, IsDependent,
SourceLocation(),
false,
TypeResult(),
false,
false);
}
NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
ElaboratedTypeKeyword Keyword
= TypeWithKeyword::getKeywordForTagTypeKind(Kind);
QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
*Name, NameLoc);
if (T.isNull())
return nullptr;
TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
if (isa<DependentNameType>(T)) {
DependentNameTypeLoc TL =
TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
TL.setElaboratedKeywordLoc(TagLoc);
TL.setQualifierLoc(QualifierLoc);
TL.setNameLoc(NameLoc);
} else {
ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
TL.setElaboratedKeywordLoc(TagLoc);
TL.setQualifierLoc(QualifierLoc);
TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
}
FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
TSI, FriendLoc, TempParamLists);
Friend->setAccess(AS_public);
CurContext->addDecl(Friend);
return Friend;
}
assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
<< SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
TL.setElaboratedKeywordLoc(TagLoc);
TL.setQualifierLoc(SS.getWithLocInContext(Context));
TL.setNameLoc(NameLoc);
FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
TSI, FriendLoc, TempParamLists);
Friend->setAccess(AS_public);
Friend->setUnsupportedFriend(true);
CurContext->addDecl(Friend);
return Friend;
}
Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
MultiTemplateParamsArg TempParams) {
SourceLocation Loc = DS.getBeginLoc();
assert(DS.isFriendSpecified());
assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
if (DS.getTypeQualifiers()) {
if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
}
Declarator TheDeclarator(DS, ParsedAttributesView::none(),
DeclaratorContext::Member);
TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
QualType T = TSI->getType();
if (TheDeclarator.isInvalidType())
return nullptr;
if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
return nullptr;
if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
Diag(Loc, diag::err_tagless_friend_type_template)
<< DS.getSourceRange();
return nullptr;
}
Decl *D;
if (!TempParams.empty())
D = FriendTemplateDecl::Create(Context, CurContext, Loc,
TempParams,
TSI,
DS.getFriendSpecLoc());
else
D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
if (!D)
return nullptr;
D->setAccess(AS_public);
CurContext->addDecl(D);
return D;
}
NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParams) {
const DeclSpec &DS = D.getDeclSpec();
assert(DS.isFriendSpecified());
assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
SourceLocation Loc = D.getIdentifierLoc();
TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
if (!TInfo->getType()->isFunctionType()) {
Diag(Loc, diag::err_unexpected_friend);
return nullptr;
}
CXXScopeSpec &SS = D.getCXXScopeSpec();
DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
assert(NameInfo.getName());
if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
return nullptr;
DeclContext *DC;
Scope *DCScope = S;
LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
ForExternalRedeclaration);
FunctionDecl *FunctionContainingLocalClass = nullptr;
if ((SS.isInvalid() || !SS.isSet()) &&
(FunctionContainingLocalClass =
cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
DCScope = S->getFnParent();
Previous.clear(LookupLocalFriendName);
LookupName(Previous, S, false);
if (!Previous.empty()) {
DC = Previous.getRepresentativeDecl()->getDeclContext();
} else {
DC = FunctionContainingLocalClass;
}
adjustContextForLocalExternDecl(DC);
if (D.isFunctionDefinition()) {
Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
}
} else if (SS.isInvalid() || !SS.isSet()) {
bool isTemplateId =
D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
DC = CurContext;
while (DC->isRecord())
DC = DC->getParent();
DeclContext *LookupDC = DC->getNonTransparentContext();
while (true) {
LookupQualifiedName(Previous, LookupDC);
if (!Previous.empty()) {
DC = LookupDC;
break;
}
if (isTemplateId) {
if (isa<TranslationUnitDecl>(LookupDC)) break;
} else {
if (LookupDC->isFileContext()) break;
}
LookupDC = LookupDC->getParent();
}
DCScope = getScopeForDeclContext(S, DC);
} else if (!SS.getScopeRep()->isDependent()) {
DC = computeDeclContext(SS);
if (!DC) return nullptr;
if (RequireCompleteDeclContext(SS, DC)) return nullptr;
LookupQualifiedName(Previous, DC);
if (DC->Equals(CurContext))
Diag(DS.getFriendSpecLoc(),
getLangOpts().CPlusPlus11 ?
diag::warn_cxx98_compat_friend_is_member :
diag::err_friend_is_member);
if (D.isFunctionDefinition()) {
SemaDiagnosticBuilder DB
= Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
DB << SS.getScopeRep();
if (DC->isFileContext())
DB << FixItHint::CreateRemoval(SS.getRange());
SS.clear();
}
} else {
if (D.isFunctionDefinition()) {
Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
<< SS.getScopeRep();
}
DC = CurContext;
assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
}
if (!DC->isRecord()) {
int DiagArg = -1;
switch (D.getName().getKind()) {
case UnqualifiedIdKind::IK_ConstructorTemplateId:
case UnqualifiedIdKind::IK_ConstructorName:
DiagArg = 0;
break;
case UnqualifiedIdKind::IK_DestructorName:
DiagArg = 1;
break;
case UnqualifiedIdKind::IK_ConversionFunctionId:
DiagArg = 2;
break;
case UnqualifiedIdKind::IK_DeductionGuideName:
DiagArg = 3;
break;
case UnqualifiedIdKind::IK_Identifier:
case UnqualifiedIdKind::IK_ImplicitSelfParam:
case UnqualifiedIdKind::IK_LiteralOperatorId:
case UnqualifiedIdKind::IK_OperatorFunctionId:
case UnqualifiedIdKind::IK_TemplateId:
break;
}
if (DiagArg >= 0) {
Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
return nullptr;
}
}
Scope FakeDCScope(S, Scope::DeclScope, Diags);
if (!DCScope) {
FakeDCScope.setEntity(DC);
DCScope = &FakeDCScope;
}
bool AddToScope = true;
NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
TemplateParams, AddToScope);
if (!ND) return nullptr;
assert(ND->getLexicalDeclContext() == CurContext);
DC = ND->getDeclContext();
if (!CurContext->isDependentContext()) {
DC = DC->getRedeclContext();
DC->makeDeclVisibleInContext(ND);
if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
PushOnScopeChains(ND, EnclosingScope, false);
}
FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
D.getIdentifierLoc(), ND,
DS.getFriendSpecLoc());
FrD->setAccess(AS_public);
CurContext->addDecl(FrD);
if (ND->isInvalidDecl()) {
FrD->setInvalidDecl();
} else {
if (DC->isRecord()) CheckFriendAccess(ND);
FunctionDecl *FD;
if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
FD = FTD->getTemplatedDecl();
else
FD = cast<FunctionDecl>(ND);
if (functionDeclHasDefaultArgument(FD)) {
if (D.isRedeclaration()) {
Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
Diag(Previous.getRepresentativeDecl()->getLocation(),
diag::note_previous_declaration);
} else if (!D.isFunctionDefinition())
Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
}
if (FD->getNumTemplateParameterLists() && SS.isValid()) {
Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
<< SS.getScopeRep() << SS.getRange()
<< cast<CXXRecordDecl>(CurContext);
FrD->setUnsupportedFriend(true);
}
}
warnOnReservedIdentifier(ND);
return ND;
}
void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
AdjustDeclIfTemplate(Dcl);
FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
if (!Fn) {
Diag(DelLoc, diag::err_deleted_non_function);
return;
}
Fn->setWillHaveBody(false);
if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
Prev->getPreviousDecl()) &&
!Prev->isDefined()) {
Diag(DelLoc, diag::err_deleted_decl_not_first);
Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
Prev->isImplicit() ? diag::note_previous_implicit_declaration
: diag::note_previous_declaration);
Fn->setInvalidDecl();
return;
}
Fn = Fn->getCanonicalDecl();
}
if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
Fn->setInvalidDecl();
}
if (Fn->isMain())
Diag(DelLoc, diag::err_deleted_main);
Fn->setImplicitlyInline();
Fn->setDeletedAsWritten();
}
void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
if (!Dcl || Dcl->isInvalidDecl())
return;
auto *FD = dyn_cast<FunctionDecl>(Dcl);
if (!FD) {
if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
Diag(DefaultLoc, diag::err_defaulted_comparison_template);
return;
}
}
Diag(DefaultLoc, diag::err_default_special_members)
<< getLangOpts().CPlusPlus20;
return;
}
DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
if (!DefKind &&
(!FD->isDependentContext() ||
(!isa<CXXConstructorDecl>(FD) &&
FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
Diag(DefaultLoc, diag::err_default_special_members)
<< getLangOpts().CPlusPlus20;
return;
}
if (DefKind.isComparison() &&
DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
Diag(DefaultLoc, getLangOpts().CPlusPlus20
? diag::warn_cxx17_compat_defaulted_comparison
: diag::ext_defaulted_comparison);
}
FD->setDefaulted();
FD->setExplicitlyDefaulted();
if (FD->isDependentContext())
return;
FD->setWillHaveBody(false);
if (DefKind.isComparison()) {
if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
if (!RD->isCompleteDefinition())
return;
}
if (isa<CXXMethodDecl>(FD)) {
const FunctionDecl *Primary = FD;
if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
Primary = Pattern;
if (Primary->getCanonicalDecl()->isDefaulted())
return;
}
if (DefKind.isComparison()) {
if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
FD->setInvalidDecl();
else
DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
} else {
auto *MD = cast<CXXMethodDecl>(FD);
if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
MD->setInvalidDecl();
else
DefineDefaultedFunction(*this, MD, DefaultLoc);
}
}
static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
for (Stmt *SubStmt : S->children()) {
if (!SubStmt)
continue;
if (isa<ReturnStmt>(SubStmt))
Self.Diag(SubStmt->getBeginLoc(),
diag::err_return_in_constructor_handler);
if (!isa<Expr>(SubStmt))
SearchForReturnInStmt(Self, SubStmt);
}
}
void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
CXXCatchStmt *Handler = TryBlock->getHandler(I);
SearchForReturnInStmt(*this, Handler);
}
}
void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc,
FnBodyKind BodyKind) {
switch (BodyKind) {
case FnBodyKind::Delete:
SetDeclDeleted(D, Loc);
break;
case FnBodyKind::Default:
SetDeclDefaulted(D, Loc);
break;
case FnBodyKind::Other:
llvm_unreachable(
"Parsed function body should be '= delete;' or '= default;'");
}
}
bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
const CXXMethodDecl *Old) {
const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
if (OldFT->hasExtParameterInfos()) {
for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
if (OldFT->getExtParameterInfo(I).isNoEscape() &&
!NewFT->getExtParameterInfo(I).isNoEscape()) {
Diag(New->getParamDecl(I)->getLocation(),
diag::warn_overriding_method_missing_noescape);
Diag(Old->getParamDecl(I)->getLocation(),
diag::note_overridden_marked_noescape);
}
}
const auto *OldCSA = Old->getAttr<CodeSegAttr>();
const auto *NewCSA = New->getAttr<CodeSegAttr>();
if ((NewCSA || OldCSA) &&
(!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
Diag(Old->getLocation(), diag::note_previous_declaration);
return true;
}
CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
if (NewCC == OldCC)
return false;
if (New->getStorageClass() == SC_Static)
return false;
Diag(New->getLocation(),
diag::err_conflicting_overriding_cc_attributes)
<< New->getDeclName() << New->getType() << Old->getType();
Diag(Old->getLocation(), diag::note_overridden_virtual_function);
return true;
}
bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
const CXXMethodDecl *Old) {
QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
if (Context.hasSameType(NewTy, OldTy) ||
NewTy->isDependentType() || OldTy->isDependentType())
return false;
QualType NewClassTy, OldClassTy;
if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
NewClassTy = NewPT->getPointeeType();
OldClassTy = OldPT->getPointeeType();
}
} else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
NewClassTy = NewRT->getPointeeType();
OldClassTy = OldRT->getPointeeType();
}
}
}
if (NewClassTy.isNull()) {
Diag(New->getLocation(),
diag::err_different_return_type_for_overriding_virtual_function)
<< New->getDeclName() << NewTy << OldTy
<< New->getReturnTypeSourceRange();
Diag(Old->getLocation(), diag::note_overridden_virtual_function)
<< Old->getReturnTypeSourceRange();
return true;
}
if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
if (!RT->isBeingDefined() &&
RequireCompleteType(New->getLocation(), NewClassTy,
diag::err_covariant_return_incomplete,
New->getDeclName()))
return true;
}
if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
Diag(New->getLocation(), diag::err_covariant_return_not_derived)
<< New->getDeclName() << NewTy << OldTy
<< New->getReturnTypeSourceRange();
Diag(Old->getLocation(), diag::note_overridden_virtual_function)
<< Old->getReturnTypeSourceRange();
return true;
}
if (CheckDerivedToBaseConversion(
NewClassTy, OldClassTy,
diag::err_covariant_return_inaccessible_base,
diag::err_covariant_return_ambiguous_derived_to_base_conv,
New->getLocation(), New->getReturnTypeSourceRange(),
New->getDeclName(), nullptr)) {
Diag(Old->getLocation(), diag::note_overridden_virtual_function)
<< Old->getReturnTypeSourceRange();
return true;
}
}
if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Diag(New->getLocation(),
diag::err_covariant_return_type_different_qualifications)
<< New->getDeclName() << NewTy << OldTy
<< New->getReturnTypeSourceRange();
Diag(Old->getLocation(), diag::note_overridden_virtual_function)
<< Old->getReturnTypeSourceRange();
return true;
}
if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
Diag(New->getLocation(),
diag::err_covariant_return_type_class_type_more_qualified)
<< New->getDeclName() << NewTy << OldTy
<< New->getReturnTypeSourceRange();
Diag(Old->getLocation(), diag::note_overridden_virtual_function)
<< Old->getReturnTypeSourceRange();
return true;
}
return false;
}
bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
SourceLocation EndLoc = InitRange.getEnd();
if (EndLoc.isValid())
Method->setRangeEnd(EndLoc);
if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
Method->setPure();
return false;
}
if (!Method->isInvalidDecl())
Diag(Method->getLocation(), diag::err_non_virtual_pure)
<< Method->getDeclName() << InitRange;
return true;
}
void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
if (D->getFriendObjectKind())
Diag(D->getLocation(), diag::err_pure_friend);
else if (auto *M = dyn_cast<CXXMethodDecl>(D))
CheckPureMethod(M, ZeroLoc);
else
Diag(D->getLocation(), diag::err_illegal_initializer);
}
static bool isNonlocalVariable(const Decl *D) {
if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
return Var->hasGlobalStorage();
return false;
}
void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
if (!D || D->isInvalidDecl())
return;
if (S && D->isOutOfLine())
EnterDeclaratorContext(S, D->getDeclContext());
if (isNonlocalVariable(D))
PushExpressionEvaluationContext(
ExpressionEvaluationContext::PotentiallyEvaluated, D);
}
void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
if (!D || D->isInvalidDecl())
return;
if (isNonlocalVariable(D))
PopExpressionEvaluationContext();
if (S && D->isOutOfLine())
ExitDeclaratorContext(S);
}
DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
"Parser allowed 'typedef' as storage class of condition decl.");
Decl *Dcl = ActOnDeclarator(S, D);
if (!Dcl)
return true;
if (isa<FunctionDecl>(Dcl)) { Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
<< D.getSourceRange();
return true;
}
return Dcl;
}
void Sema::LoadExternalVTableUses() {
if (!ExternalSource)
return;
SmallVector<ExternalVTableUse, 4> VTables;
ExternalSource->ReadUsedVTables(VTables);
SmallVector<VTableUse, 4> NewUses;
for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
= VTablesUsed.find(VTables[I].Record);
if (Pos != VTablesUsed.end()) {
if (!Pos->second && VTables[I].DefinitionRequired)
Pos->second = true;
continue;
}
VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
}
VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
}
void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
bool DefinitionRequired) {
if (!Class->isDynamicClass() || Class->isDependentContext() ||
CurContext->isDependentContext() || isUnevaluatedContext())
return;
if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
!isInOpenMPDeclareTargetContext() &&
!isInOpenMPTargetExecutionDirective()) {
if (!DefinitionRequired)
MarkVirtualMembersReferenced(Loc, Class);
return;
}
LoadExternalVTableUses();
Class = Class->getCanonicalDecl();
std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
if (!Pos.second) {
if (DefinitionRequired && !Pos.first->second) {
Pos.first->second = true;
} else {
return;
}
} else {
if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
CXXDestructorDecl *DD = Class->getDestructor();
if (DD && DD->isVirtual() && !DD->isDeleted()) {
if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
ContextRAII SavedContext(*this, DD);
CheckDestructor(DD);
} else {
MarkFunctionReferenced(Loc, Class->getDestructor());
}
}
}
}
if (Class->isLocalClass())
MarkVirtualMembersReferenced(Loc, Class);
else
VTableUses.push_back(std::make_pair(Class, Loc));
}
bool Sema::DefineUsedVTables() {
LoadExternalVTableUses();
if (VTableUses.empty())
return false;
bool DefinedAnything = false;
for (unsigned I = 0; I != VTableUses.size(); ++I) {
CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
if (!Class)
continue;
TemplateSpecializationKind ClassTSK =
Class->getTemplateSpecializationKind();
SourceLocation Loc = VTableUses[I].second;
bool DefineVTable = true;
const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
if (KeyFunction && !KeyFunction->hasBody()) {
DefineVTable = false;
TemplateSpecializationKind TSK =
KeyFunction->getTemplateSpecializationKind();
assert(TSK != TSK_ExplicitInstantiationDefinition &&
TSK != TSK_ImplicitInstantiation &&
"Instantiations don't have key functions");
(void)TSK;
} else if (!KeyFunction) {
bool IsExplicitInstantiationDeclaration =
ClassTSK == TSK_ExplicitInstantiationDeclaration;
for (auto R : Class->redecls()) {
TemplateSpecializationKind TSK
= cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
if (TSK == TSK_ExplicitInstantiationDeclaration)
IsExplicitInstantiationDeclaration = true;
else if (TSK == TSK_ExplicitInstantiationDefinition) {
IsExplicitInstantiationDeclaration = false;
break;
}
}
if (IsExplicitInstantiationDeclaration)
DefineVTable = false;
}
if (!DefineVTable) {
MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
continue;
}
DefinedAnything = true;
MarkVirtualMembersReferenced(Loc, Class);
CXXRecordDecl *Canonical = Class->getCanonicalDecl();
if (VTablesUsed[Canonical])
Consumer.HandleVTable(Class);
if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
ClassTSK != TSK_ExplicitInstantiationDefinition) {
const FunctionDecl *KeyFunctionDef = nullptr;
if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
KeyFunctionDef->isInlined()))
Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
}
}
VTableUses.clear();
return DefinedAnything;
}
void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
const CXXRecordDecl *RD) {
for (const auto *I : RD->methods())
if (I->isVirtual() && !I->isPure())
ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
}
void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
const CXXRecordDecl *RD,
bool ConstexprOnly) {
CXXFinalOverriderMap FinalOverriders;
RD->getFinalOverriders(FinalOverriders);
for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
E = FinalOverriders.end();
I != E; ++I) {
for (OverridingMethods::const_iterator OI = I->second.begin(),
OE = I->second.end();
OI != OE; ++OI) {
assert(OI->second.size() > 0 && "no final overrider");
CXXMethodDecl *Overrider = OI->second.front().Method;
if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
MarkFunctionReferenced(Loc, Overrider);
}
}
if (RD->getNumVBases() == 0)
return;
for (const auto &I : RD->bases()) {
const auto *Base =
cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
if (Base->getNumVBases() == 0)
continue;
MarkVirtualMembersReferenced(Loc, Base);
}
}
void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
if (!getLangOpts().CPlusPlus)
return;
if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
SmallVector<ObjCIvarDecl*, 8> ivars;
CollectIvarsToConstructOrDestruct(OID, ivars);
if (ivars.empty())
return;
SmallVector<CXXCtorInitializer*, 32> AllToInit;
for (unsigned i = 0; i < ivars.size(); i++) {
FieldDecl *Field = ivars[i];
if (Field->isInvalidDecl())
continue;
CXXCtorInitializer *Member;
InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
InitializationKind InitKind =
InitializationKind::CreateDefault(ObjCImplementation->getLocation());
InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
ExprResult MemberInit =
InitSeq.Perform(*this, InitEntity, InitKind, None);
MemberInit = MaybeCreateExprWithCleanups(MemberInit);
if (!MemberInit.get() || MemberInit.isInvalid())
continue;
Member =
new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
SourceLocation(),
MemberInit.getAs<Expr>(),
SourceLocation());
AllToInit.push_back(Member);
if (const RecordType *RecordTy =
Context.getBaseElementType(Field->getType())
->getAs<RecordType>()) {
CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
MarkFunctionReferenced(Field->getLocation(), Destructor);
CheckDestructorAccess(Field->getLocation(), Destructor,
PDiag(diag::err_access_dtor_ivar)
<< Context.getBaseElementType(Field->getType()));
}
}
}
ObjCImplementation->setIvarInitializers(Context,
AllToInit.data(), AllToInit.size());
}
}
static
void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
Sema &S) {
if (Ctor->isInvalidDecl())
return;
CXXConstructorDecl *Target = Ctor->getTargetConstructor();
if (Target) {
const FunctionDecl *FNTarget = nullptr;
(void)Target->hasBody(FNTarget);
Target = const_cast<CXXConstructorDecl*>(
cast_or_null<CXXConstructorDecl>(FNTarget));
}
CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
*TCanonical = Target? Target->getCanonicalDecl() : nullptr;
if (!Current.insert(Canonical).second)
return;
if (!Target || !Target->isDelegatingConstructor() ||
Target->isInvalidDecl() || Valid.count(TCanonical)) {
Valid.insert(Current.begin(), Current.end());
Current.clear();
} else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
Current.count(TCanonical)) {
if (!Invalid.count(TCanonical)) {
S.Diag((*Ctor->init_begin())->getSourceLocation(),
diag::warn_delegating_ctor_cycle)
<< Ctor;
if (TCanonical != Canonical)
S.Diag(Target->getLocation(), diag::note_it_delegates_to);
CXXConstructorDecl *C = Target;
while (C->getCanonicalDecl() != Canonical) {
const FunctionDecl *FNTarget = nullptr;
(void)C->getTargetConstructor()->hasBody(FNTarget);
assert(FNTarget && "Ctor cycle through bodiless function");
C = const_cast<CXXConstructorDecl*>(
cast<CXXConstructorDecl>(FNTarget));
S.Diag(C->getLocation(), diag::note_which_delegates_to);
}
}
Invalid.insert(Current.begin(), Current.end());
Current.clear();
} else {
DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
}
}
void Sema::CheckDelegatingCtorCycles() {
llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
for (DelegatingCtorDeclsType::iterator
I = DelegatingCtorDecls.begin(ExternalSource),
E = DelegatingCtorDecls.end();
I != E; ++I)
DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
(*CI)->setInvalidDecl();
}
namespace {
class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
Sema &S;
public:
explicit FindCXXThisExpr(Sema &S) : S(S) { }
bool VisitCXXThisExpr(CXXThisExpr *E) {
S.Diag(E->getLocation(), diag::err_this_static_member_func)
<< E->isImplicit();
return false;
}
};
}
bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
if (!TSInfo)
return false;
TypeLoc TL = TSInfo->getTypeLoc();
FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
if (!ProtoTL)
return false;
const FunctionProtoType *Proto = ProtoTL.getTypePtr();
FindCXXThisExpr Finder(*this);
if (Proto->hasTrailingReturn() &&
!Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
return true;
if (checkThisInStaticMemberFunctionExceptionSpec(Method))
return true;
if (Expr *E = Method->getTrailingRequiresClause())
if (!Finder.TraverseStmt(E))
return true;
return checkThisInStaticMemberFunctionAttributes(Method);
}
bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
if (!TSInfo)
return false;
TypeLoc TL = TSInfo->getTypeLoc();
FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
if (!ProtoTL)
return false;
const FunctionProtoType *Proto = ProtoTL.getTypePtr();
FindCXXThisExpr Finder(*this);
switch (Proto->getExceptionSpecType()) {
case EST_Unparsed:
case EST_Uninstantiated:
case EST_Unevaluated:
case EST_BasicNoexcept:
case EST_NoThrow:
case EST_DynamicNone:
case EST_MSAny:
case EST_None:
break;
case EST_DependentNoexcept:
case EST_NoexceptFalse:
case EST_NoexceptTrue:
if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
return true;
LLVM_FALLTHROUGH;
case EST_Dynamic:
for (const auto &E : Proto->exceptions()) {
if (!Finder.TraverseType(E))
return true;
}
break;
}
return false;
}
bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
FindCXXThisExpr Finder(*this);
for (const auto *A : Method->attrs()) {
Expr *Arg = nullptr;
ArrayRef<Expr *> Args;
if (const auto *G = dyn_cast<GuardedByAttr>(A))
Arg = G->getArg();
else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Arg = G->getArg();
else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Arg = ETLF->getSuccessValue();
Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
} else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Arg = STLF->getSuccessValue();
Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
} else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Arg = LR->getArg();
else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
if (Arg && !Finder.TraverseStmt(Arg))
return true;
for (unsigned I = 0, N = Args.size(); I != N; ++I) {
if (!Finder.TraverseStmt(Args[I]))
return true;
}
}
return false;
}
void Sema::checkExceptionSpecification(
bool IsTopLevel, ExceptionSpecificationType EST,
ArrayRef<ParsedType> DynamicExceptions,
ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
SmallVectorImpl<QualType> &Exceptions,
FunctionProtoType::ExceptionSpecInfo &ESI) {
Exceptions.clear();
ESI.Type = EST;
if (EST == EST_Dynamic) {
Exceptions.reserve(DynamicExceptions.size());
for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
if (IsTopLevel) {
SmallVector<UnexpandedParameterPack, 2> Unexpanded;
collectUnexpandedParameterPacks(ET, Unexpanded);
if (!Unexpanded.empty()) {
DiagnoseUnexpandedParameterPacks(
DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
Unexpanded);
continue;
}
}
if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
Exceptions.push_back(ET);
}
ESI.Exceptions = Exceptions;
return;
}
if (isComputedNoexcept(EST)) {
assert((NoexceptExpr->isTypeDependent() ||
NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
Context.BoolTy) &&
"Parser should have made sure that the expression is boolean");
if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
ESI.Type = EST_BasicNoexcept;
return;
}
ESI.NoexceptExpr = NoexceptExpr;
return;
}
}
void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
ExceptionSpecificationType EST,
SourceRange SpecificationRange,
ArrayRef<ParsedType> DynamicExceptions,
ArrayRef<SourceRange> DynamicExceptionRanges,
Expr *NoexceptExpr) {
if (!MethodD)
return;
if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
MethodD = FunTmpl->getTemplatedDecl();
CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
if (!Method)
return;
llvm::SmallVector<QualType, 4> Exceptions;
FunctionProtoType::ExceptionSpecInfo ESI;
checkExceptionSpecification(true, EST, DynamicExceptions,
DynamicExceptionRanges, NoexceptExpr, Exceptions,
ESI);
Context.adjustExceptionSpec(Method, ESI, true);
if (Method->isStatic())
checkThisInStaticMemberFunctionExceptionSpec(Method);
if (Method->isVirtual()) {
for (const CXXMethodDecl *O : Method->overridden_methods())
CheckOverridingFunctionExceptionSpec(Method, O);
}
}
MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
SourceLocation DeclStart, Declarator &D,
Expr *BitWidth,
InClassInitStyle InitStyle,
AccessSpecifier AS,
const ParsedAttr &MSPropertyAttr) {
IdentifierInfo *II = D.getIdentifier();
if (!II) {
Diag(DeclStart, diag::err_anonymous_property);
return nullptr;
}
SourceLocation Loc = D.getIdentifierLoc();
TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
QualType T = TInfo->getType();
if (getLangOpts().CPlusPlus) {
CheckExtraCXXDefaultArguments(D);
if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
UPPC_DataMemberType)) {
D.setInvalidType();
T = Context.IntTy;
TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
}
}
DiagnoseFunctionSpecifiers(D.getDeclSpec());
if (D.getDeclSpec().isInlineSpecified())
Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
<< getLangOpts().CPlusPlus17;
if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
diag::err_invalid_thread)
<< DeclSpec::getSpecifierName(TSCS);
NamedDecl *PrevDecl = nullptr;
LookupResult Previous(*this, II, Loc, LookupMemberName,
ForVisibleRedeclaration);
LookupName(Previous, S);
switch (Previous.getResultKind()) {
case LookupResult::Found:
case LookupResult::FoundUnresolvedValue:
PrevDecl = Previous.getAsSingle<NamedDecl>();
break;
case LookupResult::FoundOverloaded:
PrevDecl = Previous.getRepresentativeDecl();
break;
case LookupResult::NotFound:
case LookupResult::NotFoundInCurrentInstantiation:
case LookupResult::Ambiguous:
break;
}
if (PrevDecl && PrevDecl->isTemplateParameter()) {
DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
PrevDecl = nullptr;
}
if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
PrevDecl = nullptr;
SourceLocation TSSL = D.getBeginLoc();
MSPropertyDecl *NewPD =
MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
MSPropertyAttr.getPropertyDataGetter(),
MSPropertyAttr.getPropertyDataSetter());
ProcessDeclAttributes(TUScope, NewPD, D);
NewPD->setAccess(AS);
if (NewPD->isInvalidDecl())
Record->setInvalidDecl();
if (D.getDeclSpec().isModulePrivateSpecified())
NewPD->setModulePrivate();
if (NewPD->isInvalidDecl() && PrevDecl) {
} else if (II) {
PushOnScopeChains(NewPD, S);
} else
Record->addDecl(NewPD);
return NewPD;
}
void Sema::ActOnStartFunctionDeclarationDeclarator(
Declarator &Declarator, unsigned TemplateParameterDepth) {
auto &Info = InventedParameterInfos.emplace_back();
TemplateParameterList *ExplicitParams = nullptr;
ArrayRef<TemplateParameterList *> ExplicitLists =
Declarator.getTemplateParameterLists();
if (!ExplicitLists.empty()) {
bool IsMemberSpecialization, IsInvalid;
ExplicitParams = MatchTemplateParametersToScopeSpecifier(
Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
Declarator.getCXXScopeSpec(), nullptr,
ExplicitLists, false, IsMemberSpecialization, IsInvalid,
true);
}
if (ExplicitParams) {
Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
llvm::append_range(Info.TemplateParams, *ExplicitParams);
Info.NumExplicitTemplateParams = ExplicitParams->size();
} else {
Info.AutoTemplateParameterDepth = TemplateParameterDepth;
Info.NumExplicitTemplateParams = 0;
}
}
void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
auto &FSI = InventedParameterInfos.back();
if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
if (FSI.NumExplicitTemplateParams != 0) {
TemplateParameterList *ExplicitParams =
Declarator.getTemplateParameterLists().back();
Declarator.setInventedTemplateParameterList(
TemplateParameterList::Create(
Context, ExplicitParams->getTemplateLoc(),
ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
ExplicitParams->getRAngleLoc(),
ExplicitParams->getRequiresClause()));
} else {
Declarator.setInventedTemplateParameterList(
TemplateParameterList::Create(
Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
SourceLocation(), nullptr));
}
}
InventedParameterInfos.pop_back();
}