diff --git a/clang-tools-extra/clang-tidy/hicpp/ExceptionBaseclassCheck.cpp b/clang-tools-extra/clang-tidy/hicpp/ExceptionBaseclassCheck.cpp --- a/clang-tools-extra/clang-tidy/hicpp/ExceptionBaseclassCheck.cpp +++ b/clang-tools-extra/clang-tidy/hicpp/ExceptionBaseclassCheck.cpp @@ -52,7 +52,7 @@ diag(BadThrow->getSubExpr()->getBeginLoc(), "type %0 is a template instantiation of %1", DiagnosticIDs::Note) << BadThrow->getSubExpr()->getType() - << Template->getReplacedParameter()->getDecl(); + << Template->getReplacedTemplateParam(); if (const auto *TypeDecl = Result.Nodes.getNodeAs("decl")) diag(TypeDecl->getBeginLoc(), "type defined here", DiagnosticIDs::Note); diff --git a/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp b/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp --- a/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp +++ b/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp @@ -191,12 +191,13 @@ getSubstitutedType(VarType, Context)) { if (const SubstTemplateTypeParmType *InitializerTmplType = getSubstitutedType(InitializerType, Context)) { - return VarTmplType->getReplacedParameter() - ->desugar() - .getCanonicalType() != - InitializerTmplType->getReplacedParameter() - ->desugar() - .getCanonicalType(); + const TemplateTypeParmDecl *VarTTP = + VarTmplType->getReplacedTemplateParam(); + const TemplateTypeParmDecl *InitTTP = + InitializerTmplType->getReplacedTemplateParam(); + return (VarTTP->getDepth() != InitTTP->getDepth() || + VarTTP->getIndex() != InitTTP->getIndex() || + VarTTP->isParameterPack() != InitTTP->isParameterPack()); } } return false; diff --git a/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp b/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp --- a/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp @@ -128,7 +128,7 @@ auto UnlessFunctionType = unless(hasUnqualifiedDesugaredType(functionType())); auto IsAutoDeducedToPointer = [](const auto &...InnerMatchers) { return autoType(hasDeducedType( - hasUnqualifiedDesugaredType(pointerType(pointee(InnerMatchers...))))); + hasCanonicalType(pointerType(pointee(InnerMatchers...))))); }; Finder->addMatcher( diff --git a/clang-tools-extra/clangd/AST.cpp b/clang-tools-extra/clangd/AST.cpp --- a/clang-tools-extra/clangd/AST.cpp +++ b/clang-tools-extra/clangd/AST.cpp @@ -706,10 +706,10 @@ if (auto *RT = dyn_cast(PlainType)) PlainType = RT->getPointeeTypeAsWritten().getTypePtr(); if (const auto *SubstType = dyn_cast(PlainType)) { - const auto *ReplacedParameter = SubstType->getReplacedParameter(); + const auto *ReplacedParameter = SubstType->getReplacedTemplateParam(); if (ReplacedParameter->isParameterPack()) { - return dyn_cast( - ReplacedParameter->getCanonicalTypeUnqualified()->getTypePtr()); + return ReplacedParameter->getTypeForDecl() + ->castAs(); } } return nullptr; diff --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp b/clang-tools-extra/clangd/unittests/HoverTests.cpp --- a/clang-tools-extra/clangd/unittests/HoverTests.cpp +++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp @@ -995,7 +995,7 @@ HI.LocalScope = ""; HI.Kind = index::SymbolKind::TypeAlias; HI.Definition = "template using AA = A"; - HI.Type = {"A", "type-parameter-0-0"}; // FIXME: should be 'T' + HI.Type = {"A", "T"}; HI.TemplateParameters = {{{"typename"}, std::string("T"), llvm::None}}; }}, {// Constant array diff --git a/clang/include/clang/AST/ASTContext.h b/clang/include/clang/AST/ASTContext.h --- a/clang/include/clang/AST/ASTContext.h +++ b/clang/include/clang/AST/ASTContext.h @@ -1605,11 +1605,10 @@ QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped); - QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced, - QualType Replacement, + QualType getSubstTemplateTypeParmType(QualType Replacement, + Decl *ReplacedDecl, unsigned Index, Optional PackIndex) const; - QualType getSubstTemplateTypeParmPackType( - const TemplateTypeParmType *Replaced, + QualType getSubstTemplateTypeParmPackType(Decl *ReplacedDecl, unsigned Index, const TemplateArgument &ArgPack); QualType @@ -1626,7 +1625,7 @@ ArrayRef Args) const; QualType getTemplateSpecializationType(TemplateName T, - const TemplateArgumentListInfo &Args, + ArrayRef Args, QualType Canon = QualType()) const; TypeSourceInfo * @@ -1647,10 +1646,9 @@ const IdentifierInfo *Name, QualType Canon = QualType()) const; - QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, - NestedNameSpecifier *NNS, - const IdentifierInfo *Name, - const TemplateArgumentListInfo &Args) const; + QualType getDependentTemplateSpecializationType( + ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, + const IdentifierInfo *Name, ArrayRef Args) const; QualType getDependentTemplateSpecializationType( ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef Args) const; diff --git a/clang/include/clang/AST/ASTNodeTraverser.h b/clang/include/clang/AST/ASTNodeTraverser.h --- a/clang/include/clang/AST/ASTNodeTraverser.h +++ b/clang/include/clang/AST/ASTNodeTraverser.h @@ -389,12 +389,9 @@ void VisitBTFTagAttributedType(const BTFTagAttributedType *T) { Visit(T->getWrappedType()); } - void VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) { - Visit(T->getReplacedParameter()); - } + void VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *) {} void VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) { - Visit(T->getReplacedParameter()); Visit(T->getArgumentPack()); } void VisitTemplateSpecializationType(const TemplateSpecializationType *T) { diff --git a/clang/include/clang/AST/DeclTemplate.h b/clang/include/clang/AST/DeclTemplate.h --- a/clang/include/clang/AST/DeclTemplate.h +++ b/clang/include/clang/AST/DeclTemplate.h @@ -452,6 +452,8 @@ TemplatedDecl->getSourceRange().getEnd()); } + bool isTypeAlias() const; + protected: NamedDecl *TemplatedDecl; TemplateParameterList *TemplateParams; diff --git a/clang/include/clang/AST/JSONNodeDumper.h b/clang/include/clang/AST/JSONNodeDumper.h --- a/clang/include/clang/AST/JSONNodeDumper.h +++ b/clang/include/clang/AST/JSONNodeDumper.h @@ -221,6 +221,8 @@ void VisitTagType(const TagType *TT); void VisitTemplateTypeParmType(const TemplateTypeParmType *TTPT); void VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *STTPT); + void + VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T); void VisitAutoType(const AutoType *AT); void VisitTemplateSpecializationType(const TemplateSpecializationType *TST); void VisitInjectedClassNameType(const InjectedClassNameType *ICNT); diff --git a/clang/include/clang/AST/TemplateBase.h b/clang/include/clang/AST/TemplateBase.h --- a/clang/include/clang/AST/TemplateBase.h +++ b/clang/include/clang/AST/TemplateBase.h @@ -572,6 +572,12 @@ SourceLocation RAngleLoc) : LAngleLoc(LAngleLoc), RAngleLoc(RAngleLoc) {} + TemplateArgumentListInfo(TemplateArgumentListInfo &&) = default; + TemplateArgumentListInfo &operator=(TemplateArgumentListInfo &&) = default; + TemplateArgumentListInfo(const TemplateArgumentListInfo &) = default; + TemplateArgumentListInfo & + operator=(const TemplateArgumentListInfo &) = default; + // This can leak if used in an AST node, use ASTTemplateArgumentListInfo // instead. void *operator new(size_t bytes, ASTContext &C) = delete; @@ -588,9 +594,8 @@ return Arguments.data(); } - llvm::ArrayRef arguments() const { - return Arguments; - } + llvm::ArrayRef arguments() const { return Arguments; } + llvm::MutableArrayRef arguments() { return Arguments; } const TemplateArgumentLoc &operator[](unsigned I) const { return Arguments[I]; diff --git a/clang/include/clang/AST/TextNodeDumper.h b/clang/include/clang/AST/TextNodeDumper.h --- a/clang/include/clang/AST/TextNodeDumper.h +++ b/clang/include/clang/AST/TextNodeDumper.h @@ -318,6 +318,8 @@ void VisitTagType(const TagType *T); void VisitTemplateTypeParmType(const TemplateTypeParmType *T); void VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T); + void + VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T); void VisitAutoType(const AutoType *T); void VisitDeducedTemplateSpecializationType( const DeducedTemplateSpecializationType *T); diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h --- a/clang/include/clang/AST/Type.h +++ b/clang/include/clang/AST/Type.h @@ -1790,16 +1790,37 @@ unsigned NumArgs; }; + class UsingBitfields { + friend class UsingType; + + unsigned : NumTypeBits; + + /// True if this UsingType has underlying type different from decl. + unsigned hasDifferentUnderlyingType : 1; + }; + + class TypedefBitfields { + friend class TypedefType; + + unsigned : NumTypeBits; + + /// True if this typedef has underlying type different from decl. + unsigned hasDifferentUnderlyingType : 1; + }; + class SubstTemplateTypeParmTypeBitfields { friend class SubstTemplateTypeParmType; unsigned : NumTypeBits; + // The index of the template parameter this substitution represents. + unsigned Index : 16; + /// Represents the index within a pack if this represents a substitution /// from a pack expansion. /// Positive non-zero number represents the index + 1. /// Zero means this is not substituted from an expansion. - unsigned PackIndex; + unsigned PackIndex : 16; }; class SubstTemplateTypeParmPackTypeBitfields { @@ -1807,14 +1828,14 @@ unsigned : NumTypeBits; + // The index of the template parameter this substitution represents. + unsigned Index : 16; + /// The number of template arguments in \c Arguments, which is /// expected to be able to hold at least 1024 according to [implimits]. /// However as this limit is somewhat easy to hit with template /// metaprogramming we'd prefer to keep it as large as possible. - /// At the moment it has been left as a non-bitfield since this type - /// safely fits in 64 bits as an unsigned, so there is no reason to - /// introduce the performance impact of a bitfield. - unsigned NumArgs; + unsigned NumArgs : 16; }; class TemplateSpecializationTypeBitfields { @@ -1876,6 +1897,8 @@ ConstantArrayTypeBitfields ConstantArrayTypeBits; AttributedTypeBitfields AttributedTypeBits; AutoTypeBitfields AutoTypeBits; + TypedefBitfields TypedefBits; + UsingBitfields UsingBits; BuiltinTypeBitfields BuiltinTypeBits; FunctionTypeBitfields FunctionTypeBits; ObjCObjectTypeBitfields ObjCObjectTypeBits; @@ -4460,15 +4483,21 @@ public: UsingShadowDecl *getFoundDecl() const { return Found; } + bool hasDifferentUnderlyingType() const { + return UsingBits.hasDifferentUnderlyingType; + } QualType getUnderlyingType() const; bool isSugared() const { return true; } QualType desugar() const { return getUnderlyingType(); } - void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Found); } - static void Profile(llvm::FoldingSetNodeID &ID, - const UsingShadowDecl *Found) { + void Profile(llvm::FoldingSetNodeID &ID) { + Profile(ID, Found, getUnderlyingType()); + } + static void Profile(llvm::FoldingSetNodeID &ID, const UsingShadowDecl *Found, + QualType Underlying) { ID.AddPointer(Found); + Underlying.Profile(ID); } static bool classof(const Type *T) { return T->getTypeClass() == Using; } }; @@ -4484,6 +4513,9 @@ public: TypedefNameDecl *getDecl() const { return Decl; } + bool hasDifferentUnderlyingType() const { + return TypedefBits.hasDifferentUnderlyingType; + } bool isSugared() const { return true; } QualType desugar() const; @@ -4984,26 +5016,25 @@ friend class ASTContext; // The original type parameter. - const TemplateTypeParmType *Replaced; + QualType Replacement; - SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon, - Optional PackIndex) - : Type(SubstTemplateTypeParm, Canon, Canon->getDependence()), - Replaced(Param) { - SubstTemplateTypeParmTypeBits.PackIndex = PackIndex ? *PackIndex + 1 : 0; - } + // The templated entity which owned the substituted type parameter. + Decl *ReplacedDecl; -public: - /// Gets the template parameter that was substituted for. - const TemplateTypeParmType *getReplacedParameter() const { - return Replaced; - } + SubstTemplateTypeParmType(QualType Replacement, Decl *ReplacedDecl, + unsigned Index, Optional PackIndex); +public: /// Gets the type that was substituted for the template /// parameter. - QualType getReplacementType() const { - return getCanonicalTypeInternal(); - } + QualType getReplacementType() const { return Replacement; } + + /// Gets the template specialization that was substituted. + Decl *getReplacedDecl() const { return ReplacedDecl; } + + const TemplateTypeParmDecl *getReplacedTemplateParam() const; + + unsigned getIndex() const { return SubstTemplateTypeParmTypeBits.Index; } Optional getPackIndex() const { if (SubstTemplateTypeParmTypeBits.PackIndex == 0) @@ -5015,14 +5046,16 @@ QualType desugar() const { return getReplacementType(); } void Profile(llvm::FoldingSetNodeID &ID) { - Profile(ID, getReplacedParameter(), getReplacementType(), getPackIndex()); + Profile(ID, getReplacementType(), getReplacedDecl(), getIndex(), + getPackIndex()); } - static void Profile(llvm::FoldingSetNodeID &ID, - const TemplateTypeParmType *Replaced, - QualType Replacement, Optional PackIndex) { - ID.AddPointer(Replaced); + static void Profile(llvm::FoldingSetNodeID &ID, QualType Replacement, + const Decl *ReplacedDecl, unsigned Index, + Optional PackIndex) { + ID.AddPointer(ReplacedDecl); ID.AddPointer(Replacement.getAsOpaquePtr()); + ID.AddInteger(Index); ID.AddInteger(PackIndex ? *PackIndex - 1 : 0); } @@ -5046,24 +5079,26 @@ class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode { friend class ASTContext; - /// The original type parameter. - const TemplateTypeParmType *Replaced; - /// A pointer to the set of template arguments that this /// parameter pack is instantiated with. const TemplateArgument *Arguments; - SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, - QualType Canon, + // The template specialization which owned the substituted type parameter. + Decl *ReplacedDecl; + + SubstTemplateTypeParmPackType(QualType Canon, Decl *ReplacedDecl, + unsigned Index, const TemplateArgument &ArgPack); public: - IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); } + IdentifierInfo *getIdentifier() const; - /// Gets the template parameter that was substituted for. - const TemplateTypeParmType *getReplacedParameter() const { - return Replaced; - } + /// Gets the template specialization that was substituted. + Decl *getReplacedDecl() const { return ReplacedDecl; } + + const TemplateTypeParmDecl *getReplacedTemplateParam() const; + + unsigned getIndex() const { return SubstTemplateTypeParmPackTypeBits.Index; } unsigned getNumArgs() const { return SubstTemplateTypeParmPackTypeBits.NumArgs; @@ -5075,9 +5110,8 @@ TemplateArgument getArgumentPack() const; void Profile(llvm::FoldingSetNodeID &ID); - static void Profile(llvm::FoldingSetNodeID &ID, - const TemplateTypeParmType *Replaced, - const TemplateArgument &ArgPack); + static void Profile(llvm::FoldingSetNodeID &ID, const Decl *ReplacedDecl, + unsigned Index, const TemplateArgument &ArgPack); static bool classof(const Type *T) { return T->getTypeClass() == SubstTemplateTypeParmPack; diff --git a/clang/include/clang/AST/TypeLoc.h b/clang/include/clang/AST/TypeLoc.h --- a/clang/include/clang/AST/TypeLoc.h +++ b/clang/include/clang/AST/TypeLoc.h @@ -901,7 +901,7 @@ } }; -struct BTFTagAttributedLocInfo {}; // Nothing. +struct alignas(4) BTFTagAttributedLocInfo {}; // Nothing. /// Type source information for an btf_tag attributed type. class BTFTagAttributedTypeLoc diff --git a/clang/include/clang/AST/TypeProperties.td b/clang/include/clang/AST/TypeProperties.td --- a/clang/include/clang/AST/TypeProperties.td +++ b/clang/include/clang/AST/TypeProperties.td @@ -379,16 +379,12 @@ def : Property<"declaration", DeclRef> { let Read = [{ node->getDecl() }]; } - def : Property<"canonicalType", Optional> { - let Read = [{ makeOptionalFromNullable(node->getCanonicalTypeInternal()) }]; + def : Property<"underlyingType", QualType> { + let Read = [{ node->desugar() }]; } def : Creator<[{ - QualType finalCanonicalType = - canonicalType ? ctx.getCanonicalType(*canonicalType) - : QualType(); - return ctx.getTypedefType(cast(declaration), - finalCanonicalType); + return ctx.getTypedefType(cast(declaration), underlyingType); }]>; } @@ -728,21 +724,22 @@ } let Class = SubstTemplateTypeParmType in { - def : Property<"replacedParameter", QualType> { - let Read = [{ QualType(node->getReplacedParameter(), 0) }]; - } def : Property<"replacementType", QualType> { let Read = [{ node->getReplacementType() }]; } + def : Property<"replacedDecl", DeclRef> { + let Read = [{ node->getReplacedDecl() }]; + } + def : Property<"Index", UInt32> { + let Read = [{ node->getIndex() }]; + } def : Property<"PackIndex", Optional> { let Read = [{ node->getPackIndex() }]; } def : Creator<[{ - // The call to getCanonicalType here existed in ASTReader.cpp, too. return ctx.getSubstTemplateTypeParmType( - cast(replacedParameter), - ctx.getCanonicalType(replacementType), PackIndex); + replacementType, replacedDecl, Index, PackIndex); }]>; } @@ -761,8 +758,11 @@ } let Class = SubstTemplateTypeParmPackType in { - def : Property<"replacedParameter", QualType> { - let Read = [{ QualType(node->getReplacedParameter(), 0) }]; + def : Property<"replacedDecl", DeclRef> { + let Read = [{ node->getReplacedDecl() }]; + } + def : Property<"Index", UInt32> { + let Read = [{ node->getIndex() }]; } def : Property<"replacementPack", TemplateArgument> { let Read = [{ node->getArgumentPack() }]; @@ -770,8 +770,7 @@ def : Creator<[{ return ctx.getSubstTemplateTypeParmPackType( - cast(replacedParameter), - replacementPack); + replacedDecl, Index, replacementPack); }]>; } diff --git a/clang/include/clang/Basic/LangOptions.h b/clang/include/clang/Basic/LangOptions.h --- a/clang/include/clang/Basic/LangOptions.h +++ b/clang/include/clang/Basic/LangOptions.h @@ -467,6 +467,9 @@ /// forward slash (/) elsewhere. bool UseTargetPathSeparator = false; + /// Resugar template specializations. + bool Resugar = true; + LangOptions(); /// Set language defaults for the given input language and diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -5796,6 +5796,9 @@ LangOpts<"RecoveryASTType">, DefaultTrue, NegFlag, PosFlag>; +def fno_resugar : Flag<["-"], "fno-resugar">, + HelpText<"Do not resugar template specializations">, + MarshallingInfoNegativeFlag>; let Group = Action_Group in { diff --git a/clang/include/clang/Sema/Overload.h b/clang/include/clang/Sema/Overload.h --- a/clang/include/clang/Sema/Overload.h +++ b/clang/include/clang/Sema/Overload.h @@ -881,6 +881,9 @@ StandardConversionSequence FinalConversion; }; + /// Deduced Arguments for Function Templates. + const TemplateArgumentList *Deduced; + /// Get RewriteKind value in OverloadCandidateRewriteKind type (This /// function is to workaround the spurious GCC bitfield enum warning) OverloadCandidateRewriteKind getRewriteKind() const { diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -3844,7 +3844,8 @@ bool AllowExplicitConversion = false, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, ConversionSequenceList EarlyConversions = None, - OverloadCandidateParamOrder PO = {}); + OverloadCandidateParamOrder PO = {}, + const TemplateArgumentList *Deduced = nullptr); void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef Args, OverloadCandidateSet &CandidateSet, @@ -3859,16 +3860,16 @@ OverloadCandidateSet& CandidateSet, bool SuppressUserConversion = false, OverloadCandidateParamOrder PO = {}); - void AddMethodCandidate(CXXMethodDecl *Method, - DeclAccessPair FoundDecl, + void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef Args, - OverloadCandidateSet& CandidateSet, + OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, ConversionSequenceList EarlyConversions = None, - OverloadCandidateParamOrder PO = {}); + OverloadCandidateParamOrder PO = {}, + const TemplateArgumentList *Deduced = nullptr); void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, @@ -4004,10 +4005,9 @@ bool resolveAndFixAddressOfSingleOverloadCandidate( ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); - FunctionDecl * - ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, - bool Complain = false, - DeclAccessPair *Found = nullptr); + FunctionDecl *ResolveSingleFunctionTemplateSpecialization( + OverloadExpr *ovl, TemplateArgumentListInfo &ExplicitTemplateArgs, + bool Complain = false, DeclAccessPair *Found = nullptr); bool ResolveAndFixSingleFunctionTemplateSpecialization( ExprResult &SrcExpr, @@ -4017,13 +4017,13 @@ QualType DestTypeForComplaining = QualType(), unsigned DiagIDForComplaining = 0); - - Expr *FixOverloadedFunctionReference(Expr *E, - DeclAccessPair FoundDecl, - FunctionDecl *Fn); - ExprResult FixOverloadedFunctionReference(ExprResult, - DeclAccessPair FoundDecl, - FunctionDecl *Fn); + Expr *FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, + FunctionDecl *Fn, + const TemplateArgumentList *Deduced); + ExprResult + FixOverloadedFunctionReference(ExprResult, DeclAccessPair FoundDecl, + FunctionDecl *Fn, + const TemplateArgumentList *Deduced); void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef Args, @@ -5441,13 +5441,11 @@ SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); - ExprResult - BuildAnonymousStructUnionMemberReference( - const CXXScopeSpec &SS, - SourceLocation nameLoc, + ExprResult BuildAnonymousStructUnionMemberReference( + const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), - Expr *baseObjectExpr = nullptr, + Expr *baseObjectExpr = nullptr, const Type *BaseType = nullptr, SourceLocation opLoc = SourceLocation()); ExprResult BuildPossibleImplicitMemberExpr( @@ -5638,7 +5636,8 @@ ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, - const CXXScopeSpec &SS, FieldDecl *Field, + const NestedNameSpecifierLoc &NNS, + FieldDecl *Field, QualType FieldType, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo); @@ -7916,9 +7915,9 @@ void NoteAllFoundTemplates(TemplateName Name); - QualType CheckTemplateIdType(TemplateName Template, + QualType CheckTemplateIdType(const CXXScopeSpec &SS, TemplateName Template, SourceLocation TemplateLoc, - TemplateArgumentListInfo &TemplateArgs); + TemplateArgumentListInfo &TemplateArgs); TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, @@ -8069,14 +8068,13 @@ CTAK_DeducedFromArrayBound }; - bool CheckTemplateArgument(NamedDecl *Param, - TemplateArgumentLoc &Arg, - NamedDecl *Template, - SourceLocation TemplateLoc, + bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, + NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, - SmallVectorImpl &Converted, - CheckTemplateArgumentKind CTAK = CTAK_Specified); + SmallVectorImpl &Converted, + CheckTemplateArgumentKind CTAK, + bool DontCanonicalize); /// Check that the given template arguments can be be provided to /// the given template, converting the arguments along the way. @@ -8113,17 +8111,20 @@ bool PartialTemplateArgs, SmallVectorImpl &Converted, bool UpdateArgsWithConversions = true, - bool *ConstraintsNotSatisfied = nullptr); + bool *ConstraintsNotSatisfied = nullptr, + bool DontCanonicalize = false); bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, - SmallVectorImpl &Converted); + SmallVectorImpl &Converted, + bool DontCanonizalize); bool CheckTemplateArgument(TypeSourceInfo *Arg); ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType InstantiatedParamType, Expr *Arg, TemplateArgument &Converted, - CheckTemplateArgumentKind CTAK = CTAK_Specified); + CheckTemplateArgumentKind CTAK, + bool DontCanonizalize); bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg); @@ -8738,12 +8739,14 @@ TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, - sema::TemplateDeductionInfo &Info); + sema::TemplateDeductionInfo &Info, + bool DontCanonicalize = false); TemplateDeductionResult DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, - sema::TemplateDeductionInfo &Info); + sema::TemplateDeductionInfo &Info, + bool DontCanonicalize = false); TemplateDeductionResult SubstituteExplicitTemplateArguments( FunctionTemplateDecl *FunctionTemplate, @@ -9600,6 +9603,27 @@ } }; + enum class ResugarArgumentKind { AsWritten, Resolved }; + + QualType resugar(const CXXScopeSpec &SS, QualType T); + QualType + resugar(const CXXScopeSpec &SS, NamedDecl *ND, + ArrayRef Args, QualType T, + ResugarArgumentKind ArgumentKind = ResugarArgumentKind::AsWritten); + + QualType resugar(const Type *Base, NestedNameSpecifierLoc &FieldNNS, + QualType T); + QualType + resugar(const Type *Base, NestedNameSpecifierLoc &FieldNNS, NamedDecl *ND, + ArrayRef Args, QualType T, + ResugarArgumentKind ArgumentKind = ResugarArgumentKind::AsWritten); + + QualType resugar(const Type *Base, QualType T); + QualType + resugar(const Type *Base, NamedDecl *ND, ArrayRef Args, + QualType T, + ResugarArgumentKind ArgumentKind = ResugarArgumentKind::AsWritten); + void PerformPendingInstantiations(bool LocalOnly = false); TypeSourceInfo *SubstType(TypeSourceInfo *T, diff --git a/clang/include/clang/Sema/Template.h b/clang/include/clang/Sema/Template.h --- a/clang/include/clang/Sema/Template.h +++ b/clang/include/clang/Sema/Template.h @@ -76,9 +76,14 @@ /// The template argument list at a certain template depth using ArgList = ArrayRef; + struct ArgumentListLevel { + Decl *ReplacedDecl; + ArgList Args; + }; + /// The template argument lists, stored from the innermost template /// argument list (first) to the outermost template argument list (last). - SmallVector TemplateArgumentLists; + SmallVector TemplateArgumentLists; /// The number of outer levels of template arguments that are not /// being substituted. @@ -92,9 +97,8 @@ MultiLevelTemplateArgumentList() = default; /// Construct a single-level template argument list. - explicit - MultiLevelTemplateArgumentList(const TemplateArgumentList &TemplateArgs) { - addOuterTemplateArguments(&TemplateArgs); + explicit MultiLevelTemplateArgumentList(Decl *D, ArgList Args) { + addOuterTemplateArguments(D, Args); } void setKind(TemplateSubstitutionKind K) { Kind = K; } @@ -138,8 +142,14 @@ /// Retrieve the template argument at a given depth and index. const TemplateArgument &operator()(unsigned Depth, unsigned Index) const { assert(NumRetainedOuterLevels <= Depth && Depth < getNumLevels()); - assert(Index < TemplateArgumentLists[getNumLevels() - Depth - 1].size()); - return TemplateArgumentLists[getNumLevels() - Depth - 1][Index]; + assert(Index < + TemplateArgumentLists[getNumLevels() - Depth - 1].Args.size()); + return TemplateArgumentLists[getNumLevels() - Depth - 1].Args[Index]; + } + + Decl *getReplacedDecl(unsigned Depth) const { + assert(NumRetainedOuterLevels <= Depth && Depth < getNumLevels()); + return TemplateArgumentLists[getNumLevels() - Depth - 1].ReplacedDecl; } /// Determine whether there is a non-NULL template argument at the @@ -152,7 +162,8 @@ if (Depth < NumRetainedOuterLevels) return false; - if (Index >= TemplateArgumentLists[getNumLevels() - Depth - 1].size()) + if (Index >= + TemplateArgumentLists[getNumLevels() - Depth - 1].Args.size()) return false; return !(*this)(Depth, Index).isNull(); @@ -162,25 +173,34 @@ void setArgument(unsigned Depth, unsigned Index, TemplateArgument Arg) { assert(NumRetainedOuterLevels <= Depth && Depth < getNumLevels()); - assert(Index < TemplateArgumentLists[getNumLevels() - Depth - 1].size()); - const_cast( - TemplateArgumentLists[getNumLevels() - Depth - 1][Index]) - = Arg; + assert(Index < + TemplateArgumentLists[getNumLevels() - Depth - 1].Args.size()); + const_cast( + TemplateArgumentLists[getNumLevels() - Depth - 1].Args[Index]) = Arg; } - /// Add a new outermost level to the multi-level template argument + /// Add a new outmost level to the multi-level template argument /// list. - void addOuterTemplateArguments(const TemplateArgumentList *TemplateArgs) { - addOuterTemplateArguments(ArgList(TemplateArgs->data(), - TemplateArgs->size())); + void addOuterTemplateArguments(Decl *ReplacedDecl, ArgList Args) { + assert(!NumRetainedOuterLevels && + "substituted args outside retained args?"); + assert(getKind() == TemplateSubstitutionKind::Specialization); + assert(ReplacedDecl != nullptr || Args.size() == 0); + TemplateArgumentLists.push_back( + {ReplacedDecl ? ReplacedDecl->getCanonicalDecl() : nullptr, Args}); } - /// Add a new outmost level to the multi-level template argument - /// list. void addOuterTemplateArguments(ArgList Args) { assert(!NumRetainedOuterLevels && "substituted args outside retained args?"); - TemplateArgumentLists.push_back(Args); + assert(getKind() == TemplateSubstitutionKind::Rewrite); + TemplateArgumentLists.push_back({nullptr, Args}); + } + + void addOuterTemplateArguments(llvm::NoneType) { + assert(!NumRetainedOuterLevels && + "substituted args outside retained args?"); + TemplateArgumentLists.push_back({}); } /// Add an outermost level that we are not substituting. We have no @@ -195,7 +215,7 @@ /// Retrieve the innermost template argument list. const ArgList &getInnermost() const { - return TemplateArgumentLists.front(); + return TemplateArgumentLists.front().Args; } }; diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp --- a/clang/lib/AST/ASTContext.cpp +++ b/clang/lib/AST/ASTContext.cpp @@ -2367,12 +2367,12 @@ return getTypeInfo(cast(T)->desugar().getTypePtr()); case Type::Typedef: { - const TypedefNameDecl *Typedef = cast(T)->getDecl(); - TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); + const auto *TT = cast(T); + TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr()); // If the typedef has an aligned attribute on it, it overrides any computed // alignment we have. This violates the GCC documentation (which says that // attribute(aligned) can only round up) but matches its implementation. - if (unsigned AttrAlign = Typedef->getMaxAlignment()) { + if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) { Align = AttrAlign; AlignRequirement = AlignRequirementKind::RequiredByTypedef; } else { @@ -4630,14 +4630,22 @@ /// specified typedef name decl. QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl, QualType Underlying) const { - if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); - - if (Underlying.isNull()) - Underlying = Decl->getUnderlyingType(); - QualType Canonical = getCanonicalType(Underlying); - auto *newType = new (*this, TypeAlignment) - TypedefType(Type::Typedef, Decl, Underlying, Canonical); - Decl->TypeForDecl = newType; + if (!Decl->TypeForDecl) { + if (Underlying.isNull()) + Underlying = Decl->getUnderlyingType(); + auto *newType = new (*this, TypeAlignment) TypedefType( + Type::Typedef, Decl, QualType(), getCanonicalType(Underlying)); + Decl->TypeForDecl = newType; + Types.push_back(newType); + return QualType(newType, 0); + } + if (Underlying.isNull() || Decl->getUnderlyingType() == Underlying) + return QualType(Decl->TypeForDecl, 0); + assert(hasSameType(Decl->getUnderlyingType(), Underlying)); + // FIXME: Unique + void *Mem = Allocate(sizeof(TypedefType) + sizeof(QualType), TypeAlignment); + auto *newType = new (Mem) TypedefType(Type::Typedef, Decl, Underlying, + getCanonicalType(Underlying)); Types.push_back(newType); return QualType(newType, 0); } @@ -4645,19 +4653,26 @@ QualType ASTContext::getUsingType(const UsingShadowDecl *Found, QualType Underlying) const { llvm::FoldingSetNodeID ID; - UsingType::Profile(ID, Found); + UsingType::Profile(ID, Found, Underlying); void *InsertPos = nullptr; UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos); if (T) return QualType(T, 0); + const Type *TypeForDecl = + cast(Found->getTargetDecl())->getTypeForDecl(); + assert(!Underlying.hasLocalQualifiers()); - assert(Underlying == getTypeDeclType(cast(Found->getTargetDecl()))); - QualType Canon = Underlying.getCanonicalType(); + QualType Canon = Underlying->getCanonicalTypeInternal(); + assert(TypeForDecl->getCanonicalTypeInternal() == Canon); - UsingType *NewType = - new (*this, TypeAlignment) UsingType(Found, Underlying, Canon); + if (Underlying.getTypePtr() == TypeForDecl) + Underlying = QualType(); + void *Mem = Allocate(sizeof(UsingType) + + (!Underlying.isNull() ? sizeof(QualType) : 0), + TypeAlignment); + UsingType *NewType = new (Mem) UsingType(Found, Underlying, Canon); Types.push_back(NewType); UsingTypes.InsertNode(NewType, InsertPos); return QualType(NewType, 0); @@ -4747,21 +4762,19 @@ /// Retrieve a substitution-result type. QualType -ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, - QualType Replacement, +ASTContext::getSubstTemplateTypeParmType(QualType Replacement, + Decl *ReplacedDecl, unsigned Index, Optional PackIndex) const { - assert(Replacement.isCanonical() - && "replacement types must always be canonical"); - llvm::FoldingSetNodeID ID; - SubstTemplateTypeParmType::Profile(ID, Parm, Replacement, PackIndex); + SubstTemplateTypeParmType::Profile(ID, Replacement, ReplacedDecl, Index, + PackIndex); void *InsertPos = nullptr; - SubstTemplateTypeParmType *SubstParm - = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); + SubstTemplateTypeParmType *SubstParm = + SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); if (!SubstParm) { SubstParm = new (*this, TypeAlignment) - SubstTemplateTypeParmType(Parm, Replacement, PackIndex); + SubstTemplateTypeParmType(Replacement, ReplacedDecl, Index, PackIndex); Types.push_back(SubstParm); SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); } @@ -4770,34 +4783,32 @@ } /// Retrieve a -QualType ASTContext::getSubstTemplateTypeParmPackType( - const TemplateTypeParmType *Parm, - const TemplateArgument &ArgPack) { +QualType +ASTContext::getSubstTemplateTypeParmPackType(Decl *ReplacedDecl, unsigned Index, + const TemplateArgument &ArgPack) { #ifndef NDEBUG for (const auto &P : ArgPack.pack_elements()) { - assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); + assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type"); assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); } #endif llvm::FoldingSetNodeID ID; - SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); + SubstTemplateTypeParmPackType::Profile(ID, ReplacedDecl, Index, ArgPack); void *InsertPos = nullptr; - if (SubstTemplateTypeParmPackType *SubstParm - = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) + if (SubstTemplateTypeParmPackType *SubstParm = + SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(SubstParm, 0); QualType Canon; - if (!Parm->isCanonicalUnqualified()) { - Canon = getCanonicalType(QualType(Parm, 0)); - Canon = getSubstTemplateTypeParmPackType(cast(Canon), - ArgPack); + if (!ReplacedDecl->isCanonicalDecl()) { + Canon = getSubstTemplateTypeParmPackType(ReplacedDecl->getCanonicalDecl(), + Index, ArgPack); SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); } - auto *SubstParm - = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, - ArgPack); + auto *SubstParm = new (*this, TypeAlignment) + SubstTemplateTypeParmPackType(Canon, ReplacedDecl, Index, ArgPack); Types.push_back(SubstParm); SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); return QualType(SubstParm, 0); @@ -4843,7 +4854,8 @@ QualType Underlying) const { assert(!Name.getAsDependentTemplateName() && "No dependent template names here!"); - QualType TST = getTemplateSpecializationType(Name, Args, Underlying); + QualType TST = + getTemplateSpecializationType(Name, Args.arguments(), Underlying); TypeSourceInfo *DI = CreateTypeSourceInfo(TST); TemplateSpecializationTypeLoc TL = @@ -4859,14 +4871,14 @@ QualType ASTContext::getTemplateSpecializationType(TemplateName Template, - const TemplateArgumentListInfo &Args, + ArrayRef Args, QualType Underlying) const { assert(!Template.getAsDependentTemplateName() && "No dependent template names here!"); SmallVector ArgVec; ArgVec.reserve(Args.size()); - for (const TemplateArgumentLoc &Arg : Args.arguments()) + for (const TemplateArgumentLoc &Arg : Args) ArgVec.push_back(Arg.getArgument()); return getTemplateSpecializationType(Template, ArgVec, Underlying); @@ -4892,8 +4904,8 @@ if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) Template = QTN->getUnderlyingTemplate(); - bool IsTypeAlias = - isa_and_nonnull(Template.getAsTemplateDecl()); + const auto *TD = Template.getAsTemplateDecl(); + bool IsTypeAlias = TD && TD->isTypeAlias(); QualType CanonType; if (!Underlying.isNull()) CanonType = getCanonicalType(Underlying); @@ -5070,12 +5082,9 @@ return QualType(T, 0); } -QualType -ASTContext::getDependentTemplateSpecializationType( - ElaboratedTypeKeyword Keyword, - NestedNameSpecifier *NNS, - const IdentifierInfo *Name, - const TemplateArgumentListInfo &Args) const { +QualType ASTContext::getDependentTemplateSpecializationType( + ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, + const IdentifierInfo *Name, ArrayRef Args) const { // TODO: avoid this copy SmallVector ArgCopy; for (unsigned I = 0, E = Args.size(); I != E; ++I) @@ -7268,8 +7277,7 @@ void ASTContext::setCFConstantStringType(QualType T) { const auto *TD = T->castAs(); CFConstantStringTypeDecl = cast(TD->getDecl()); - const auto *TagType = - CFConstantStringTypeDecl->getUnderlyingType()->castAs(); + const auto *TagType = TD->castAs(); CFConstantStringTagDecl = TagType->getDecl(); } @@ -12777,16 +12785,15 @@ case Type::SubstTemplateTypeParm: { const auto *SX = cast(X), *SY = cast(Y); + unsigned Index = SX->getIndex(); auto PackIndex = SX->getPackIndex(); - if (PackIndex != SY->getPackIndex()) + if (Index != SY->getIndex() || PackIndex != SY->getPackIndex()) return QualType(); - - const TemplateTypeParmType *PX = SX->getReplacedParameter(); - if (PX != SY->getReplacedParameter()) + Decl *CD = ::getCommonDecl(SX->getReplacedDecl(), SY->getReplacedDecl()); + if (!CD) return QualType(); - - return Ctx.getSubstTemplateTypeParmType( - PX, Ctx.getQualifiedType(Underlying), PackIndex); + return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying), + CD, Index, PackIndex); } case Type::ObjCTypeParam: // FIXME: Try to merge these. diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp --- a/clang/lib/AST/ASTImporter.cpp +++ b/clang/lib/AST/ASTImporter.cpp @@ -1361,8 +1361,12 @@ Expected ToDeclOrErr = import(T->getDecl()); if (!ToDeclOrErr) return ToDeclOrErr.takeError(); + ExpectedType ToUnderlyingTypeOrErr = import(T->desugar()); + if (!ToUnderlyingTypeOrErr) + return ToUnderlyingTypeOrErr.takeError(); - return Importer.getToContext().getTypeDeclType(*ToDeclOrErr); + return Importer.getToContext().getTypedefType(*ToDeclOrErr, + *ToUnderlyingTypeOrErr); } ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) { @@ -1519,8 +1523,7 @@ ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmType( const SubstTemplateTypeParmType *T) { - Expected ReplacedOrErr = - import(T->getReplacedParameter()); + Expected ReplacedOrErr = import(T->getReplacedDecl()); if (!ReplacedOrErr) return ReplacedOrErr.takeError(); @@ -1529,14 +1532,13 @@ return ToReplacementTypeOrErr.takeError(); return Importer.getToContext().getSubstTemplateTypeParmType( - *ReplacedOrErr, ToReplacementTypeOrErr->getCanonicalType(), + *ToReplacementTypeOrErr, *ReplacedOrErr, T->getIndex(), T->getPackIndex()); } ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmPackType( const SubstTemplateTypeParmPackType *T) { - Expected ReplacedOrErr = - import(T->getReplacedParameter()); + Expected ReplacedOrErr = import(T->getReplacedDecl()); if (!ReplacedOrErr) return ReplacedOrErr.takeError(); @@ -1545,7 +1547,7 @@ return ToArgumentPack.takeError(); return Importer.getToContext().getSubstTemplateTypeParmPackType( - *ReplacedOrErr, *ToArgumentPack); + *ReplacedOrErr, T->getIndex(), *ToArgumentPack); } ExpectedType ASTNodeImporter::VisitTemplateSpecializationType( @@ -3599,6 +3601,10 @@ } } + // If it is a template, import all related things. + if (Error Err = ImportTemplateInformation(D, ToFunction)) + return std::move(Err); + if (D->doesThisDeclarationHaveABody()) { Error Err = ImportFunctionDeclBody(D, ToFunction); @@ -3620,10 +3626,6 @@ // FIXME: Other bits to merge? - // If it is a template, import all related things. - if (Error Err = ImportTemplateInformation(D, ToFunction)) - return std::move(Err); - addDeclToContexts(D, ToFunction); if (auto *FromCXXMethod = dyn_cast(D)) @@ -5843,6 +5845,30 @@ D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind()); + if (auto P = D->getInstantiatedFrom()) { + if (auto *CTD = P.dyn_cast()) { + if (auto CTDorErr = import(CTD)) + D2->setInstantiationOf(*CTDorErr); + } else { + auto *CTPSD = cast(P); + auto CTPSDOrErr = import(CTPSD); + if (!CTPSDOrErr) + return CTPSDOrErr.takeError(); + const TemplateArgumentList &DArgs = D->getTemplateInstantiationArgs(); + SmallVector D2ArgsVec(DArgs.size()); + for (unsigned I = 0; I < DArgs.size(); ++I) { + const TemplateArgument &DArg = DArgs[I]; + if (auto ArgOrErr = import(DArg)) + D2ArgsVec[I] = *ArgOrErr; + else + return ArgOrErr.takeError(); + } + D2->setInstantiationOf( + *CTPSDOrErr, + TemplateArgumentList::CreateCopy(Importer.getToContext(), D2ArgsVec)); + } + } + if (D->isCompleteDefinition()) if (Error Err = ImportDefinition(D, D2)) return std::move(Err); @@ -6006,15 +6032,6 @@ } } } else { - // Import the type. - QualType T; - if (Error Err = importInto(T, D->getType())) - return std::move(Err); - - auto TInfoOrErr = import(D->getTypeSourceInfo()); - if (!TInfoOrErr) - return TInfoOrErr.takeError(); - TemplateArgumentListInfo ToTAInfo; if (const ASTTemplateArgumentListInfo *Args = D->getTemplateArgsInfo()) { if (Error Err = ImportTemplateArgumentListInfo(*Args, ToTAInfo)) @@ -6039,7 +6056,7 @@ PartVarSpecDecl *ToPartial; if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC, *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr, - VarTemplate, T, *TInfoOrErr, + VarTemplate, QualType(), nullptr, D->getStorageClass(), TemplateArgs, ArgInfos)) return ToPartial; @@ -6060,11 +6077,21 @@ } else { // Full specialization if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, *BeginLocOrErr, *IdLocOrErr, VarTemplate, - T, *TInfoOrErr, - D->getStorageClass(), TemplateArgs)) + QualType(), nullptr, D->getStorageClass(), + TemplateArgs)) return D2; } + QualType T; + if (Error Err = importInto(T, D->getType())) + return std::move(Err); + D2->setType(T); + + auto TInfoOrErr = import(D->getTypeSourceInfo()); + if (!TInfoOrErr) + return TInfoOrErr.takeError(); + D2->setTypeSourceInfo(*TInfoOrErr); + if (D->getPointOfInstantiation().isValid()) { if (ExpectedSLoc POIOrErr = import(D->getPointOfInstantiation())) D2->setPointOfInstantiation(*POIOrErr); diff --git a/clang/lib/AST/ASTStructuralEquivalence.cpp b/clang/lib/AST/ASTStructuralEquivalence.cpp --- a/clang/lib/AST/ASTStructuralEquivalence.cpp +++ b/clang/lib/AST/ASTStructuralEquivalence.cpp @@ -957,11 +957,17 @@ if (!IsStructurallyEquivalent(Context, cast(T1)->getFoundDecl(), cast(T2)->getFoundDecl())) return false; + if (!IsStructurallyEquivalent(Context, + cast(T1)->getUnderlyingType(), + cast(T2)->getUnderlyingType())) + return false; break; case Type::Typedef: if (!IsStructurallyEquivalent(Context, cast(T1)->getDecl(), - cast(T2)->getDecl())) + cast(T2)->getDecl()) || + !IsStructurallyEquivalent(Context, cast(T1)->desugar(), + cast(T2)->desugar())) return false; break; @@ -1055,13 +1061,13 @@ case Type::SubstTemplateTypeParm: { const auto *Subst1 = cast(T1); const auto *Subst2 = cast(T2); - if (!IsStructurallyEquivalent(Context, - QualType(Subst1->getReplacedParameter(), 0), - QualType(Subst2->getReplacedParameter(), 0))) - return false; if (!IsStructurallyEquivalent(Context, Subst1->getReplacementType(), Subst2->getReplacementType())) return false; + if (Subst1->getReplacedDecl() != Subst2->getReplacedDecl()) + return false; + if (Subst1->getIndex() != Subst2->getIndex()) + return false; if (Subst1->getPackIndex() != Subst2->getPackIndex()) return false; break; @@ -1070,9 +1076,9 @@ case Type::SubstTemplateTypeParmPack: { const auto *Subst1 = cast(T1); const auto *Subst2 = cast(T2); - if (!IsStructurallyEquivalent(Context, - QualType(Subst1->getReplacedParameter(), 0), - QualType(Subst2->getReplacedParameter(), 0))) + if (Subst1->getReplacedDecl() != Subst2->getReplacedDecl()) + return false; + if (Subst1->getIndex() != Subst2->getIndex()) return false; if (!IsStructurallyEquivalent(Context, Subst1->getArgumentPack(), Subst2->getArgumentPack())) diff --git a/clang/lib/AST/DeclTemplate.cpp b/clang/lib/AST/DeclTemplate.cpp --- a/clang/lib/AST/DeclTemplate.cpp +++ b/clang/lib/AST/DeclTemplate.cpp @@ -250,6 +250,23 @@ return false; } +bool TemplateDecl::isTypeAlias() const { + switch (getKind()) { + case TemplateDecl::TypeAliasTemplate: + return true; + case TemplateDecl::BuiltinTemplate: { + const auto *BT = cast(this); + if (BT->getBuiltinTemplateKind() == + BuiltinTemplateKind::BTK__make_integer_seq) + return true; + return false; + } + default: + return false; + }; + llvm_unreachable("unknown template kind"); +} + //===----------------------------------------------------------------------===// // RedeclarableTemplateDecl Implementation //===----------------------------------------------------------------------===// diff --git a/clang/lib/AST/JSONNodeDumper.cpp b/clang/lib/AST/JSONNodeDumper.cpp --- a/clang/lib/AST/JSONNodeDumper.cpp +++ b/clang/lib/AST/JSONNodeDumper.cpp @@ -530,6 +530,8 @@ void JSONNodeDumper::VisitTypedefType(const TypedefType *TT) { JOS.attribute("decl", createBareDeclRef(TT->getDecl())); + if (TT->hasDifferentUnderlyingType()) + JOS.attribute("type", createQualType(TT->desugar())); } void JSONNodeDumper::VisitFunctionType(const FunctionType *T) { @@ -682,10 +684,16 @@ void JSONNodeDumper::VisitSubstTemplateTypeParmType( const SubstTemplateTypeParmType *STTPT) { + JOS.attribute("index", STTPT->getIndex()); if (auto PackIndex = STTPT->getPackIndex()) JOS.attribute("pack_index", *PackIndex); } +void JSONNodeDumper::VisitSubstTemplateTypeParmPackType( + const SubstTemplateTypeParmPackType *T) { + JOS.attribute("index", T->getIndex()); +} + void JSONNodeDumper::VisitAutoType(const AutoType *AT) { JOS.attribute("undeduced", !AT->isDeduced()); switch (AT->getKeyword()) { diff --git a/clang/lib/AST/ODRHash.cpp b/clang/lib/AST/ODRHash.cpp --- a/clang/lib/AST/ODRHash.cpp +++ b/clang/lib/AST/ODRHash.cpp @@ -671,7 +671,7 @@ } } - void AddDecl(Decl *D) { + void AddDecl(const Decl *D) { Hash.AddBoolean(D); if (D) { Hash.AddDecl(D); @@ -995,13 +995,13 @@ void VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) { - AddType(T->getReplacedParameter()); + AddDecl(T->getReplacedDecl()); Hash.AddTemplateArgument(T->getArgumentPack()); VisitType(T); } void VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) { - AddType(T->getReplacedParameter()); + AddDecl(T->getReplacedDecl()); AddQualType(T->getReplacementType()); VisitType(T); } diff --git a/clang/lib/AST/TextNodeDumper.cpp b/clang/lib/AST/TextNodeDumper.cpp --- a/clang/lib/AST/TextNodeDumper.cpp +++ b/clang/lib/AST/TextNodeDumper.cpp @@ -1543,10 +1543,14 @@ void TextNodeDumper::VisitUsingType(const UsingType *T) { dumpDeclRef(T->getFoundDecl()); + if (T->hasDifferentUnderlyingType()) + OS << " resugared"; } void TextNodeDumper::VisitTypedefType(const TypedefType *T) { dumpDeclRef(T->getDecl()); + if (T->hasDifferentUnderlyingType()) + OS << " resugared"; } void TextNodeDumper::VisitUnaryTransformType(const UnaryTransformType *T) { @@ -1570,10 +1574,18 @@ void TextNodeDumper::VisitSubstTemplateTypeParmType( const SubstTemplateTypeParmType *T) { + dumpDeclRef(T->getReplacedDecl()); + VisitTemplateTypeParmDecl(T->getReplacedTemplateParam()); if (auto PackIndex = T->getPackIndex()) OS << " pack_index " << *PackIndex; } +void TextNodeDumper::VisitSubstTemplateTypeParmPackType( + const SubstTemplateTypeParmPackType *T) { + dumpDeclRef(T->getReplacedDecl()); + VisitTemplateTypeParmDecl(T->getReplacedTemplateParam()); +} + void TextNodeDumper::VisitAutoType(const AutoType *T) { if (T->isDecltypeAuto()) OS << " decltype(auto)"; diff --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp --- a/clang/lib/AST/Type.cpp +++ b/clang/lib/AST/Type.cpp @@ -1166,8 +1166,9 @@ == T->getReplacementType().getAsOpaquePtr()) return QualType(T, 0); - return Ctx.getSubstTemplateTypeParmType(T->getReplacedParameter(), - replacementType, T->getPackIndex()); + return Ctx.getSubstTemplateTypeParmType(replacementType, + T->getReplacedDecl(), T->getIndex(), + T->getPackIndex()); } // FIXME: Non-trivial to implement, but important for C++ @@ -3434,25 +3435,35 @@ } TypedefType::TypedefType(TypeClass tc, const TypedefNameDecl *D, - QualType underlying, QualType can) - : Type(tc, can, toSemanticDependence(underlying->getDependence())), + QualType Underlying, QualType can) + : Type(tc, can, toSemanticDependence(can->getDependence())), Decl(const_cast(D)) { assert(!isa(can) && "Invalid canonical type"); + TypedefBits.hasDifferentUnderlyingType = !Underlying.isNull(); + if (hasDifferentUnderlyingType()) + *reinterpret_cast(this + 1) = Underlying; } QualType TypedefType::desugar() const { - return getDecl()->getUnderlyingType(); + return hasDifferentUnderlyingType() + ? *reinterpret_cast(this + 1) + : Decl->getUnderlyingType(); } UsingType::UsingType(const UsingShadowDecl *Found, QualType Underlying, QualType Canon) - : Type(Using, Canon, toSemanticDependence(Underlying->getDependence())), + : Type(Using, Canon, toSemanticDependence(Canon->getDependence())), Found(const_cast(Found)) { - assert(Underlying == getUnderlyingType()); + UsingBits.hasDifferentUnderlyingType = !Underlying.isNull(); + if (hasDifferentUnderlyingType()) + *reinterpret_cast(this + 1) = Underlying; } QualType UsingType::getUnderlyingType() const { - return QualType(cast(Found->getTargetDecl())->getTypeForDecl(), 0); + return hasDifferentUnderlyingType() + ? *reinterpret_cast(this + 1) + : QualType( + cast(Found->getTargetDecl())->getTypeForDecl(), 0); } QualType MacroQualifiedType::desugar() const { return getUnderlyingType(); } @@ -3649,14 +3660,105 @@ return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier(); } +static const TemplateParameterList * +getReplacedTemplateParameterList(const Decl *D) { + switch (D->getKind()) { + case Decl::Kind::ClassTemplate: + return cast(D)->getTemplateParameters(); + case Decl::Kind::ClassTemplateSpecialization: { + const auto *CTSD = cast(D); + auto P = CTSD->getSpecializedTemplateOrPartial(); + if (const auto *CTPSD = + P.dyn_cast()) + return CTPSD->getTemplateParameters(); + return cast(P)->getTemplateParameters(); + } + case Decl::Kind::ClassTemplatePartialSpecialization: + return cast(D) + ->getTemplateParameters(); + case Decl::Kind::TypeAliasTemplate: + return cast(D)->getTemplateParameters(); + case Decl::Kind::BuiltinTemplate: + return cast(D)->getTemplateParameters(); + case Decl::Kind::CXXConversion: + case Decl::Kind::CXXConstructor: + case Decl::Kind::CXXDestructor: + case Decl::Kind::CXXMethod: + case Decl::Kind::Function: + return cast(D) + ->getTemplateSpecializationInfo() + ->getTemplate() + ->getTemplateParameters(); + case Decl::Kind::FunctionTemplate: + return cast(D)->getTemplateParameters(); + case Decl::Kind::VarTemplate: + return cast(D)->getTemplateParameters(); + case Decl::Kind::VarTemplateSpecialization: { + const auto *VTSD = cast(D); + auto P = VTSD->getSpecializedTemplateOrPartial(); + if (const auto *VTPSD = + P.dyn_cast()) + return VTPSD->getTemplateParameters(); + return cast(P)->getTemplateParameters(); + } + case Decl::Kind::VarTemplatePartialSpecialization: + return cast(D) + ->getTemplateParameters(); + case Decl::Kind::TemplateTemplateParm: + return cast(D)->getTemplateParameters(); + case Decl::Kind::Concept: + return cast(D)->getTemplateParameters(); + default: + D->dumpColor(); + llvm_unreachable("Unhandled Replaced Kind"); + } +} + +static const TemplateTypeParmDecl *getReplacedTemplateParam(const Decl *D, + unsigned Index) { + if (const auto *TTP = dyn_cast(D)) + return TTP; + return cast( + getReplacedTemplateParameterList(D)->getParam(Index)); +} + +SubstTemplateTypeParmType::SubstTemplateTypeParmType( + QualType Replacement, Decl *ReplacedDecl, unsigned Index, + Optional PackIndex) + : Type(SubstTemplateTypeParm, Replacement.getCanonicalType(), + Replacement->getDependence()), + Replacement(Replacement), ReplacedDecl(ReplacedDecl) { + SubstTemplateTypeParmTypeBits.Index = Index; + SubstTemplateTypeParmTypeBits.PackIndex = PackIndex ? *PackIndex + 1 : 0; + assert(ReplacedDecl != nullptr); + assert(getReplacedTemplateParam() != nullptr); +} + +const TemplateTypeParmDecl * +SubstTemplateTypeParmType::getReplacedTemplateParam() const { + return ::getReplacedTemplateParam(getReplacedDecl(), getIndex()); +} + SubstTemplateTypeParmPackType::SubstTemplateTypeParmPackType( - const TemplateTypeParmType *Param, QualType Canon, + QualType Canon, Decl *ReplacedDecl, unsigned Index, const TemplateArgument &ArgPack) : Type(SubstTemplateTypeParmPack, Canon, TypeDependence::DependentInstantiation | TypeDependence::UnexpandedPack), - Replaced(Param), Arguments(ArgPack.pack_begin()) { + Arguments(ArgPack.pack_begin()), ReplacedDecl(ReplacedDecl) { + SubstTemplateTypeParmPackTypeBits.Index = Index; SubstTemplateTypeParmPackTypeBits.NumArgs = ArgPack.pack_size(); + assert(ReplacedDecl != nullptr); + assert(getReplacedTemplateParam() != nullptr); +} + +const TemplateTypeParmDecl * +SubstTemplateTypeParmPackType::getReplacedTemplateParam() const { + return ::getReplacedTemplateParam(getReplacedDecl(), getIndex()); +} + +IdentifierInfo *SubstTemplateTypeParmPackType::getIdentifier() const { + return getReplacedTemplateParam()->getIdentifier(); } TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const { @@ -3664,13 +3766,15 @@ } void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) { - Profile(ID, getReplacedParameter(), getArgumentPack()); + Profile(ID, getReplacedDecl(), getIndex(), getArgumentPack()); } void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID, - const TemplateTypeParmType *Replaced, + const Decl *ReplacedDecl, + unsigned Index, const TemplateArgument &ArgPack) { - ID.AddPointer(Replaced); + ID.AddPointer(ReplacedDecl); + ID.AddInteger(Index); ID.AddInteger(ArgPack.pack_size()); for (const auto &P : ArgPack.pack_elements()) ID.AddPointer(P.getAsType().getAsOpaquePtr()); diff --git a/clang/lib/AST/TypePrinter.cpp b/clang/lib/AST/TypePrinter.cpp --- a/clang/lib/AST/TypePrinter.cpp +++ b/clang/lib/AST/TypePrinter.cpp @@ -1470,14 +1470,27 @@ const SubstTemplateTypeParmPackType *T, raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); - printTemplateTypeParmBefore(T->getReplacedParameter(), OS); + if (const TemplateTypeParmDecl *D = T->getReplacedTemplateParam()) { + if (D && D->isImplicit()) { + if (auto *TC = D->getTypeConstraint()) { + TC->print(OS, Policy); + OS << ' '; + } + OS << "auto"; + } else if (IdentifierInfo *Id = D->getIdentifier()) + OS << (Policy.CleanUglifiedParameters ? Id->deuglifiedName() + : Id->getName()); + else + OS << "type-parameter-" << D->getDepth() << '-' << D->getIndex(); + + spaceBeforePlaceHolder(OS); + } } void TypePrinter::printSubstTemplateTypeParmPackAfter( const SubstTemplateTypeParmPackType *T, raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); - printTemplateTypeParmAfter(T->getReplacedParameter(), OS); } void TypePrinter::printTemplateId(const TemplateSpecializationType *T, diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp b/clang/lib/CodeGen/CGDebugInfo.cpp --- a/clang/lib/CodeGen/CGDebugInfo.cpp +++ b/clang/lib/CodeGen/CGDebugInfo.cpp @@ -1264,10 +1264,11 @@ assert(Ty->isTypeAlias()); llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit); - auto *AliasDecl = - cast(Ty->getTemplateName().getAsTemplateDecl()) - ->getTemplatedDecl(); + const TemplateDecl *TD = Ty->getTemplateName().getAsTemplateDecl(); + if (isa(TD)) + return Src; + const auto *AliasDecl = cast(TD)->getTemplatedDecl(); if (AliasDecl->hasAttr()) return Src; diff --git a/clang/lib/Sema/SemaCXXScopeSpec.cpp b/clang/lib/Sema/SemaCXXScopeSpec.cpp --- a/clang/lib/Sema/SemaCXXScopeSpec.cpp +++ b/clang/lib/Sema/SemaCXXScopeSpec.cpp @@ -734,8 +734,8 @@ return false; } - QualType T = - Context.getTypeDeclType(cast(SD->getUnderlyingDecl())); + QualType T = resugar( + SS, Context.getTypeDeclType(cast(SD->getUnderlyingDecl()))); if (T->isEnumeralType()) Diag(IdInfo.IdentifierLoc, diag::warn_cxx98_compat_enum_nested_name_spec); @@ -875,17 +875,19 @@ QualType T = BuildDecltypeType(DS.getRepAsExpr()); if (T.isNull()) return true; + T = resugar(SS, T); + + TypeLocBuilder TLB; + DecltypeTypeLoc DecltypeTL = TLB.push(T); + DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); + DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd()); if (!T->isDependentType() && !T->getAs()) { Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace) - << T << getLangOpts().CPlusPlus; + << T << getLangOpts().CPlusPlus; return true; } - TypeLocBuilder TLB; - DecltypeTypeLoc DecltypeTL = TLB.push(T); - DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); - DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd()); SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T), ColonColonLoc); return false; @@ -931,10 +933,9 @@ // Handle a dependent template specialization for which we cannot resolve // the template name. assert(DTN->getQualifier() == SS.getScopeRep()); - QualType T = Context.getDependentTemplateSpecializationType(ETK_None, - DTN->getQualifier(), - DTN->getIdentifier(), - TemplateArgs); + QualType T = Context.getDependentTemplateSpecializationType( + ETK_None, DTN->getQualifier(), DTN->getIdentifier(), + TemplateArgs.arguments()); // Create source-location information for this type. TypeLocBuilder Builder; @@ -975,18 +976,10 @@ // We were able to resolve the template name to an actual template. // Build an appropriate nested-name-specifier. - QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs); + QualType T = CheckTemplateIdType(SS, Template, TemplateNameLoc, TemplateArgs); if (T.isNull()) return true; - // Alias template specializations can produce types which are not valid - // nested name specifiers. - if (!T->isDependentType() && !T->getAs()) { - Diag(TemplateNameLoc, diag::err_nested_name_spec_non_tag) << T; - NoteAllFoundTemplates(Template); - return true; - } - // Provide source-location information for the template specialization type. TypeLocBuilder Builder; TemplateSpecializationTypeLoc SpecTL @@ -998,6 +991,13 @@ for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); + // Alias template specializations can produce types which are not valid + // nested name specifiers. + if (!T->isDependentType() && !T->getAs()) { + Diag(TemplateNameLoc, diag::err_nested_name_spec_non_tag) << T; + NoteAllFoundTemplates(Template); + return true; + } SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T), CCLoc); diff --git a/clang/lib/Sema/SemaCast.cpp b/clang/lib/Sema/SemaCast.cpp --- a/clang/lib/Sema/SemaCast.cpp +++ b/clang/lib/Sema/SemaCast.cpp @@ -1808,7 +1808,9 @@ return TC_Failed; } - SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn); + // FIXME: resugar + SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn, + nullptr); if (!SrcExpr.isUsable()) { msg = 0; return TC_Failed; @@ -2885,7 +2887,9 @@ DeclAccessPair DAP; if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction( SrcExpr.get(), DestType, /*Complain=*/true, DAP)) - SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD); + // FIXME: resugar + SrcExpr = + Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD, nullptr); else return; assert(SrcExpr.isUsable()); diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -560,9 +560,11 @@ if (!FD || FD->isUnnamedBitfield() || FD->isAnonymousStructOrUnion()) continue; + QualType FieldType = FD->getType(); + llvm::SmallString<20> Format = llvm::StringRef("%s%s %s "); llvm::SmallVector Args = {FieldIndentArg, - getTypeString(FD->getType()), + getTypeString(FieldType), getStringLiteral(FD->getName())}; if (FD->isBitField()) { @@ -578,15 +580,16 @@ ExprResult Field = IFD ? S.BuildAnonymousStructUnionMemberReference( CXXScopeSpec(), Loc, IFD, - DeclAccessPair::make(IFD, AS_public), RecordArg, Loc) + DeclAccessPair::make(IFD, AS_public), RecordArg, nullptr, + Loc) : S.BuildFieldReferenceExpr( - RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD, - DeclAccessPair::make(FD, AS_public), + RecordArg, RecordArgIsPtr, Loc, NestedNameSpecifierLoc(), + FD, FieldType, DeclAccessPair::make(FD, AS_public), DeclarationNameInfo(FD->getDeclName(), Loc)); if (Field.isInvalid()) return true; - auto *InnerRD = FD->getType()->getAsRecordDecl(); + auto *InnerRD = FieldType->getAsRecordDecl(); auto *InnerCXXRD = dyn_cast_or_null(InnerRD); if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) { // Recursively print the values of members of aggregate record type. @@ -595,7 +598,7 @@ return true; } else { Format += " "; - if (appendFormatSpecifier(FD->getType(), Format)) { + if (appendFormatSpecifier(FieldType, Format)) { // We know how to print this field. Args.push_back(Field.get()); } else { diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp --- a/clang/lib/Sema/SemaConcept.cpp +++ b/clang/lib/Sema/SemaConcept.cpp @@ -292,7 +292,8 @@ return true; MultiLevelTemplateArgumentList MLTAL; - MLTAL.addOuterTemplateArguments(TemplateArgs); + MLTAL.addOuterTemplateArguments(const_cast(Template), + TemplateArgs); for (const Expr *ConstraintExpr : ConstraintExprs) { if (calculateConstraintSatisfaction(S, Template, TemplateArgs, @@ -434,7 +435,7 @@ if (Inst.isInvalid()) return true; MultiLevelTemplateArgumentList MLTAL( - *Decl->getTemplateSpecializationArgs()); + Decl, Decl->getTemplateSpecializationArgs()->asArray()); if (addInstantiatedParametersToScope( Decl, Decl->getPrimaryTemplate()->getTemplatedDecl(), Scope, MLTAL)) return true; @@ -736,7 +737,7 @@ AtomicConstraint &Atomic = *N.getAtomicConstraint(); TemplateArgumentListInfo SubstArgs; MultiLevelTemplateArgumentList MLTAL; - MLTAL.addOuterTemplateArguments(TemplateArgs); + MLTAL.addOuterTemplateArguments(Concept, TemplateArgs); if (!Atomic.ParameterMapping) { llvm::SmallBitVector OccurringIndices(TemplateParams->size()); S.MarkUsedTemplateParameters(Atomic.ConstraintExpr, /*OnlyDeduced=*/false, diff --git a/clang/lib/Sema/SemaCoroutine.cpp b/clang/lib/Sema/SemaCoroutine.cpp --- a/clang/lib/Sema/SemaCoroutine.cpp +++ b/clang/lib/Sema/SemaCoroutine.cpp @@ -91,8 +91,8 @@ AddArg(T); // Build the template-id. - QualType CoroTrait = - S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args); + QualType CoroTrait = S.CheckTemplateIdType( + CXXScopeSpec(), TemplateName(CoroTraits), KwLoc, Args); if (CoroTrait.isNull()) return QualType(); if (S.RequireCompleteType(KwLoc, CoroTrait, @@ -169,8 +169,8 @@ S.Context.getTrivialTypeSourceInfo(PromiseType, Loc))); // Build the template-id. - QualType CoroHandleType = - S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args); + QualType CoroHandleType = S.CheckTemplateIdType( + CXXScopeSpec(), TemplateName(CoroHandle), Loc, Args); if (CoroHandleType.isNull()) return QualType(); if (S.RequireCompleteType(Loc, CoroHandleType, diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -530,6 +530,8 @@ DiagnoseUseOfDecl(IIDecl, NameLoc); T = Context.getTypeDeclType(TD); + if (SS && SS->isNotEmpty()) + T = resugar(*SS, T); MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); } else if (ObjCInterfaceDecl *IDecl = dyn_cast(IIDecl)) { (void)DiagnoseUseOfDecl(IDecl, NameLoc); @@ -12262,6 +12264,7 @@ return true; } + // FIXME: Set TypeSourceInfo? VDecl->setType(DeducedType); assert(VDecl->isLinkageValid()); diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp --- a/clang/lib/Sema/SemaDeclAttr.cpp +++ b/clang/lib/Sema/SemaDeclAttr.cpp @@ -3596,9 +3596,13 @@ return; } } else if (auto *ULE = dyn_cast(E)) { - if (ULE->hasExplicitTemplateArgs()) + if (ULE->hasExplicitTemplateArgs()) { S.Diag(Loc, diag::warn_cleanup_ext); - FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true); + TemplateArgumentListInfo ExplicitTemplateArgs; + ULE->copyTemplateArgumentsInto(ExplicitTemplateArgs); + FD = S.ResolveSingleFunctionTemplateSpecialization( + ULE, ExplicitTemplateArgs, /*Complain=*/true); + } NI = ULE->getNameInfo(); if (!FD) { S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2 @@ -3620,6 +3624,7 @@ // We're currently more strict than GCC about what function types we accept. // If this ever proves to be a problem it should be easy to fix. + // FIXME: resugar QualType Ty = S.Context.getPointerType(cast(D)->getType()); QualType ParamTy = FD->getParamDecl(0)->getType(); if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(), diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp --- a/clang/lib/Sema/SemaDeclCXX.cpp +++ b/clang/lib/Sema/SemaDeclCXX.cpp @@ -1031,7 +1031,8 @@ } // Build the template-id. - QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); + QualType TraitTy = + S.CheckTemplateIdType(CXXScopeSpec(), TemplateName(TraitTD), Loc, Args); if (TraitTy.isNull()) return true; if (!S.isCompleteType(Loc, TraitTy)) { @@ -1401,6 +1402,9 @@ if (FD->isUnnamedBitfield()) continue; + // FIXME: Avoid having to recreate the naming context for every field. + QualType FieldType = S.resugar(DecompType.getTypePtr(), FD->getType()); + // All the non-static data members are required to be nameable, so they // must all have names. if (!FD->getDeclName()) { @@ -1412,7 +1416,7 @@ if (FD->isAnonymousStructOrUnion()) { S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) - << DecompType << FD->getType()->isUnionType(); + << DecompType << FieldType->isUnionType(); S.Diag(FD->getLocation(), diag::note_declared_at); return true; } @@ -1444,7 +1448,7 @@ if (E.isInvalid()) return true; E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, - CXXScopeSpec(), FD, + NestedNameSpecifierLoc(), FD, FieldType, DeclAccessPair::make(FD, FD->getAccess()), DeclarationNameInfo(FD->getDeclName(), Loc)); if (E.isInvalid()) @@ -1458,7 +1462,7 @@ Qualifiers Q = DecompType.getQualifiers(); if (FD->isMutable()) Q.removeConst(); - B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); + B->setBinding(S.BuildQualifiedType(FieldType, Loc, Q), E.get()); } if (I != Bindings.size()) @@ -8246,10 +8250,13 @@ DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); + QualType FieldType = Field->getType(); return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, - CXXScopeSpec(), Field, Found, NameInfo), + NestedNameSpecifierLoc(), Field, + FieldType, Found, NameInfo), S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, - CXXScopeSpec(), Field, Found, NameInfo)}; + NestedNameSpecifierLoc(), Field, + FieldType, Found, NameInfo)}; } // FIXME: When expanding a subobject, register a note in the code synthesis @@ -11561,7 +11568,8 @@ return Context.getElaboratedType( ElaboratedTypeKeyword::ETK_None, NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()), - CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); + CheckTemplateIdType(CXXScopeSpec(), TemplateName(StdInitializerList), Loc, + Args)); } bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -3308,6 +3308,13 @@ QualType type = VD->getType(); if (type.isNull()) return ExprError(); + // A DeclRefExpr captures everything needed to make sense + // of the substitution sugar, so it's not correct to say + // that it would be escaping into it, however there is + // seemingly no use for it, and it would be more annoying + // to deal with it later. + type = TemplateArgs ? resugar(SS, VD, TemplateArgs->arguments(), type) + : resugar(SS, type); ExprValueKind valueKind = VK_PRValue; // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of @@ -9977,7 +9984,8 @@ DeclAccessPair DAP; if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( RHS.get(), LHSType, /*Complain=*/false, DAP)) - RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); + // FIXME: resugar + RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD, nullptr); else return Incompatible; } @@ -14255,14 +14263,18 @@ } OverloadExpr *Ovl = cast(E); - if (isa(Ovl)) - if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { - Diag(OpLoc, diag::err_invalid_form_pointer_member_function) - << OrigOp.get()->getSourceRange(); - return QualType(); - } - - return Context.OverloadTy; + if (!isa(Ovl)) + return Context.OverloadTy; + if (Ovl->hasExplicitTemplateArgs()) { + TemplateArgumentListInfo ExplicitTemplateArgs; + Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); + if (ResolveSingleFunctionTemplateSpecialization(Ovl, + ExplicitTemplateArgs)) + return Context.OverloadTy; + } + Diag(OpLoc, diag::err_invalid_form_pointer_member_function) + << OrigOp.get()->getSourceRange(); + return QualType(); } if (PTy->getKind() == BuiltinType::UnknownAny) @@ -14368,8 +14380,24 @@ if (isa(MD)) Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); - QualType MPTy = Context.getMemberPointerType( - op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); + const CXXRecordDecl *Cls = MD->getParent(); + const Type *ClsType = nullptr; + if (const NestedNameSpecifier *NNS = DRE->getQualifier()) { + const Type *Type = NNS->getAsType(); + const CXXRecordDecl *ClsAsWritten = + Type ? Type->getAsCXXRecordDecl() : NNS->getAsRecordDecl(); + assert(ClsAsWritten != nullptr); + if (declaresSameEntity(Cls, ClsAsWritten)) + ClsType = + Type ? Type : Context.getTypeDeclType(ClsAsWritten).getTypePtr(); + else + // FIXME: Can we do better here? + assert(ClsAsWritten->isDerivedFrom(Cls)); + } + if (!ClsType) + ClsType = Context.getTypeDeclType(Cls).getTypePtr(); + + QualType MPTy = Context.getMemberPointerType(op->getType(), ClsType); // Under the MS ABI, lock down the inheritance model now. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) (void)isCompleteType(OpLoc, MPTy); @@ -19449,10 +19477,18 @@ // Re-set the member to trigger a recomputation of the dependence bits // for the expression. - if (auto *DRE = dyn_cast_or_null(E)) + CXXScopeSpec SS; + if (auto *DRE = dyn_cast_or_null(E)) { DRE->setDecl(DRE->getDecl()); - else if (auto *ME = dyn_cast_or_null(E)) + SS.Adopt(DRE->getQualifierLoc()); + DRE->setType(SemaRef.resugar( + SS, DRE->getDecl(), DRE->template_arguments(), DRE->getType())); + } else if (auto *ME = dyn_cast_or_null(E)) { ME->setMemberDecl(ME->getMemberDecl()); + SS.Adopt(ME->getQualifierLoc()); + ME->setType(SemaRef.resugar(SS, ME->getMemberDecl(), + ME->template_arguments(), ME->getType())); + } } else if (FirstInstantiation || isa(Var)) { // FIXME: For a specialization of a variable template, we don't @@ -20663,6 +20699,7 @@ SS.Adopt(DRE->getQualifierLoc()); TemplateArgumentListInfo TemplateArgs; DRE->copyTemplateArgumentsInto(TemplateArgs); + // FIXME: resugar return BuildDeclRefExpr( FD, FD->getType(), VK_LValue, DRE->getNameInfo(), DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(), diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp --- a/clang/lib/Sema/SemaExprCXX.cpp +++ b/clang/lib/Sema/SemaExprCXX.cpp @@ -4249,7 +4249,8 @@ if (DiagnoseUseOfDecl(Fn, From->getBeginLoc())) return ExprError(); - From = FixOverloadedFunctionReference(From, Found, Fn); + // FIXME: resugar + From = FixOverloadedFunctionReference(From, Found, Fn, nullptr); // We might get back another placeholder expression if we resolved to a // builtin. @@ -8907,13 +8908,13 @@ Context.getReferenceQualifiedType(E).getCanonicalType(); llvm::SmallVector Args; Args.push_back(TemplateArgument(MatchedType)); + + auto *Param = cast(TPL->getParam(0)); + TemplateArgumentList TAL(TemplateArgumentList::OnStack, Args); - MultiLevelTemplateArgumentList MLTAL(TAL); - for (unsigned I = 0; I < TPL->getDepth(); ++I) - MLTAL.addOuterRetainedLevel(); - Expr *IDC = - cast(TPL->getParam(0))->getTypeConstraint() - ->getImmediatelyDeclaredConstraint(); + MultiLevelTemplateArgumentList MLTAL(Param, TAL.asArray()); + MLTAL.addOuterRetainedLevels(TPL->getDepth()); + Expr *IDC = Param->getTypeConstraint()->getImmediatelyDeclaredConstraint(); ExprResult Constraint = SubstExpr(IDC, MLTAL); if (Constraint.isInvalid()) { Status = concepts::ExprRequirement::SS_ExprSubstitutionFailure; diff --git a/clang/lib/Sema/SemaExprMember.cpp b/clang/lib/Sema/SemaExprMember.cpp --- a/clang/lib/Sema/SemaExprMember.cpp +++ b/clang/lib/Sema/SemaExprMember.cpp @@ -798,18 +798,14 @@ false, ExtraArgs); } -ExprResult -Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, - SourceLocation loc, - IndirectFieldDecl *indirectField, - DeclAccessPair foundDecl, - Expr *baseObjectExpr, - SourceLocation opLoc) { +ExprResult Sema::BuildAnonymousStructUnionMemberReference( + const CXXScopeSpec &SS, SourceLocation loc, + IndirectFieldDecl *indirectField, DeclAccessPair foundDecl, + Expr *baseObjectExpr, const Type *BaseType, SourceLocation opLoc) { // First, build the expression that refers to the base object. // Case 1: the base of the indirect field is not a field. VarDecl *baseVariable = indirectField->getVarDecl(); - CXXScopeSpec EmptySS; if (baseVariable) { assert(baseVariable->getType()->isRecordType()); @@ -822,6 +818,7 @@ DeclarationNameInfo baseNameInfo(DeclarationName(), loc); + CXXScopeSpec EmptySS; ExprResult result = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable); if (result.isInvalid()) return ExprError(); @@ -839,6 +836,8 @@ IndirectFieldDecl::chain_iterator FI = indirectField->chain_begin(), FEnd = indirectField->chain_end(); + NestedNameSpecifierLoc NNS = SS.getWithLocInContext(Context); + // Case 2: the base of the indirect field is a field and the user // wrote a member expression. if (!baseVariable) { @@ -849,11 +848,15 @@ // Make a nameInfo that properly uses the anonymous name. DeclarationNameInfo memberNameInfo(field->getDeclName(), loc); + // FIXME: Avoid redundant setting of the naming scope with the loop below. + QualType FieldType = + BaseType ? resugar(BaseType, NNS, field->getType()) : field->getType(); + // Build the first member access in the chain with full information. - result = - BuildFieldReferenceExpr(result, baseObjectIsPointer, SourceLocation(), - SS, field, foundDecl, memberNameInfo) - .get(); + result = BuildFieldReferenceExpr(result, baseObjectIsPointer, + SourceLocation(), NNS, field, FieldType, + foundDecl, memberNameInfo) + .get(); if (!result) return ExprError(); } @@ -869,10 +872,14 @@ DeclAccessPair fakeFoundDecl = DeclAccessPair::make(field, field->getAccess()); + QualType FieldType = BaseType && FI == FEnd + ? resugar(BaseType, NNS, field->getType()) + : field->getType(); + result = BuildFieldReferenceExpr(result, /*isarrow*/ false, SourceLocation(), - (FI == FEnd ? SS : EmptySS), field, - fakeFoundDecl, memberNameInfo) + (FI == FEnd ? NNS : NestedNameSpecifierLoc()), + field, FieldType, fakeFoundDecl, memberNameInfo) .get(); } @@ -1094,29 +1101,41 @@ if (DiagnoseUseOfDecl(MemberDecl, MemberLoc)) return ExprError(); - if (FieldDecl *FD = dyn_cast(MemberDecl)) - return BuildFieldReferenceExpr(BaseExpr, IsArrow, OpLoc, SS, FD, FoundDecl, - MemberNameInfo); + if (FieldDecl *FD = dyn_cast(MemberDecl)) { + assert(!TemplateArgs); + NestedNameSpecifierLoc NNS = SS.getWithLocInContext(Context); + QualType FieldType = resugar(BaseType.getTypePtr(), NNS, FD->getType()); + // null + // in case of implicit access. + return BuildFieldReferenceExpr(BaseExpr, IsArrow, OpLoc, NNS, FD, FieldType, + FoundDecl, MemberNameInfo); + } if (MSPropertyDecl *PD = dyn_cast(MemberDecl)) + // FIXME: resugar these. return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD, MemberNameInfo); if (IndirectFieldDecl *FD = dyn_cast(MemberDecl)) // We may have found a field within an anonymous union or struct // (C++ [class.union]). - return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD, - FoundDecl, BaseExpr, - OpLoc); + return BuildAnonymousStructUnionMemberReference( + SS, MemberLoc, FD, FoundDecl, BaseExpr, BaseType.getTypePtr(), OpLoc); if (VarDecl *Var = dyn_cast(MemberDecl)) { - return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc, Var, + assert(!TemplateArgs); + NestedNameSpecifierLoc NNS = SS.getWithLocInContext(Context); + QualType VarType = resugar(BaseType.getTypePtr(), NNS, Var->getType()); + return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, NNS, TemplateKWLoc, Var, FoundDecl, /*HadMultipleCandidates=*/false, - MemberNameInfo, Var->getType().getNonReferenceType(), + MemberNameInfo, VarType.getNonReferenceType(), VK_LValue, OK_Ordinary); } if (CXXMethodDecl *MemberFn = dyn_cast(MemberDecl)) { + assert(!TemplateArgs); + NestedNameSpecifierLoc NNS = SS.getWithLocInContext(Context); + ExprValueKind valueKind; QualType type; if (MemberFn->isInstance()) { @@ -1124,20 +1143,23 @@ type = Context.BoundMemberTy; } else { valueKind = VK_LValue; - type = MemberFn->getType(); + type = resugar(BaseType.getTypePtr(), NNS, MemberFn->getType()); } - return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc, + return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, NNS, TemplateKWLoc, MemberFn, FoundDecl, /*HadMultipleCandidates=*/false, MemberNameInfo, type, valueKind, OK_Ordinary); } assert(!isa(MemberDecl) && "member function not C++ method?"); if (EnumConstantDecl *Enum = dyn_cast(MemberDecl)) { - return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc, Enum, + assert(!TemplateArgs); + NestedNameSpecifierLoc NNS = SS.getWithLocInContext(Context); + // FIXME: EnumType resugaring not implemented. + QualType EnumType = resugar(BaseType.getTypePtr(), NNS, Enum->getType()); + return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, NNS, TemplateKWLoc, Enum, FoundDecl, /*HadMultipleCandidates=*/false, - MemberNameInfo, Enum->getType(), VK_PRValue, - OK_Ordinary); + MemberNameInfo, EnumType, VK_PRValue, OK_Ordinary); } if (VarTemplateDecl *VarTempl = dyn_cast(MemberDecl)) { @@ -1161,10 +1183,13 @@ if (!Var->getTemplateSpecializationKind()) Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation, MemberLoc); + NestedNameSpecifierLoc NNS = SS.getWithLocInContext(Context); + QualType VarType = resugar(BaseType.getTypePtr(), NNS, Var, + TemplateArgs->arguments(), Var->getType()); return BuildMemberExpr( - BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc, Var, FoundDecl, + BaseExpr, IsArrow, OpLoc, NNS, TemplateKWLoc, Var, FoundDecl, /*HadMultipleCandidates=*/false, MemberNameInfo, - Var->getType().getNonReferenceType(), VK_LValue, OK_Ordinary); + VarType.getNonReferenceType(), VK_LValue, OK_Ordinary); } // We found something that we didn't expect. Complain. @@ -1796,11 +1821,10 @@ } } -ExprResult -Sema::BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, - SourceLocation OpLoc, const CXXScopeSpec &SS, - FieldDecl *Field, DeclAccessPair FoundDecl, - const DeclarationNameInfo &MemberNameInfo) { +ExprResult Sema::BuildFieldReferenceExpr( + Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, + const NestedNameSpecifierLoc &NNS, FieldDecl *Field, QualType FieldType, + DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo) { // x.a is an l-value if 'a' has a reference type. Otherwise: // x.a is an l-value/x-value/pr-value if the base is (and note // that *x is always an l-value), except that if the base isn't @@ -1817,9 +1841,8 @@ OK = OK_BitField; // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref] - QualType MemberType = Field->getType(); - if (const ReferenceType *Ref = MemberType->getAs()) { - MemberType = Ref->getPointeeType(); + if (const ReferenceType *Ref = FieldType->getAs()) { + FieldType = Ref->getPointeeType(); VK = VK_LValue; } else { QualType BaseType = BaseExpr->getType(); @@ -1835,29 +1858,29 @@ if (Field->isMutable()) BaseQuals.removeConst(); Qualifiers MemberQuals = - Context.getCanonicalType(MemberType).getQualifiers(); + Context.getCanonicalType(FieldType).getQualifiers(); assert(!MemberQuals.hasAddressSpace()); Qualifiers Combined = BaseQuals + MemberQuals; if (Combined != MemberQuals) - MemberType = Context.getQualifiedType(MemberType, Combined); + FieldType = Context.getQualifiedType(FieldType, Combined); // Pick up NoDeref from the base in case we end up using AddrOf on the // result. E.g. the expression // &someNoDerefPtr->pointerMember // should be a noderef pointer again. if (BaseType->hasAttr(attr::NoDeref)) - MemberType = - Context.getAttributedType(attr::NoDeref, MemberType, MemberType); + FieldType = + Context.getAttributedType(attr::NoDeref, FieldType, FieldType); } auto *CurMethod = dyn_cast(CurContext); if (!(CurMethod && CurMethod->isDefaulted())) UnusedPrivateFields.remove(Field); - ExprResult Base = PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(), - FoundDecl, Field); + ExprResult Base = PerformObjectMemberConversion( + BaseExpr, NNS.getNestedNameSpecifier(), FoundDecl, Field); if (Base.isInvalid()) return ExprError(); @@ -1872,10 +1895,10 @@ } } - return BuildMemberExpr(Base.get(), IsArrow, OpLoc, &SS, + return BuildMemberExpr(Base.get(), IsArrow, OpLoc, NNS, /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl, /*HadMultipleCandidates=*/false, MemberNameInfo, - MemberType, VK, OK); + FieldType, VK, OK); } /// Builds an implicit member access expression. The current context diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp --- a/clang/lib/Sema/SemaInit.cpp +++ b/clang/lib/Sema/SemaInit.cpp @@ -8251,9 +8251,9 @@ S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl); if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation())) return ExprError(); - CurInit = S.FixOverloadedFunctionReference(CurInit, - Step->Function.FoundDecl, - Step->Function.Function); + // FIXME: resugar + CurInit = S.FixOverloadedFunctionReference( + CurInit, Step->Function.FoundDecl, Step->Function.Function, nullptr); // We might get back another placeholder expression if we resolved to a // builtin. if (!CurInit.isInvalid()) @@ -10275,12 +10275,13 @@ MarkFunctionReferenced(Kind.getLocation(), Best->Function); break; } + QualType RT = Best->Function->getReturnType(); + // FIXME: resugar here // C++ [dcl.type.class.deduct]p1: // The placeholder is replaced by the return type of the function selected // by overload resolution for class template deduction. - QualType DeducedType = - SubstAutoType(TSInfo->getType(), Best->Function->getReturnType()); + QualType DeducedType = SubstAutoType(TSInfo->getType(), RT); Diag(TSInfo->getTypeLoc().getBeginLoc(), diag::warn_cxx14_compat_class_template_argument_deduction) << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType; diff --git a/clang/lib/Sema/SemaLookup.cpp b/clang/lib/Sema/SemaLookup.cpp --- a/clang/lib/Sema/SemaLookup.cpp +++ b/clang/lib/Sema/SemaLookup.cpp @@ -3686,8 +3686,9 @@ SmallVector Checked; TemplateArgumentLoc Arg(TemplateArgument(StringLit), StringLit); if (CheckTemplateArgument(Params->getParam(0), Arg, FD, - R.getNameLoc(), R.getNameLoc(), 0, - Checked) || + R.getNameLoc(), R.getNameLoc(), 0, Checked, + CTAK_Specified, + /*DontCanonicalize=*/true) || Trap.hasErrorOccurred()) IsTemplate = false; } diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp --- a/clang/lib/Sema/SemaOverload.cpp +++ b/clang/lib/Sema/SemaOverload.cpp @@ -5691,9 +5691,6 @@ Sema::CCEKind CCE, bool RequireInt, NamedDecl *Dest) { - assert(S.getLangOpts().CPlusPlus11 && - "converted constant expression outside C++11"); - if (checkPlaceholderForOverload(S, From)) return ExprError(); @@ -6332,7 +6329,7 @@ OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, - OverloadCandidateParamOrder PO) { + OverloadCandidateParamOrder PO, const TemplateArgumentList *Deduced) { const FunctionProtoType *Proto = dyn_cast(Function->getType()->getAs()); assert(Proto && "Functions without a prototype cannot be overloaded"); @@ -6351,7 +6348,7 @@ AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), Expr::Classification::makeSimpleLValue(), Args, CandidateSet, SuppressUserConversions, - PartialOverloading, EarlyConversions, PO); + PartialOverloading, EarlyConversions, PO, Deduced); return; } // We treat a constructor like a non-member function, since its object @@ -6396,6 +6393,7 @@ Candidate.IsADLCandidate = IsADLCandidate; Candidate.IgnoreObjectArgument = false; Candidate.ExplicitCallArguments = Args.size(); + Candidate.Deduced = Deduced; // Explicit functions are not actually candidates at all if we're not // allowing them in this context, but keep them around so we can point @@ -6909,16 +6907,13 @@ /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't /// allow user-defined conversions via constructors or conversion /// operators. -void -Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, - CXXRecordDecl *ActingContext, QualType ObjectType, - Expr::Classification ObjectClassification, - ArrayRef Args, - OverloadCandidateSet &CandidateSet, - bool SuppressUserConversions, - bool PartialOverloading, - ConversionSequenceList EarlyConversions, - OverloadCandidateParamOrder PO) { +void Sema::AddMethodCandidate( + CXXMethodDecl *Method, DeclAccessPair FoundDecl, + CXXRecordDecl *ActingContext, QualType ObjectType, + Expr::Classification ObjectClassification, ArrayRef Args, + OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, + bool PartialOverloading, ConversionSequenceList EarlyConversions, + OverloadCandidateParamOrder PO, const TemplateArgumentList *Deduced) { const FunctionProtoType *Proto = dyn_cast(Method->getType()->getAs()); assert(Proto && "Methods without a prototype cannot be overloaded"); @@ -6949,6 +6944,7 @@ Candidate.IsSurrogate = false; Candidate.IgnoreObjectArgument = false; Candidate.ExplicitCallArguments = Args.size(); + Candidate.Deduced = Deduced; unsigned NumParams = Proto->getNumParams(); @@ -7125,7 +7121,7 @@ AddMethodCandidate(cast(Specialization), FoundDecl, ActingContext, ObjectType, ObjectClassification, Args, CandidateSet, SuppressUserConversions, PartialOverloading, - Conversions, PO); + Conversions, PO, Info.take()); } /// Determine whether a given function template has a simple explicit specifier @@ -7205,10 +7201,11 @@ // Add the function template specialization produced by template argument // deduction as a candidate. assert(Specialization && "Missing function template specialization?"); - AddOverloadCandidate( - Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, - PartialOverloading, AllowExplicit, - /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); + AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, + SuppressUserConversions, PartialOverloading, + AllowExplicit, + /*AllowExplicitConversions*/ false, IsADLCandidate, + Conversions, PO, Info.take()); } /// Check that implicit conversion sequences can be formed for each argument @@ -12054,15 +12051,20 @@ FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { ExtractUnqualifiedFunctionTypeFromTargetType(); + if (OvlExpr->hasExplicitTemplateArgs()) + OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); + if (TargetFunctionType->isFunctionType()) { if (UnresolvedMemberExpr *UME = dyn_cast(OvlExpr)) if (!UME->isImplicitAccess() && - !S.ResolveSingleFunctionTemplateSpecialization(UME)) + (!OvlExpr->hasExplicitTemplateArgs() || + !S.ResolveSingleFunctionTemplateSpecialization( + UME, OvlExplicitTemplateArgs))) StaticMemberFunctionFromBoundPointer = true; } else if (OvlExpr->hasExplicitTemplateArgs()) { DeclAccessPair dap; if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( - OvlExpr, false, &dap)) { + OvlExpr, OvlExplicitTemplateArgs, /*Complain=*/false, &dap)) { if (CXXMethodDecl *Method = dyn_cast(Fn)) if (!Method->isStatic()) { // If the target type is a non-function type and the function found @@ -12081,9 +12083,6 @@ return; } - if (OvlExpr->hasExplicitTemplateArgs()) - OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); - if (FindAllFunctionsThatMatchTargetTypeExactly()) { // C++ [over.over]p4: // If more than one function is selected, [...] @@ -12569,7 +12568,8 @@ // for both. DiagnoseUseOfDecl(Found, E->getExprLoc()); CheckAddressOfMemberAccess(E, DAP); - Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); + // FIXME: resugar + Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found, nullptr); if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); else @@ -12587,10 +12587,9 @@ /// /// If no template-ids are found, no diagnostics are emitted and NULL is /// returned. -FunctionDecl * -Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, - bool Complain, - DeclAccessPair *FoundResult) { +FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization( + OverloadExpr *ovl, TemplateArgumentListInfo &ExplicitTemplateArgs, + bool Complain, DeclAccessPair *FoundResult) { // C++ [over.over]p1: // [...] [Note: any redundant set of parentheses surrounding the // overloaded function name is ignored (5.1). ] @@ -12598,12 +12597,9 @@ // [...] The overloaded function name can be preceded by the & // operator. - // If we didn't actually find any template-ids, we're done. - if (!ovl->hasExplicitTemplateArgs()) - return nullptr; + // Specializations must have template args. + assert(ovl->hasExplicitTemplateArgs()); - TemplateArgumentListInfo ExplicitTemplateArgs; - ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); // Look through all of the overloaded functions, searching for one @@ -12679,50 +12675,54 @@ assert(SrcExpr.get()->getType() == Context.OverloadTy); OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); - - DeclAccessPair found; ExprResult SingleFunctionExpression; - if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( - ovl.Expression, /*complain*/ false, &found)) { - if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { - SrcExpr = ExprError(); - return true; - } + if (ovl.Expression->hasExplicitTemplateArgs()) { + TemplateArgumentListInfo ExplicitTemplateArgs; + ovl.Expression->copyTemplateArgumentsInto(ExplicitTemplateArgs); + + DeclAccessPair found; + if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( + ovl.Expression, ExplicitTemplateArgs, /*Complain=*/false, &found)) { + if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { + SrcExpr = ExprError(); + return true; + } - // It is only correct to resolve to an instance method if we're - // resolving a form that's permitted to be a pointer to member. - // Otherwise we'll end up making a bound member expression, which - // is illegal in all the contexts we resolve like this. - if (!ovl.HasFormOfMemberPointer && - isa(fn) && - cast(fn)->isInstance()) { - if (!complain) return false; - - Diag(ovl.Expression->getExprLoc(), - diag::err_bound_member_function) - << 0 << ovl.Expression->getSourceRange(); - - // TODO: I believe we only end up here if there's a mix of - // static and non-static candidates (otherwise the expression - // would have 'bound member' type, not 'overload' type). - // Ideally we would note which candidate was chosen and why - // the static candidates were rejected. - SrcExpr = ExprError(); - return true; - } + // It is only correct to resolve to an instance method if we're + // resolving a form that's permitted to be a pointer to member. + // Otherwise we'll end up making a bound member expression, which + // is illegal in all the contexts we resolve like this. + if (!ovl.HasFormOfMemberPointer && isa(fn) && + cast(fn)->isInstance()) { + if (!complain) + return false; - // Fix the expression to refer to 'fn'. - SingleFunctionExpression = - FixOverloadedFunctionReference(SrcExpr.get(), found, fn); + Diag(ovl.Expression->getExprLoc(), diag::err_bound_member_function) + << 0 << ovl.Expression->getSourceRange(); - // If desired, do function-to-pointer decay. - if (doFunctionPointerConverion) { - SingleFunctionExpression = - DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); - if (SingleFunctionExpression.isInvalid()) { + // TODO: I believe we only end up here if there's a mix of + // static and non-static candidates (otherwise the expression + // would have 'bound member' type, not 'overload' type). + // Ideally we would note which candidate was chosen and why + // the static candidates were rejected. SrcExpr = ExprError(); return true; } + + // Fix the expression to refer to 'fn'. + // FIXME: resugar + SingleFunctionExpression = + FixOverloadedFunctionReference(SrcExpr.get(), found, fn, nullptr); + + // If desired, do function-to-pointer decay. + if (doFunctionPointerConverion) { + SingleFunctionExpression = DefaultFunctionArrayLvalueConversion( + SingleFunctionExpression.get()); + if (SingleFunctionExpression.isInvalid()) { + SrcExpr = ExprError(); + return true; + } + } } } @@ -13235,7 +13235,8 @@ SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) return ExprError(); - Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); + Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl, + (*Best)->Deduced); return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, ExecConfig, /*IsExecConfig=*/false, (*Best)->IsADLCandidate); @@ -13293,7 +13294,8 @@ // We emitted an error for the unavailable/deleted function call but keep // the call in the AST. FunctionDecl *FDecl = (*Best)->Function; - Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); + Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl, + (*Best)->Deduced); return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, ExecConfig, /*IsExecConfig=*/false, (*Best)->IsADLCandidate); @@ -14561,7 +14563,8 @@ if (!Succeeded) return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best)); - MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); + MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method, + Best->Deduced); // If overload resolution picked a static member, build a // non-member call based on that function. @@ -14572,20 +14575,30 @@ MemExpr = cast(MemExprE->IgnoreParens()); } + assert(Method && "Member call to something that isn't a method?"); - QualType ResultType = Method->getReturnType(); - ExprValueKind VK = Expr::getValueKindForType(ResultType); - ResultType = ResultType.getNonLValueExprType(Context); + QualType MethodType; + { + QualType BaseType = MemExpr->getBase()->getType(); + if (MemExpr->isArrow()) + BaseType = BaseType->castAs()->getPointeeType(); + NestedNameSpecifierLoc NNS = MemExpr->getQualifierLoc(); + MethodType = resugar(BaseType.getTypePtr(), NNS, Method, + MemExpr->template_arguments(), Method->getType()); + } + + const auto *Proto = MethodType->castAs(); + QualType ReturnType = Proto->getReturnType(); + + ExprValueKind VK = Expr::getValueKindForType(ReturnType); + QualType ResultType = ReturnType.getNonLValueExprType(Context); - assert(Method && "Member call to something that isn't a method?"); - const auto *Proto = Method->getType()->castAs(); CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create( Context, MemExprE, Args, ResultType, VK, RParenLoc, CurFPFeatureOverrides(), Proto->getNumParams()); // Check for a valid return type. - if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), - TheCall, Method)) + if (CheckCallReturnType(ReturnType, MemExpr->getMemberLoc(), TheCall, Method)) return BuildRecoveryExpr(ResultType); // Convert the object argument (for a non-static member function call). @@ -15176,11 +15189,13 @@ /// perhaps a '&' around it). We have resolved the overloaded function /// to the function declaration Fn, so patch up the expression E to /// refer (possibly indirectly) to Fn. Returns the new expr. -Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, - FunctionDecl *Fn) { +Expr * +Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, + FunctionDecl *Fn, + const TemplateArgumentList *Deduced) { if (ParenExpr *PE = dyn_cast(E)) { - Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), - Found, Fn); + Expr *SubExpr = + FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn, Deduced); if (SubExpr == PE->getSubExpr()) return PE; @@ -15188,8 +15203,8 @@ } if (ImplicitCastExpr *ICE = dyn_cast(E)) { - Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), - Found, Fn); + Expr *SubExpr = + FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn, Deduced); assert(Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && "Implicit cast type cannot be determined from overload"); @@ -15204,8 +15219,8 @@ if (auto *GSE = dyn_cast(E)) { if (!GSE->isResultDependent()) { - Expr *SubExpr = - FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); + Expr *SubExpr = FixOverloadedFunctionReference(GSE->getResultExpr(), + Found, Fn, Deduced); if (SubExpr == GSE->getResultExpr()) return GSE; @@ -15227,6 +15242,16 @@ return GSE; } + SmallVector Args; + if (Deduced) { + Sema::SFINAETrap Trap(*this); + ArrayRef DeducedArray = Deduced->asArray(); + Args.resize(DeducedArray.size()); + for (unsigned I = 0; I < DeducedArray.size(); ++I) + Args[I] = getTrivialTemplateArgumentLoc(DeducedArray[I], QualType(), + SourceLocation()); + } + if (UnaryOperator *UnOp = dyn_cast(E)) { assert(UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function"); @@ -15239,7 +15264,7 @@ // UnresolvedLookupExpr holding an overloaded member function // or template. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), - Found, Fn); + Found, Fn, Deduced); if (SubExpr == UnOp->getSubExpr()) return UnOp; @@ -15251,10 +15276,13 @@ // We have taken the address of a pointer to member // function. Perform the computation here so that we get the // appropriate pointer to member type. + // FIXME: get sugared class type QualType ClassType = Context.getTypeDeclType(cast(Method->getDeclContext())); - QualType MemPtrType - = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); + QualType Type = resugar(CXXScopeSpec(), Fn, Args, Fn->getType(), + ResugarArgumentKind::Resolved); + QualType MemPtrType = + Context.getMemberPointerType(Type, ClassType.getTypePtr()); // Under the MS ABI, lock down the inheritance model now. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); @@ -15264,8 +15292,8 @@ UnOp->getOperatorLoc(), false, CurFPFeatureOverrides()); } } - Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), - Found, Fn); + Expr *SubExpr = + FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn, Deduced); if (SubExpr == UnOp->getSubExpr()) return UnOp; @@ -15281,21 +15309,28 @@ ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); TemplateArgs = &TemplateArgsBuffer; } + NestedNameSpecifierLoc NNS = ULE->getQualifierLoc(); - QualType Type = Fn->getType(); ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue; // FIXME: Duplicated from BuildDeclarationNameExpr. - if (unsigned BID = Fn->getBuiltinID()) { - if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) { + QualType Type; + { + unsigned BID = Fn->getBuiltinID(); + if (BID && !Context.BuiltinInfo.isDirectlyAddressable(BID)) { Type = Context.BuiltinFnTy; ValueKind = VK_PRValue; + } else { + CXXScopeSpec SS; + SS.Adopt(NNS); + Type = + resugar(SS, Fn, Args, Fn->getType(), ResugarArgumentKind::Resolved); } } DeclRefExpr *DRE = BuildDeclRefExpr( - Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(), - Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs); + Fn, Type, ValueKind, ULE->getNameInfo(), NNS, Found.getDecl(), + ULE->getTemplateKeywordLoc(), TemplateArgs); DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); return DRE; } @@ -15307,6 +15342,10 @@ MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); TemplateArgs = &TemplateArgsBuffer; } + QualType BaseType = MemExpr->getBaseType(); + const Type *BasePointeeType = BaseType->getPointeeType().getTypePtrOrNull(); + if (!BasePointeeType) + BasePointeeType = BaseType.getTypePtr(); Expr *Base; @@ -15314,46 +15353,50 @@ // implicit member access, rewrite to a simple decl ref. if (MemExpr->isImplicitAccess()) { if (cast(Fn)->isStatic()) { - DeclRefExpr *DRE = BuildDeclRefExpr( - Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), - MemExpr->getQualifierLoc(), Found.getDecl(), - MemExpr->getTemplateKeywordLoc(), TemplateArgs); + QualType Type = resugar(BasePointeeType, Fn, Args, Fn->getType(), + ResugarArgumentKind::Resolved); + DeclRefExpr *DRE = + BuildDeclRefExpr(Fn, Type, VK_LValue, MemExpr->getNameInfo(), + MemExpr->getQualifierLoc(), Found.getDecl(), + MemExpr->getTemplateKeywordLoc(), TemplateArgs); DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); return DRE; } else { SourceLocation Loc = MemExpr->getMemberLoc(); if (MemExpr->getQualifier()) Loc = MemExpr->getQualifierLoc().getBeginLoc(); - Base = - BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); + Base = BuildCXXThisExpr(Loc, BaseType, /*IsImplicit=*/true); } } else Base = MemExpr->getBase(); ExprValueKind valueKind; - QualType type; + QualType Type; if (cast(Fn)->isStatic()) { valueKind = VK_LValue; - type = Fn->getType(); + Type = resugar(BasePointeeType, Fn, Args, Fn->getType(), + ResugarArgumentKind::Resolved); } else { valueKind = VK_PRValue; - type = Context.BoundMemberTy; + Type = Context.BoundMemberTy; } + // FIXME: This should carry the sugared resolved template arguments as well. return BuildMemberExpr( Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, - /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), - type, valueKind, OK_Ordinary, TemplateArgs); + /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), Type, + valueKind, OK_Ordinary, TemplateArgs); } llvm_unreachable("Invalid reference to overloaded function"); } -ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, - DeclAccessPair Found, - FunctionDecl *Fn) { - return FixOverloadedFunctionReference(E.get(), Found, Fn); +ExprResult +Sema::FixOverloadedFunctionReference(ExprResult E, DeclAccessPair Found, + FunctionDecl *Fn, + const TemplateArgumentList *Deduced) { + return FixOverloadedFunctionReference(E.get(), Found, Fn, Deduced); } bool clang::shouldEnforceArgLimit(bool PartialOverloading, diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp --- a/clang/lib/Sema/SemaTemplate.cpp +++ b/clang/lib/Sema/SemaTemplate.cpp @@ -11,6 +11,7 @@ #include "TreeTransform.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" +#include "clang/AST/ASTLambda.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclFriend.h" #include "clang/AST/DeclTemplate.h" @@ -90,6 +91,1204 @@ return Depth; } +TemplateDecl *getTemplateDecl(NamedDecl *D) { + switch (D->getKind()) { + case Decl::Kind::Var: + case Decl::Kind::ParmVar: + case Decl::Kind::Field: + case Decl::Kind::IndirectField: + case Decl::Kind::EnumConstant: + case Decl::Kind::Binding: + case Decl::Kind::ImplicitParam: + case Decl::Kind::MSGuid: + case Decl::Kind::MSProperty: + case Decl::Kind::NonTypeTemplateParm: + case Decl::Kind::TemplateParamObject: + return nullptr; + case Decl::Kind::FunctionTemplate: + case Decl::Kind::ClassTemplate: + case Decl::Kind::TypeAliasTemplate: + case Decl::Kind::BuiltinTemplate: + return cast(D); + case Decl::Kind::VarTemplateSpecialization: + return cast(D)->getSpecializedTemplate(); + case Decl::Kind::CXXDeductionGuide: + return cast(D)->getDeducedTemplate(); + case Decl::Kind::CXXConversion: + case Decl::Kind::CXXConstructor: + case Decl::Kind::CXXDestructor: + case Decl::Kind::CXXMethod: + case Decl::Kind::Function: { + const auto *FD = cast(D); + switch (FD->getTemplatedKind()) { + case FunctionDecl::TK_NonTemplate: + return nullptr; + case FunctionDecl::TK_FunctionTemplate: + return FD->getDescribedFunctionTemplate(); + case FunctionDecl::TK_MemberSpecialization: + return nullptr; + case FunctionDecl::TK_FunctionTemplateSpecialization: + return FD->getPrimaryTemplate(); + case FunctionDecl::TK_DependentFunctionTemplateSpecialization: + return nullptr; + } + llvm_unreachable("Unhandled function template kind"); + } + case Decl::Kind::CXXRecord: + return cast(D)->getDescribedClassTemplate(); + case Decl::Kind::TemplateTemplateParm: + return cast(D); + default: + // Maybe fall back to Decl::getDescribedTemplate. + D->dumpColor(); + llvm_unreachable("Unhandled decl kind"); + } +} + +namespace { +class Resugarer : public TreeTransform { + using inherited = TreeTransform; + + struct Inner { + const Decl *ReplacedDecl; + ArrayRef Args; + }; + Inner CurInner; + + using TemplateToArgs = + llvm::DenseMap>; + TemplateToArgs CurTemplateToArgs; + + SmallVector, 4> ArgsBuf; + + const TemplateArgument *getArgument(const Decl *ReplacedDecl, unsigned Index, + Optional PackIndex) const { + ArrayRef Args; + if (!CurInner.Args.empty() && CurInner.ReplacedDecl == ReplacedDecl) { + Args = CurInner.Args; + } else { + auto It = CurTemplateToArgs.find(ReplacedDecl); + if (It == CurTemplateToArgs.end()) + return nullptr; + Args = It->second; + } + // FIXME: This should never happen, but some arguments might be missing + // from argument deduction of function templates + if (Index >= Args.size()) + return nullptr; + const TemplateArgument &Arg = Args[Index]; + if (!PackIndex) + return &Arg; + ArrayRef PackArgs = Arg.getPackAsArray(); + // FIXME: As above, arguments might be missing. + if (*PackIndex >= PackArgs.size()) + return nullptr; + return &PackArgs[*PackIndex]; + } + + struct BaseSemanticContextRAII { + BaseSemanticContextRAII(Resugarer &R) + : R(&R), OldInner(std::move(R.CurInner)) {} + ~BaseSemanticContextRAII() { R->CurInner = std::move(OldInner); } + + protected: + Resugarer *R; + + private: + Inner OldInner; + }; + +public: + struct NonTemplateSemanticContextRAII { + NonTemplateSemanticContextRAII(Resugarer &R) + : R(&R), OldInner(std::move(R.CurInner)) {} + ~NonTemplateSemanticContextRAII() { R->CurInner = std::move(OldInner); } + + protected: + Resugarer *R; + + private: + Inner OldInner; + }; + + struct SemanticContextRAII : private NonTemplateSemanticContextRAII { + SemanticContextRAII(Resugarer &R, NamedDecl *ND, + ArrayRef Args, + bool AsWritten = true) + : NonTemplateSemanticContextRAII(R), OldArgsBufSize(R.ArgsBuf.size()) { + assert(ND != nullptr); + if (Args.size() == 0) + return; + TemplateDecl *TD = getTemplateDecl(ND); + assert(TD != nullptr); + R.CurInner.ReplacedDecl = TD->getCanonicalDecl(); + + SmallVector ConvertedArgs; + if (!AsWritten) { + ConvertedArgs.reserve(Args.size()); + for (const TemplateArgumentLoc &I : Args) + ConvertedArgs.push_back(I.getArgument()); + R.CurInner.Args = R.ArgsBuf.emplace_back(std::move(ConvertedArgs)); + return; + } + + Sema::SFINAETrap Trap(R.SemaRef); + + Qualifiers ThisTypeQuals; + CXXRecordDecl *ThisContext = nullptr; + if (auto *Method = dyn_cast(ND)) { + ThisContext = Method->getParent(); + ThisTypeQuals = Method->getMethodQualifiers(); + } + Sema::CXXThisScopeRAII ThisScope(R.SemaRef, ThisContext, ThisTypeQuals, + R.SemaRef.getLangOpts().CPlusPlus17); + + TemplateArgumentListInfo TAL; + for (const auto &ArgLoc : Args) + TAL.addArgument(ArgLoc); + if (R.SemaRef.CheckTemplateArgumentList( + TD, SourceLocation(), TAL, false, ConvertedArgs, + /*UpdateArgsWithConversions=*/false, + /*ConstrantsNotSatisfied=*/nullptr, + /*DontCanonicalize=*/true)) { + // FIXME: This can fail sometimes because we only keep + // the as-written template arguments around for + // functions, and we don't have the information + // to try to deduce them again. + assert(TD->getKind() == Decl::Kind::FunctionTemplate); + return; + } + switch (ND->getKind()) { + case Decl::Kind::TypeAliasTemplate: + case Decl::Kind::BuiltinTemplate: + case Decl::Kind::CXXMethod: + case Decl::Kind::Function: + break; + case Decl::Kind::VarTemplateSpecialization: { + auto *VD = cast(ND); + auto *VTPSD = VD->getSpecializedTemplateOrPartial() + .dyn_cast(); + if (!VTPSD) + break; + TemplateParameterList *TPL = VTPSD->getTemplateParameters(); + TemplateDeductionInfo Info(SourceLocation{}, TPL->getDepth()); + // FIXME: We can't deal very well with non-canonical template + // arguments so this will fail sometimes. + Sema::TemplateDeductionResult Res = R.SemaRef.DeduceTemplateArguments( + VTPSD, + TemplateArgumentList(TemplateArgumentList::OnStackType{}, + ConvertedArgs), + Info, + /*DontCaninicalize=*/true); + if (Res != Sema::TDK_Success) + break; + R.CurInner.Args = Info.take()->asArray(); + return; + } + default: + ND->dump(); + llvm_unreachable("Unhandled Template Kind"); + } + R.CurInner.Args = R.ArgsBuf.emplace_back(std::move(ConvertedArgs)); + } + + ~SemanticContextRAII() { R->ArgsBuf.resize(OldArgsBufSize); } + + size_t OldArgsBufSize; + }; + + struct NamingContextBase { + NamingContextBase(Resugarer &R) + : R(&R), OldTemplateToArgs(std::move(R.CurTemplateToArgs)), + OldArgsBufSize(R.ArgsBuf.size()) {} + ~NamingContextBase() { + R->CurTemplateToArgs = std::move(OldTemplateToArgs); + R->ArgsBuf.resize(OldArgsBufSize); + } + + protected: + void insertTemplateToMap(bool Reverse, const Decl *Template, + ArrayRef Args) { + Template = Template->getCanonicalDecl(); + assert(!Args.empty()); + if (Reverse) { + R->CurTemplateToArgs.try_emplace(Template, Args); + } else { + R->CurTemplateToArgs[Template] = Args; + } + } + + void deduceClassTemplatePartialSpecialization( + ClassTemplatePartialSpecializationDecl *CTPSD, bool Reverse, + ArrayRef Args, + ClassTemplateSpecializationDecl *CTSD) { + TemplateParameterList *TPL = CTPSD->getTemplateParameters(); + TemplateDeductionInfo Info(SourceLocation{}, TPL->getDepth()); + // FIXME: We can't deal very well with non-canonical template + // arguments so this will fail sometimes. + Sema::TemplateDeductionResult Res = R->SemaRef.DeduceTemplateArguments( + CTPSD, + TemplateArgumentList(TemplateArgumentList::OnStackType{}, Args), Info, + /*DontCaninicalize=*/true); + if (Res != Sema::TDK_Success) + return; + insertTemplateToMap(Reverse, CTSD, Info.take()->asArray()); + } + + void addTypeToMap(bool Reverse, const Type *T) { + struct { + NamedDecl *ND; + const TemplateSpecializationType *TS; + } Entity; + { + QualType TCanon = T->getCanonicalTypeInternal(); + switch (TCanon->getTypeClass()) { + case Type::Record: { + const auto *TS = T->getAs(); + while (TS && TS->isTypeAlias()) + TS = TS->getAliasedType()->getAs(); + Entity = {T->getAsRecordDecl(), TS}; + break; + } + case Type::InjectedClassName: { + const auto *ICN = cast(TCanon); + Entity = {ICN->getDecl(), ICN->getInjectedTST()}; + break; + } + case Type::TemplateSpecialization: + case Type::DependentTemplateSpecialization: + case Type::TemplateTypeParm: + case Type::DependentName: + case Type::Enum: + case Type::Builtin: + return; + default: + TCanon.dump(); + llvm_unreachable(""); + } + } + switch (auto NDK = Entity.ND->getKind()) { + case Decl::CXXRecord: + case Decl::Record: + return; + case Decl::ClassTemplateSpecialization: + case Decl::ClassTemplatePartialSpecialization: { + if (!Entity.TS) + return; + assert(!Entity.TS->isTypeAlias()); + ArrayRef Args = Entity.TS->template_arguments(); + auto *CTSD = cast(Entity.ND); + + if (NDK == Decl::ClassTemplatePartialSpecialization) + return deduceClassTemplatePartialSpecialization( + cast(Entity.ND), Reverse, + Args, CTSD); + + TemplateArgumentListInfo ArgsInfo; + for (auto &&I : Args) + ArgsInfo.addArgument(R->SemaRef.getTrivialTemplateArgumentLoc( + I, /*NTTPType=*/QualType(), SourceLocation())); + + ClassTemplateDecl *TD = CTSD->getSpecializedTemplate(); + SmallVector ConvertedArgs; + // FIXME: Get rid of these conversions. + if (R->SemaRef.CheckTemplateArgumentList( + TD, SourceLocation(), ArgsInfo, false, ConvertedArgs, + /*UpdateArgsWithConversions=*/false, + /*ConstrantsNotSatisfied=*/nullptr, + /*DontCanonicalize=*/true)) + return; + if (auto *CTPSD = + CTSD->getSpecializedTemplateOrPartial() + .dyn_cast()) + return deduceClassTemplatePartialSpecialization(CTPSD, Reverse, + ConvertedArgs, CTSD); + return insertTemplateToMap( + Reverse, CTSD, R->ArgsBuf.emplace_back(std::move(ConvertedArgs))); + } + default: + break; + } + Entity.ND->dumpColor(); + llvm_unreachable("Unhandled Decl Kind"); + } + + Resugarer *R; + TemplateToArgs OldTemplateToArgs; + + private: + size_t OldArgsBufSize; + }; + + struct NamingContextRAII : NamingContextBase { + NamingContextRAII(Resugarer &R, const NestedNameSpecifier *NNS, + const Type *BaseType = nullptr) + : NamingContextBase(R) { + if (BaseType) { + assert(!BaseType->getAs()); + addTypeToMap(/*Reverse=*/false, BaseType); + } + for (/**/; NNS; NNS = NNS->getPrefix()) { + switch (NNS->getKind()) { + case NestedNameSpecifier::Global: + case NestedNameSpecifier::Namespace: + case NestedNameSpecifier::NamespaceAlias: + return; + case NestedNameSpecifier::Identifier: + case NestedNameSpecifier::Super: + continue; + case NestedNameSpecifier::TypeSpec: + case NestedNameSpecifier::TypeSpecWithTemplate: + addTypeToMap(/*Reverse=*/false, NNS->getAsType()); + continue; + } + llvm_unreachable("Unknown NestedNameSpecifier Kind"); + } + for (auto &&I : OldTemplateToArgs) { + auto &P = R.CurTemplateToArgs[I.first]; + if (P.empty()) + P = I.second; + } + } + }; + + struct NamingContextTransformRAII : NamingContextBase { + NamingContextTransformRAII(Resugarer &R, NestedNameSpecifierLoc &NNS) + : NamingContextBase(R) { + SmallVector Qs; + bool InheritOldMap = true; + for (/**/; NNS; NNS = NNS.getPrefix()) { + NestedNameSpecifier::SpecifierKind K = + NNS.getNestedNameSpecifier()->getKind(); + InheritOldMap &= K != NestedNameSpecifier::Global && + K != NestedNameSpecifier::Namespace && + K != NestedNameSpecifier::NamespaceAlias; + Qs.push_back(NNS); + } + if (InheritOldMap) + R.CurTemplateToArgs.copyFrom(OldTemplateToArgs); + + CXXScopeSpec SS; + for (const NestedNameSpecifierLoc &Q : llvm::reverse(Qs)) { + const auto *Qnns = Q.getNestedNameSpecifier(); + switch (Qnns->getKind()) { + case NestedNameSpecifier::Global: + SS.MakeGlobal(R.SemaRef.Context, Q.getBeginLoc()); + continue; + case NestedNameSpecifier::Namespace: + SS.Extend(R.SemaRef.Context, Qnns->getAsNamespace(), + Q.getLocalBeginLoc(), Q.getLocalEndLoc()); + continue; + case NestedNameSpecifier::NamespaceAlias: + SS.Extend(R.SemaRef.Context, Qnns->getAsNamespaceAlias(), + Q.getLocalBeginLoc(), Q.getLocalEndLoc()); + continue; + case NestedNameSpecifier::Identifier: + SS.Extend(R.SemaRef.Context, Qnns->getAsIdentifier(), + Q.getLocalBeginLoc(), Q.getLocalEndLoc()); + continue; + case NestedNameSpecifier::Super: + SS.MakeSuper(R.SemaRef.Context, Qnns->getAsRecordDecl(), + Q.getBeginLoc(), Q.getEndLoc()); + continue; + case NestedNameSpecifier::TypeSpec: + case NestedNameSpecifier::TypeSpecWithTemplate: { + TypeLocBuilder TLB; + TypeLoc TL = Q.getTypeLoc(); + TLB.reserve(TL.getFullDataSize()); + QualType T = R.TransformType(TLB, TL); + addTypeToMap(/*Reverse=*/true, T.getTypePtr()); + SS.Extend(R.SemaRef.Context, /*FIXME:*/ SourceLocation(), + TLB.getTypeSourceInfo(R.SemaRef.Context, T)->getTypeLoc(), + Q.getLocalEndLoc()); + continue; + } + } + llvm_unreachable("Unknown NestedNameSpecifier Kind"); + } + if (SS.getScopeRep() == NNS.getNestedNameSpecifier()) + return; + if (llvm::equal( + ArrayRef(SS.location_data(), SS.location_size()), + ArrayRef((char *)NNS.getOpaqueData(), NNS.getDataLength()))) + NNS = NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData()); + else + NNS = SS.getWithLocInContext(R.SemaRef.Context); + } + }; + + Resugarer(Sema &SemaRef) : inherited(SemaRef) {} + + bool AlwaysRebuild() { return false; } + bool ReplacingOriginal() { return false; } + + QualType TransformQualifiedType(TypeLocBuilder &TLB, QualifiedTypeLoc TL) { + QualType NewUnqual = TransformType(TLB, TL.getUnqualifiedLoc()); + QualType Result = TL.getType(); + if (NewUnqual != TL.getUnqualifiedLoc().getType()) + Result = SemaRef.Context.getQualifiedType( + NewUnqual, TL.getType().getLocalQualifiers()); + TLB.TypeWasModifiedSafely(Result); + return Result; + } + + QualType TransformAdjustedType(TypeLocBuilder &TLB, AdjustedTypeLoc TL) { + const AdjustedType *T = TL.getTypePtr(); + QualType NewOrig = TransformType(TLB, TL.getOriginalLoc()); + + QualType Result = TL.getType(); + if (NewOrig != T->getOriginalType()) + Result = SemaRef.Context.getAdjustedType(NewOrig, T->getAdjustedType()); + TLB.push(Result); + return Result; + } + + QualType TransformElaboratedType(TypeLocBuilder &TLB, ElaboratedTypeLoc TL) { + NestedNameSpecifierLoc QualifierLoc = TL.getQualifierLoc(); + NamingContextTransformRAII NamingScope(*this, QualifierLoc); + QualType NamedT = TransformType(TLB, TL.getNamedTypeLoc()); + + const ElaboratedType *T = TL.getTypePtr(); + QualType Result = TL.getType(); + if (QualifierLoc != TL.getQualifierLoc() || NamedT != T->getNamedType()) + Result = SemaRef.Context.getElaboratedType( + T->getKeyword(), QualifierLoc.getNestedNameSpecifier(), NamedT); + + auto NewTL = TLB.push(Result); + NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc()); + NewTL.setQualifierLoc(QualifierLoc); + return Result; + } + + Decl *TransformDecl(SourceLocation Loc, Decl *D) const { return D; } + + QualType TransformSubstTemplateTypeParmType(TypeLocBuilder &TLB, + SubstTemplateTypeParmTypeLoc TL) { + QualType QT = TL.getType(); + const SubstTemplateTypeParmType *T = TL.getTypePtr(); + Decl *ReplacedDecl = T->getReplacedDecl(); + + Optional PackIndex = T->getPackIndex(); + if (const TemplateArgument *Arg = + getArgument(ReplacedDecl, T->getIndex(), PackIndex)) { + QualType Replacement = Arg->getAsType().getNonPackExpansionType(); + if (!SemaRef.Context.hasSameType(Replacement, T->getReplacementType())) { + Replacement.dump(); + T->getReplacementType().dump(); + assert(false); + } + if (Replacement != T->getReplacementType()) + QT = SemaRef.Context.getSubstTemplateTypeParmType( + Replacement, ReplacedDecl, T->getIndex(), PackIndex); + } + auto NewTL = TLB.push(QT); + NewTL.setNameLoc(TL.getNameLoc()); + return QT; + } + + using inherited::TransformTemplateSpecializationType; + + QualType + TransformTemplateSpecializationType(TemplateName N, bool IsTypeAlias, + MutableArrayRef Args, + QualType Underlying) { + if (N.getAsSubstTemplateTemplateParm()) { + // FIXME: Resugar default arguments on template template parameters. + // The AST currently cannot represent this. + TransformTemplateArguments(Args); + } else { + TransformTemplateArguments(Args); + } + if (IsTypeAlias) { + SemanticContextRAII SemanticScope(*this, N.getAsTemplateDecl(), Args); + Underlying = TransformType(Underlying); + } + + return SemaRef.Context.getTemplateSpecializationType(N, Args, Underlying); + } + + QualType TransformTemplateSpecializationType(TypeLocBuilder &TLB, + TemplateSpecializationTypeLoc TL, + TemplateName N) { + const TemplateSpecializationType *T = TL.getTypePtr(); + + SmallVector Args(TL.getNumArgs()); + for (unsigned I = 0, E = TL.getNumArgs(); I < E; ++I) + Args[I] = TL.getArgLoc(I); + + QualType Result = TransformTemplateSpecializationType(N, T->isTypeAlias(), + Args, T->desugar()); + + auto NewTL = TLB.push(Result); + NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc()); + NewTL.setTemplateNameLoc(TL.getTemplateNameLoc()); + NewTL.setLAngleLoc(TL.getLAngleLoc()); + NewTL.setRAngleLoc(TL.getRAngleLoc()); + for (unsigned I = 0, E = Args.size(); I < E; ++I) + NewTL.setArgLocInfo(I, Args[I].getLocInfo()); + return Result; + } + + QualType TransformDependentTemplateSpecializationType( + TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL) { + const DependentTemplateSpecializationType *T = TL.getTypePtr(); + + SmallVector Args(TL.getNumArgs()); + for (unsigned I = 0, E = TL.getNumArgs(); I < E; ++I) + Args[I] = TL.getArgLoc(I); + + NestedNameSpecifierLoc NNS = TL.getQualifierLoc(); + NamingContextTransformRAII NamingScope(*this, NNS); + TransformTemplateArguments(Args); + // FIXME: Don't rebuild if nothing changed. + QualType Result = SemaRef.Context.getDependentTemplateSpecializationType( + T->getKeyword(), NNS.getNestedNameSpecifier(), T->getIdentifier(), + Args); + + auto NewTL = TLB.push(Result); + NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc()); + NewTL.setQualifierLoc(NNS); + NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc()); + NewTL.setTemplateNameLoc(TL.getTemplateNameLoc()); + NewTL.setLAngleLoc(TL.getLAngleLoc()); + NewTL.setRAngleLoc(TL.getRAngleLoc()); + for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) + NewTL.setArgLocInfo(I, Args[I].getLocInfo()); + return Result; + } + + TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType, NamedDecl *, + CXXScopeSpec &) = delete; + + QualType TransformDependentTemplateSpecializationType( + TypeLocBuilder &, DependentTemplateSpecializationTypeLoc, TemplateName, + CXXScopeSpec &) = delete; + + TemplateName TransformTemplateName(CXXScopeSpec &SS, TemplateName Name, + SourceLocation NameLoc, + QualType ObjectType = QualType(), + NamedDecl *FirstQualifierInScope = nullptr, + bool AllowInjectedClassName = false) { + if (Name.getKind() == TemplateName::NameKind::SubstTemplateTemplateParm) + return Name; // FIXME: resugar these + return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType, + FirstQualifierInScope, + AllowInjectedClassName); + } + + QualType TransformDependentNameType(TypeLocBuilder &TLB, + DependentNameTypeLoc TL, + bool DeducedTSTContext = false) { + const DependentNameType *T = TL.getTypePtr(); + + NestedNameSpecifierLoc QualifierLoc = TL.getQualifierLoc(); + NamingContextTransformRAII NamingContext(*this, QualifierLoc); + assert(QualifierLoc); + assert(QualifierLoc.getNestedNameSpecifier()->isDependent()); + QualType Result = SemaRef.Context.getDependentNameType( + T->getKeyword(), QualifierLoc.getNestedNameSpecifier(), + T->getIdentifier()); + auto NewTL = TLB.push(Result); + NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc()); + NewTL.setQualifierLoc(QualifierLoc); + NewTL.setNameLoc(TL.getNameLoc()); + return Result; + } + + QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) { + const TypedefType *T = TL.getTypePtr(); + const TypedefNameDecl *D = T->getDecl(); + QualType OldUnderlying = T->desugar(); + NonTemplateSemanticContextRAII SemanticScope(*this); + QualType NewUnderlying = TransformType(OldUnderlying); + QualType Result = TL.getType(); + if (NewUnderlying != OldUnderlying) + Result = SemaRef.Context.getTypedefType(D, NewUnderlying); + auto NewTL = TLB.push(Result); + NewTL.setNameLoc(TL.getNameLoc()); + return Result; + } + + QualType TransformUsingType(TypeLocBuilder &TLB, UsingTypeLoc TL) { + const UsingType *T = TL.getTypePtr(); + const UsingShadowDecl *D = T->getFoundDecl(); + QualType OldUnderlying = T->desugar(); + NonTemplateSemanticContextRAII SemanticScope(*this); + QualType NewUnderlying = TransformType(OldUnderlying); + QualType Result = TL.getType(); + if (NewUnderlying != OldUnderlying) + Result = SemaRef.Context.getUsingType(D, NewUnderlying); + TLB.pushTypeSpec(Result).setNameLoc(TL.getNameLoc()); + return Result; + } + + ExprResult TransformExpr(Expr *E) { return E; } + + bool TransformTemplateArgument(const TemplateArgumentLoc &Input, + TemplateArgumentLoc &Output, bool) = delete; + + bool TransformTemplateArgument(TemplateArgumentLoc &AL) { + const TemplateArgument &Arg = AL.getArgument(); + switch (Arg.getKind()) { + case TemplateArgument::Null: + llvm_unreachable("Unexpected Null TemplateArgument"); + case TemplateArgument::Pack: { + ArrayRef PackArray = Arg.getPackAsArray(); + SmallVector Pack(PackArray.size()); + for (unsigned I = 0; I < PackArray.size(); ++I) + Pack[I] = SemaRef.getTrivialTemplateArgumentLoc( + PackArray[I], QualType(), SourceLocation()); + bool Changed = TransformTemplateArguments(Pack); + SmallVector ROuts(Pack.size()); + for (unsigned I = 0; I < Pack.size(); ++I) + ROuts[I] = Pack[I].getArgument(); + AL = TemplateArgumentLoc( + TemplateArgument::CreatePackCopy(SemaRef.Context, ROuts), + AL.getLocInfo()); + return Changed; + } + case TemplateArgument::Integral: + case TemplateArgument::NullPtr: + case TemplateArgument::Declaration: { + QualType T = Arg.getNonTypeTemplateArgumentType(); + QualType NewT = TransformType(T); + if (NewT == T) + return false; + switch (Arg.getKind()) { + case TemplateArgument::Integral: + AL = TemplateArgumentLoc( + TemplateArgument(SemaRef.Context, Arg.getAsIntegral(), NewT), + AL.getLocInfo()); + return true; + case TemplateArgument::NullPtr: + AL = TemplateArgumentLoc(TemplateArgument(NewT, /*IsNullPtr=*/true), + AL.getLocInfo()); + return true; + default: + AL = TemplateArgumentLoc(TemplateArgument(Arg.getAsDecl(), NewT), + AL.getLocInfo()); + return true; + } + llvm_unreachable(""); + } + case TemplateArgument::Type: { + if (Arg.isPackExpansion()) { + QualType T = TransformType(Arg.getAsType()); + if (T == Arg.getAsType()) + return false; + AL = TemplateArgumentLoc(TemplateArgument(T), AL.getLocInfo()); + return true; + } + TypeSourceInfo *DI = AL.getTypeSourceInfo(); + if (!DI) + DI = InventTypeSourceInfo(Arg.getAsType()); + TypeSourceInfo *NewDI = TransformType(DI); + if (DI == NewDI) + return false; + AL = TemplateArgumentLoc(TemplateArgument(NewDI->getType()), NewDI); + return true; + } + case TemplateArgument::Template: { + NestedNameSpecifierLoc QualifierLoc = AL.getTemplateQualifierLoc(); + NamingContextTransformRAII NamingContext(*this, QualifierLoc); + + CXXScopeSpec SS; + SS.Adopt(QualifierLoc); + TemplateName Template = TransformTemplateName(SS, Arg.getAsTemplate(), + AL.getTemplateNameLoc()); + if (Template.getAsVoidPointer() == Arg.getAsTemplate().getAsVoidPointer()) + return false; + + AL = TemplateArgumentLoc(SemaRef.Context, TemplateArgument(Template), + QualifierLoc, AL.getTemplateNameLoc()); + return true; + } + case TemplateArgument::TemplateExpansion: { + AL = TemplateArgumentLoc( + TemplateArgument(Arg.getAsTemplateOrTemplatePattern(), + Arg.getNumTemplateExpansions()), + AL.getLocInfo()); + return false; + } + case TemplateArgument::Expression: + // FIXME: convert the type of these. + return false; + } + llvm_unreachable("Unexpected TemplateArgument kind"); + } + + template + bool TransformTemplateArguments(InputIterator First, InputIterator Last, + TemplateArgumentListInfo &Outputs, + bool Uneval = true) = delete; + + bool TransformTemplateArguments(MutableArrayRef Args) { + bool Changed = false; + for (auto &Arg : Args) + Changed |= TransformTemplateArgument(Arg); + return Changed; + } + + QualType TransformPackExpansionType(TypeLocBuilder &TLB, + PackExpansionTypeLoc TL) { + QualType Pattern = TransformType(TLB, TL.getPatternLoc()); + assert(!Pattern.isNull()); + + QualType Result = TL.getType(); + if (Pattern != TL.getPatternLoc().getType()) { + Result = SemaRef.Context.getPackExpansionType( + Pattern, TL.getTypePtr()->getNumExpansions(), + /*ExpectPackInType=*/false); + } + + auto NewT = TLB.push(Result); + NewT.setEllipsisLoc(TL.getEllipsisLoc()); + return Result; + } + + bool TransformTypes(llvm::ArrayRef In, + SmallVectorImpl &Out) { + bool Changed = false; + for (unsigned i = 0; i != In.size(); ++i) { + QualType OldType = In[i]; + QualType NewType = TransformType(OldType); + assert(!NewType.isNull()); + Changed |= NewType != OldType; + Out[i] = NewType; + } + return Changed; + } + + QualType TransformFunctionProtoType(TypeLocBuilder &TLB, + FunctionProtoTypeLoc TL) { + const FunctionProtoType *T = TL.getTypePtr(); + + QualType ResultType = TransformType(TLB, TL.getReturnLoc()); + assert(!ResultType.isNull()); + + bool Changed = ResultType != TL.getReturnLoc().getType(); + + SmallVector ParamTypes(T->getNumParams()); + Changed |= TransformTypes(llvm::ArrayRef(T->param_types().begin(), + T->param_types().end()), + ParamTypes); + + FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo(); + + SmallVector ExceptionStorage( + EPI.ExceptionSpec.Exceptions.size()); + Changed |= TransformTypes(EPI.ExceptionSpec.Exceptions, ExceptionStorage); + EPI.ExceptionSpec.Exceptions = ExceptionStorage; + + QualType Result = + Changed ? SemaRef.Context.getFunctionType(ResultType, ParamTypes, EPI) + : TL.getType(); + + auto NewTL = TLB.push(Result); + NewTL.setLocalRangeBegin(TL.getLocalRangeBegin()); + NewTL.setLParenLoc(TL.getLParenLoc()); + NewTL.setRParenLoc(TL.getRParenLoc()); + NewTL.setExceptionSpecRange(TL.getExceptionSpecRange()); + NewTL.setLocalRangeEnd(TL.getLocalRangeEnd()); + for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i) + NewTL.setParam(i, TL.getParam(i)); + return Result; + } + + bool TransformFunctionTypeParams(ArrayRef ParamTypes, + SmallVectorImpl &OutParamTypes) { + for (unsigned i = 0; i != ParamTypes.size(); ++i) { + QualType NewType = TransformType(ParamTypes[i]); + assert(!NewType.isNull()); + OutParamTypes.push_back(NewType); + } + return false; + } + + QualType TransformAttributedType(TypeLocBuilder &TLB, AttributedTypeLoc TL) { + const AttributedType *T = TL.getTypePtr(); + QualType MT = TransformType(TLB, TL.getModifiedLoc()); + assert(!MT.isNull()); + + const Attr *OldAttr = TL.getAttr(); + const Attr *NewAttr = OldAttr ? TransformAttr(OldAttr) : nullptr; + assert(!OldAttr == !NewAttr); + + // FIXME: Rebuild if Attr changes? + QualType Result = TL.getType(); + if (MT != T->getModifiedType()) { + Result = SemaRef.Context.getAttributedType(TL.getAttrKind(), MT, + T->getEquivalentType()); + } + + auto newTL = TLB.push(Result); + newTL.setAttr(NewAttr); + return Result; + } + + QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) { + NestedNameSpecifierLoc NNS; + const AutoType *T = TL.getTypePtr(); + + SmallVector Args(TL.getNumArgs()); + for (unsigned I = 0, E = TL.getNumArgs(); I < E; ++I) + Args[I] = TL.getArgLoc(I); + bool ChangedArgs = TransformTemplateArguments(Args); + + QualType Deduced = !T->getDeducedType().isNull() + ? TransformType(T->getDeducedType()) + : QualType(); + + QualType Result = TL.getType(); + if (Deduced != T->getDeducedType() || ChangedArgs) { + NNS = TL.getNestedNameSpecifierLoc(); + NamingContextTransformRAII NamingContext(*this, NNS); + // FIXME: Maybe don't rebuild if all template arguments are the same. + llvm::SmallVector TypeConstraintArgs(Args.size()); + for (unsigned I = 0; I < Args.size(); ++I) + TypeConstraintArgs[I] = Args[I].getArgument(); + Result = SemaRef.Context.getAutoType( + Deduced, T->getKeyword(), Deduced.isNull(), + T->containsUnexpandedParameterPack(), T->getTypeConstraintConcept(), + TypeConstraintArgs); + } + + auto NewTL = TLB.push(Result); + NewTL.setNameLoc(TL.getNameLoc()); + NewTL.setNestedNameSpecifierLoc(NNS); + NewTL.setTemplateKWLoc(TL.getTemplateKWLoc()); + NewTL.setConceptNameLoc(TL.getConceptNameLoc()); + NewTL.setFoundDecl(TL.getFoundDecl()); + NewTL.setLAngleLoc(TL.getLAngleLoc()); + NewTL.setRAngleLoc(TL.getRAngleLoc()); + NewTL.setRParenLoc(TL.getRParenLoc()); + for (unsigned I = 0; I < NewTL.getNumArgs(); ++I) + NewTL.setArgLocInfo(I, Args[I].getLocInfo()); + return Result; + } + + QualType TransformConstantArrayType(TypeLocBuilder &TLB, + ConstantArrayTypeLoc TL) { + const ConstantArrayType *T = TL.getTypePtr(); + QualType ElementType = TransformType(TLB, TL.getElementLoc()); + assert(!ElementType.isNull()); + + // Prefer the expression from the TypeLoc; the other may have been uniqued. + Expr *OldSize = TL.getSizeExpr(); + if (!OldSize) + OldSize = const_cast(T->getSizeExpr()); + Expr *NewSize = nullptr; + if (OldSize) { + NewSize = TransformExpr(OldSize).template getAs(); + } + + QualType Result = TL.getType(); + if (ElementType != T->getElementType() || + (T->getSizeExpr() && NewSize != OldSize)) { + Result = SemaRef.Context.getConstantArrayType( + ElementType, T->getSize(), NewSize, T->getSizeModifier(), + T->getIndexTypeCVRQualifiers()); + } + + auto NewTL = TLB.push(Result); + NewTL.setLBracketLoc(TL.getLBracketLoc()); + NewTL.setRBracketLoc(TL.getRBracketLoc()); + NewTL.setSizeExpr(NewSize); + return Result; + } + + QualType TransformIncompleteArrayType(TypeLocBuilder &TLB, + IncompleteArrayTypeLoc TL) { + const IncompleteArrayType *T = TL.getTypePtr(); + QualType ElementType = TransformType(TLB, TL.getElementLoc()); + assert(!ElementType.isNull()); + + QualType Result = TL.getType(); + if (ElementType != T->getElementType()) { + Result = SemaRef.Context.getIncompleteArrayType( + ElementType, T->getSizeModifier(), T->getIndexTypeCVRQualifiers()); + } + + auto NewTL = TLB.push(Result); + NewTL.setLBracketLoc(TL.getLBracketLoc()); + NewTL.setRBracketLoc(TL.getRBracketLoc()); + NewTL.setSizeExpr(nullptr); + return Result; + } + + QualType TransformVariableArrayType(TypeLocBuilder &TLB, + VariableArrayTypeLoc TL) { + const VariableArrayType *T = TL.getTypePtr(); + QualType ElementType = TransformType(TLB, TL.getElementLoc()); + assert(!ElementType.isNull()); + + Expr *NewSize = TransformExpr(T->getSizeExpr()).template getAs(); + + QualType Result = TL.getType(); + if (ElementType != T->getElementType() || NewSize != T->getSizeExpr()) { + Result = SemaRef.Context.getVariableArrayType( + ElementType, NewSize, T->getSizeModifier(), + T->getIndexTypeCVRQualifiers(), TL.getBracketsRange()); + } + + auto NewTL = TLB.push(Result); + NewTL.setLBracketLoc(TL.getLBracketLoc()); + NewTL.setRBracketLoc(TL.getRBracketLoc()); + NewTL.setSizeExpr(NewSize); + return Result; + } + + QualType TransformDependentSizedArrayType(TypeLocBuilder &TLB, + DependentSizedArrayTypeLoc TL) { + const DependentSizedArrayType *T = TL.getTypePtr(); + QualType ElementType = TransformType(TLB, TL.getElementLoc()); + assert(!ElementType.isNull()); + + // Prefer the expression from the TypeLoc; the other may have been uniqued. + Expr *OldSize = TL.getSizeExpr(); + if (!OldSize) + OldSize = const_cast(T->getSizeExpr()); + Expr *NewSize = nullptr; + if (OldSize) { + NewSize = TransformExpr(OldSize).template getAs(); + } + + QualType Result = TL.getType(); + if (ElementType != T->getElementType() || NewSize != OldSize) { + Result = SemaRef.Context.getDependentSizedArrayType( + ElementType, NewSize, T->getSizeModifier(), + T->getIndexTypeCVRQualifiers(), TL.getBracketsRange()); + } + + auto NewTL = TLB.push(Result); + NewTL.setLBracketLoc(TL.getLBracketLoc()); + NewTL.setRBracketLoc(TL.getRBracketLoc()); + NewTL.setSizeExpr(NewSize); + return Result; + } + + QualType TransformBTFTagAttributedType(TypeLocBuilder &TLB, + BTFTagAttributedTypeLoc TL) { + // The BTFTagAttributedType is available for C only. + const BTFTagAttributedType *T = TL.getTypePtr(); + + QualType NewWrappedType = TransformType(TLB, TL.getWrappedLoc()); + assert(!NewWrappedType.isNull()); + + const Attr *NewAttr = TransformAttr(T->getAttr()); + + QualType Result = TL.getType(); + if (NewWrappedType != T->getWrappedType() || NewAttr != T->getAttr()) { + Result = + SemaRef.Context.getBTFTagAttributedType(T->getAttr(), NewWrappedType); + } + TLB.push(Result); + return Result; + } + + QualType TransformDependentAddressSpaceType(TypeLocBuilder &TLB, + DependentAddressSpaceTypeLoc TL) { + const DependentAddressSpaceType *T = TL.getTypePtr(); + + QualType pointeeType = TransformType(TLB, TL.getPointeeTypeLoc()); + assert(!pointeeType.isNull()); + + Expr *AddrSpace = + TransformExpr(T->getAddrSpaceExpr()).template getAs(); + + QualType Result = TL.getType(); + if (pointeeType != T->getPointeeType() || + AddrSpace != T->getAddrSpaceExpr()) { + Result = SemaRef.Context.getDependentAddressSpaceType( + pointeeType, AddrSpace, T->getAttributeLoc()); + } + + auto NewTL = TLB.push(Result); + NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange()); + NewTL.setAttrExprOperand(AddrSpace); + NewTL.setAttrNameLoc(TL.getAttrNameLoc()); + return Result; + } + + QualType TransformDeducedTemplateSpecializationType( + TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) { + const DeducedTemplateSpecializationType *T = TL.getTypePtr(); + + CXXScopeSpec SS; + TemplateName Template = TransformTemplateName(SS, T->getTemplateName(), + TL.getTemplateNameLoc()); + assert(!Template.isNull()); + + QualType NewDeduced; + if (!T->getDeducedType().isNull()) { + NewDeduced = TransformType(T->getDeducedType()); + assert(!NewDeduced.isNull()); + } + + QualType Result = TL.getType(); + if (Template.getAsVoidPointer() != + T->getTemplateName().getAsVoidPointer() || + NewDeduced != T->getDeducedType()) + Result = SemaRef.Context.getDeducedTemplateSpecializationType( + Template, NewDeduced, T->isDependentType()); + + auto NewTL = TLB.push(Result); + NewTL.setTemplateNameLoc(TL.getTemplateNameLoc()); + return Result; + } + + QualType TransformTypeOfExprType(TypeLocBuilder &TLB, TypeOfExprTypeLoc TL) { + ExprResult E = TransformExpr(TL.getUnderlyingExpr()); + // FIXME: resugar + QualType Result = TL.getType(); + if (E.get() != TL.getUnderlyingExpr()) { + Result = SemaRef.BuildTypeofExprType(E.get()); + } + TypeOfExprTypeLoc NewTL = TLB.push(Result); + NewTL.setTypeofLoc(TL.getTypeofLoc()); + NewTL.setLParenLoc(TL.getLParenLoc()); + NewTL.setRParenLoc(TL.getRParenLoc()); + return Result; + } + + QualType TransformTypeOfType(TypeLocBuilder &TLB, TypeOfTypeLoc TL) { + TypeSourceInfo *Old = TL.getUnderlyingTInfo(); + TypeSourceInfo *New = TransformType(Old); + + QualType Result = TL.getType(); + if (New != Old) + Result = SemaRef.Context.getTypeOfType(New->getType()); + + TypeOfTypeLoc NewTL = TLB.push(Result); + NewTL.setTypeofLoc(TL.getTypeofLoc()); + NewTL.setLParenLoc(TL.getLParenLoc()); + NewTL.setRParenLoc(TL.getRParenLoc()); + NewTL.setUnderlyingTInfo(New); + return Result; + } + + QualType TransformDecltypeType(TypeLocBuilder &TLB, DecltypeTypeLoc TL) { + const DecltypeType *T = TL.getTypePtr(); + QualType NewT = TransformType(T->getUnderlyingType()); + QualType Result = TL.getType(); + if (NewT != T->getUnderlyingType()) + Result = SemaRef.Context.getDecltypeType(T->getUnderlyingExpr(), NewT); + + DecltypeTypeLoc NewTL = TLB.push(Result); + NewTL.setDecltypeLoc(TL.getDecltypeLoc()); + NewTL.setRParenLoc(TL.getRParenLoc()); + return Result; + } + + QualType TransformUnaryTransformType(TypeLocBuilder &TLB, + UnaryTransformTypeLoc TL) { + QualType Result = TL.getType(); + if (Result->isDependentType()) { + TypeSourceInfo *NewBase = TransformType(TL.getUnderlyingTInfo()); + if (NewBase->getType() != TL.getUnderlyingTInfo()->getType()) + Result = SemaRef.BuildUnaryTransformType( + NewBase->getType(), TL.getTypePtr()->getUTTKind(), TL.getKWLoc()); + } + UnaryTransformTypeLoc NewTL = TLB.push(Result); + NewTL.setKWLoc(TL.getKWLoc()); + NewTL.setParensRange(TL.getParensRange()); + NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo()); + return Result; + } + // FIXME: missing resugar of enums. +}; +} // namespace + +QualType Sema::resugar(const CXXScopeSpec &SS, QualType T) { + if (!getLangOpts().Resugar) + return T; + Resugarer R(*this); + Resugarer::NamingContextRAII NamingScope(R, SS.getScopeRep()); + return R.TransformType(T); +} + +QualType Sema::resugar(const CXXScopeSpec &SS, NamedDecl *ND, + ArrayRef Args, QualType T, + ResugarArgumentKind ArgumentKind) { + assert(ND != nullptr); + if (!getLangOpts().Resugar) + return T; + Resugarer R(*this); + Resugarer::NamingContextRAII NamingScope(R, SS.getScopeRep()); + Resugarer::SemanticContextRAII SemanticScope( + R, ND, Args, ArgumentKind == ResugarArgumentKind::AsWritten); + return R.TransformType(T); +} + +static const NestedNameSpecifier *decomposeBaseType(const Type *&Base) { + if (const auto *ElTy = Base->getAs()) { + Base = ElTy->getNamedType().getTypePtr(); + return ElTy->getQualifier(); + } + return nullptr; +} + +QualType Sema::resugar(const Type *Base, QualType T) { + if (!getLangOpts().Resugar) + return T; + Resugarer R(*this); + const NestedNameSpecifier *BaseNNS = decomposeBaseType(Base); + Resugarer::NamingContextRAII BaseScope(R, BaseNNS, Base); + return R.TransformType(T); +} + +QualType Sema::resugar(const Type *Base, NamedDecl *ND, + ArrayRef Args, QualType T, + ResugarArgumentKind ArgumentKind) { + if (!getLangOpts().Resugar) + return T; + Resugarer R(*this); + const NestedNameSpecifier *BaseNNS = decomposeBaseType(Base); + Resugarer::NamingContextRAII BaseScope(R, BaseNNS, Base); + Resugarer::SemanticContextRAII SemanticScope( + R, ND, Args, ArgumentKind == ResugarArgumentKind::AsWritten); + return R.TransformType(T); +} + +QualType Sema::resugar(const Type *Base, NestedNameSpecifierLoc &FieldNNS, + QualType T) { + if (!getLangOpts().Resugar) + return T; + Resugarer R(*this); + const NestedNameSpecifier *BaseNNS = decomposeBaseType(Base); + Resugarer::NamingContextRAII BaseScope(R, BaseNNS, Base); + Resugarer::NamingContextTransformRAII FieldScope(R, FieldNNS); + return R.TransformType(T); +} + +QualType Sema::resugar(const Type *Base, NestedNameSpecifierLoc &FieldNNS, + NamedDecl *ND, ArrayRef Args, + QualType T, ResugarArgumentKind ArgumentKind) { + if (!getLangOpts().Resugar) + return T; + Resugarer R(*this); + const NestedNameSpecifier *BaseNNS = decomposeBaseType(Base); + Resugarer::NamingContextRAII BaseScope(R, BaseNNS, Base); + Resugarer::NamingContextTransformRAII FieldScope(R, FieldNNS); + Resugarer::SemanticContextRAII SemanticScope( + R, ND, Args, ArgumentKind == ResugarArgumentKind::AsWritten); + return R.TransformType(T); +} + +static QualType getResugaredTemplateSpecializationType( + Sema &S, const CXXScopeSpec &SS, TemplateName Template, + MutableArrayRef Args, + QualType Underlying = QualType()) { + if (!S.getLangOpts().Resugar) + return S.Context.getTemplateSpecializationType(Template, Args, Underlying); + Resugarer R(S); + Resugarer::NamingContextRAII NamingScope(R, SS.getScopeRep()); + const auto *TD = Template.getAsTemplateDecl(); + bool IsTypeAlias = !Underlying.isNull() && TD && TD->isTypeAlias(); + return R.TransformTemplateSpecializationType(Template, IsTypeAlias, Args, + Underlying); +} + /// \brief Determine whether the declaration found is acceptable as the name /// of a template and, if so, return that template declaration. Otherwise, /// returns null. @@ -1592,7 +2791,8 @@ TemplateArgument Converted; ExprResult DefaultRes = - CheckTemplateArgument(Param, Param->getType(), Default, Converted); + CheckTemplateArgument(Param, Param->getType(), Default, Converted, + CTAK_Specified, /*DontCanonicalize=*/false); if (DefaultRes.isInvalid()) { Param->setInvalidDecl(); return Param; @@ -3494,7 +4694,8 @@ } static QualType -checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD, +checkBuiltinTemplateIdType(Sema &SemaRef, const CXXScopeSpec &SS, + TemplateName Name, BuiltinTemplateDecl *BTD, const SmallVectorImpl &Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs) { @@ -3526,7 +4727,13 @@ TemplateArgumentListInfo SyntheticTemplateArgs; // The type argument gets reused as the first template argument in the // synthetic template argument list. - SyntheticTemplateArgs.addArgument(TemplateArgs[1]); + QualType OrigType = TemplateArgs[1].getArgument().getAsType(); + QualType SyntheticType = + SemaRef.Context.getSubstTemplateTypeParmType(OrigType, BTD, 1, None); + SyntheticTemplateArgs.addArgument( + TemplateArgumentLoc(TemplateArgument(SyntheticType), + SemaRef.Context.getTrivialTypeSourceInfo( + SyntheticType, TemplateArgs[1].getLocation()))); // Expand N into 0 ... N-1. for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned()); I < NumArgs; ++I) { @@ -3536,8 +4743,10 @@ } // The first template argument will be reused as the template decl that // our synthetic template arguments will be applied to. - return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(), - TemplateLoc, SyntheticTemplateArgs); + QualType Result = SemaRef.CheckTemplateIdType( + SS, Converted[0].getAsTemplate(), TemplateLoc, SyntheticTemplateArgs); + return SemaRef.Context.getTemplateSpecializationType( + Name, TemplateArgs.arguments(), Result); } case BTK__type_pack_element: @@ -3559,8 +4768,10 @@ } // We simply return the type at index `Index`. + // FIXME: test this auto Nth = std::next(Ts.pack_begin(), Index.getExtValue()); - return Nth->getAsType(); + return getResugaredTemplateSpecializationType( + SemaRef, SS, Name, TemplateArgs.arguments(), Nth->getAsType()); } llvm_unreachable("unexpected BuiltinTemplateDecl!"); } @@ -3704,7 +4915,8 @@ return { FailedCond, Description }; } -QualType Sema::CheckTemplateIdType(TemplateName Name, +// FIXME: We should get the context we are in from the TemplateDeclInstantiator. +QualType Sema::CheckTemplateIdType(const CXXScopeSpec &SS, TemplateName Name, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs) { DependentTemplateName *DTN @@ -3714,10 +4926,9 @@ // assume the template is a type template. Either our assumption is // correct, or the code is ill-formed and will be diagnosed when the // dependent name is substituted. - return Context.getDependentTemplateSpecializationType(ETK_None, - DTN->getQualifier(), - DTN->getIdentifier(), - TemplateArgs); + return Context.getDependentTemplateSpecializationType( + ETK_None, DTN->getQualifier(), DTN->getIdentifier(), + TemplateArgs.arguments()); if (Name.getAsAssumedTemplateName() && resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc)) @@ -3729,7 +4940,8 @@ // We might have a substituted template template parameter pack. If so, // build a template specialization type for it. if (Name.getAsSubstTemplateTemplateParmPack()) - return Context.getTemplateSpecializationType(Name, TemplateArgs); + return getResugaredTemplateSpecializationType(*this, SS, Name, + TemplateArgs.arguments()); Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name; @@ -3760,7 +4972,8 @@ // Only substitute for the innermost template argument list. MultiLevelTemplateArgumentList TemplateArgLists; - TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs); + TemplateArgLists.addOuterTemplateArguments(Template, + StackTemplateArgs.asArray()); TemplateArgLists.addOuterRetainedLevels( AliasTemplate->getTemplateParameters()->getDepth()); @@ -3882,7 +5095,7 @@ InstantiatingTemplate Inst(*this, TemplateLoc, Decl); if (!Inst.isInvalid()) { MultiLevelTemplateArgumentList TemplateArgLists; - TemplateArgLists.addOuterTemplateArguments(Converted); + TemplateArgLists.addOuterTemplateArguments(Template, Converted); InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(), Decl); } @@ -3895,14 +5108,15 @@ assert(isa(CanonType) && "type of non-dependent specialization is not a RecordType"); } else if (auto *BTD = dyn_cast(Template)) { - CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc, - TemplateArgs); + return checkBuiltinTemplateIdType(*this, SS, Name, BTD, Converted, + TemplateLoc, TemplateArgs); } // Build the fully-sugared type for this class template // specialization, which refers back to the class template // specialization we created or found. - return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType); + return getResugaredTemplateSpecializationType( + *this, SS, Name, TemplateArgs.arguments(), CanonType); } void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName, @@ -4013,11 +5227,10 @@ translateTemplateArguments(TemplateArgsIn, TemplateArgs); if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { - QualType T - = Context.getDependentTemplateSpecializationType(ETK_None, - DTN->getQualifier(), - DTN->getIdentifier(), - TemplateArgs); + assert(SS.getScopeRep() == DTN->getQualifier()); + QualType T = Context.getDependentTemplateSpecializationType( + ETK_None, DTN->getQualifier(), DTN->getIdentifier(), + TemplateArgs.arguments()); // Build type-source information. TypeLocBuilder TLB; DependentTemplateSpecializationTypeLoc SpecTL @@ -4033,7 +5246,8 @@ return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); } - QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs); + QualType SpecTy = + CheckTemplateIdType(SS, Template, TemplateIILoc, TemplateArgs); if (SpecTy.isNull()) return true; @@ -4083,10 +5297,10 @@ = TypeWithKeyword::getKeywordForTagTypeKind(TagKind); if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { - QualType T = Context.getDependentTemplateSpecializationType(Keyword, - DTN->getQualifier(), - DTN->getIdentifier(), - TemplateArgs); + assert(SS.getScopeRep() == DTN->getQualifier()); + QualType T = Context.getDependentTemplateSpecializationType( + Keyword, DTN->getQualifier(), DTN->getIdentifier(), + TemplateArgs.arguments()); // Build type-source information. TypeLocBuilder TLB; @@ -4114,30 +5328,14 @@ Diag(TAT->getLocation(), diag::note_declared_at); } - QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); - if (Result.isNull()) + QualType T = CheckTemplateIdType(SS, Template, TemplateLoc, TemplateArgs); + if (T.isNull()) return TypeResult(true); - // Check the tag kind - if (const RecordType *RT = Result->getAs()) { - RecordDecl *D = RT->getDecl(); - - IdentifierInfo *Id = D->getIdentifier(); - assert(Id && "templated class must have an identifier"); - - if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition, - TagLoc, Id)) { - Diag(TagLoc, diag::err_use_with_wrong_tag) - << Result - << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName()); - Diag(D->getLocation(), diag::note_previous_use); - } - } - // Provide source-location information for the template specialization. TypeLocBuilder TLB; - TemplateSpecializationTypeLoc SpecTL - = TLB.push(Result); + TemplateSpecializationTypeLoc SpecTL = + TLB.push(T); SpecTL.setTemplateKeywordLoc(TemplateKWLoc); SpecTL.setTemplateNameLoc(TemplateLoc); SpecTL.setLAngleLoc(LAngleLoc); @@ -4147,11 +5345,29 @@ // Construct an elaborated type containing the nested-name-specifier (if any) // and tag keyword. - Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result); - ElaboratedTypeLoc ElabTL = TLB.push(Result); + T = Context.getElaboratedType(Keyword, SS.getScopeRep(), T); + ElaboratedTypeLoc ElabTL = TLB.push(T); ElabTL.setElaboratedKeywordLoc(TagLoc); ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); - return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); + + // Check the tag kind + if (const RecordType *RT = T->getAs()) { + RecordDecl *D = RT->getDecl(); + + IdentifierInfo *Id = D->getIdentifier(); + assert(Id && "templated class must have an identifier"); + + if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition, TagLoc, + Id)) { + Diag(TagLoc, diag::err_use_with_wrong_tag) + << T + << FixItHint::CreateReplacement(SourceRange(TagLoc), + D->getKindName()); + Diag(D->getLocation(), diag::note_previous_use); + } + } + + return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); } static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, @@ -5003,9 +6219,9 @@ return TNK_Non_template; } -bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, - TemplateArgumentLoc &AL, - SmallVectorImpl &Converted) { +bool Sema::CheckTemplateTypeArgument( + TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL, + SmallVectorImpl &Converted, bool DontCanonicalize) { const TemplateArgument &Arg = AL.getArgument(); QualType ArgType; TypeSourceInfo *TSI = nullptr; @@ -5099,7 +6315,8 @@ return true; // Add the converted template type argument. - ArgType = Context.getCanonicalType(ArgType); + if (!DontCanonicalize) + ArgType = Context.getCanonicalType(ArgType); // Objective-C ARC: // If an explicitly-specified template argument type is a lifetime type @@ -5158,8 +6375,8 @@ TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted); // Only substitute for the innermost template argument list. - MultiLevelTemplateArgumentList TemplateArgLists; - TemplateArgLists.addOuterTemplateArguments(&TemplateArgs); + MultiLevelTemplateArgumentList TemplateArgLists(Template, + TemplateArgs.asArray()); for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) TemplateArgLists.addOuterTemplateArguments(None); @@ -5214,8 +6431,8 @@ TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted); // Only substitute for the innermost template argument list. - MultiLevelTemplateArgumentList TemplateArgLists; - TemplateArgLists.addOuterTemplateArguments(&TemplateArgs); + MultiLevelTemplateArgumentList TemplateArgLists(Template, + TemplateArgs.asArray()); for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) TemplateArgLists.addOuterTemplateArguments(None); @@ -5267,8 +6484,8 @@ TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted); // Only substitute for the innermost template argument list. - MultiLevelTemplateArgumentList TemplateArgLists; - TemplateArgLists.addOuterTemplateArguments(&TemplateArgs); + MultiLevelTemplateArgumentList TemplateArgLists(Template, + TemplateArgs.asArray()); for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) TemplateArgLists.addOuterTemplateArguments(None); @@ -5418,17 +6635,14 @@ /// explicitly written, deduced, etc. /// /// \returns true on error, false otherwise. -bool Sema::CheckTemplateArgument(NamedDecl *Param, - TemplateArgumentLoc &Arg, - NamedDecl *Template, - SourceLocation TemplateLoc, - SourceLocation RAngleLoc, - unsigned ArgumentPackIndex, - SmallVectorImpl &Converted, - CheckTemplateArgumentKind CTAK) { +bool Sema::CheckTemplateArgument( + NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, + SourceLocation TemplateLoc, SourceLocation RAngleLoc, + unsigned ArgumentPackIndex, SmallVectorImpl &Converted, + CheckTemplateArgumentKind CTAK, bool DontCanonizalize) { // Check template type parameters. if (TemplateTypeParmDecl *TTP = dyn_cast(Param)) - return CheckTemplateTypeArgument(TTP, Arg, Converted); + return CheckTemplateTypeArgument(TTP, Arg, Converted, DontCanonizalize); // Check non-type template parameters. if (NonTypeTemplateParmDecl *NTTP =dyn_cast(Param)) { @@ -5456,15 +6670,15 @@ if (auto *PET = NTTPType->getAs()) { Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, ArgumentPackIndex); - NTTPType = SubstType(PET->getPattern(), - MultiLevelTemplateArgumentList(TemplateArgs), - NTTP->getLocation(), - NTTP->getDeclName()); + NTTPType = SubstType( + PET->getPattern(), + MultiLevelTemplateArgumentList(Template, TemplateArgs.asArray()), + NTTP->getLocation(), NTTP->getDeclName()); } else { - NTTPType = SubstType(NTTPType, - MultiLevelTemplateArgumentList(TemplateArgs), - NTTP->getLocation(), - NTTP->getDeclName()); + NTTPType = SubstType( + NTTPType, + MultiLevelTemplateArgumentList(Template, TemplateArgs.asArray()), + NTTP->getLocation(), NTTP->getDeclName()); } // If that worked, check the non-type template parameter type @@ -5481,11 +6695,16 @@ llvm_unreachable("Should never see a NULL template argument here"); case TemplateArgument::Expression: { + Expr *E = Arg.getArgument().getAsExpr(); + // FIXME: Workaround for double conversion + if (isa(E)) { + Converted.push_back(Arg.getArgument()); + break; + } TemplateArgument Result; unsigned CurSFINAEErrors = NumSFINAEErrors; - ExprResult Res = - CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(), - Result, CTAK); + ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK, + DontCanonizalize); if (Res.isInvalid()) return true; // If the current template argument causes an error, give up now. @@ -5545,7 +6764,8 @@ } TemplateArgument Result; - E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result); + E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result, + CTAK_Specified, DontCanonizalize); if (E.isInvalid()) return true; @@ -5613,8 +6833,9 @@ return true; TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted); - Params = SubstTemplateParams(Params, CurContext, - MultiLevelTemplateArgumentList(TemplateArgs)); + Params = SubstTemplateParams( + Params, CurContext, + MultiLevelTemplateArgumentList(Template, TemplateArgs.asArray())); if (!Params) return true; } @@ -5707,7 +6928,8 @@ TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl &Converted, - bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) { + bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied, + bool DontCanonicalize) { if (ConstraintsNotSatisfied) *ConstraintsNotSatisfied = false; @@ -5765,9 +6987,9 @@ if (ArgIdx < NumArgs) { // Check the template argument we were given. - if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, - TemplateLoc, RAngleLoc, - ArgumentPack.size(), Converted)) + if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc, + RAngleLoc, ArgumentPack.size(), Converted, + CTAK_Specified, DontCanonicalize)) return true; bool PackExpansionIntoNonPack = @@ -5926,8 +7148,8 @@ return true; // Check the default template argument. - if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, - RAngleLoc, 0, Converted)) + if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0, + Converted, CTAK_Specified, DontCanonicalize)) return true; // Core issue 150 (assumed resolution): if this is a template template @@ -6452,12 +7674,9 @@ /// Checks whether the given template argument is the address /// of an object or function according to C++ [temp.arg.nontype]p1. -static bool -CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, - NonTypeTemplateParmDecl *Param, - QualType ParamType, - Expr *ArgIn, - TemplateArgument &Converted) { +static bool CheckTemplateArgumentAddressOfObjectOrFunction( + Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, + TemplateArgument &Converted, bool DontCanonicalize) { bool Invalid = false; Expr *Arg = ArgIn; QualType ArgType = Arg->getType(); @@ -6561,8 +7780,9 @@ Entity)) { case NPV_NullPointer: S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); - Converted = TemplateArgument(S.Context.getCanonicalType(ParamType), - /*isNullPtr=*/true); + Converted = TemplateArgument( + DontCanonicalize ? ParamType : S.Context.getCanonicalType(ParamType), + /*isNullPtr=*/true); return false; case NPV_Error: @@ -6706,19 +7926,18 @@ return true; // Create the template argument. - Converted = TemplateArgument(cast(Entity->getCanonicalDecl()), - S.Context.getCanonicalType(ParamType)); + Converted = TemplateArgument( + cast(DontCanonicalize ? Entity : Entity->getCanonicalDecl()), + DontCanonicalize ? ParamType : S.Context.getCanonicalType(ParamType)); S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false); return false; } /// Checks whether the given template argument is a pointer to /// member constant according to C++ [temp.arg.nontype]p1. -static bool CheckTemplateArgumentPointerToMember(Sema &S, - NonTypeTemplateParmDecl *Param, - QualType ParamType, - Expr *&ResultArg, - TemplateArgument &Converted) { +static bool CheckTemplateArgumentPointerToMember( + Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, + Expr *&ResultArg, TemplateArgument &Converted, bool DontCanonicalize) { bool Invalid = false; Expr *Arg = ResultArg; @@ -6768,8 +7987,10 @@ if (Arg->isTypeDependent() || Arg->isValueDependent()) { Converted = TemplateArgument(Arg); } else { - VD = cast(VD->getCanonicalDecl()); - Converted = TemplateArgument(VD, ParamType); + Converted = TemplateArgument( + cast(DontCanonicalize ? VD : VD->getCanonicalDecl()), + DontCanonicalize ? ParamType + : S.Context.getCanonicalType(ParamType)); } return Invalid; } @@ -6787,8 +8008,9 @@ return true; case NPV_NullPointer: S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); - Converted = TemplateArgument(S.Context.getCanonicalType(ParamType), - /*isNullPtr*/true); + Converted = TemplateArgument( + DontCanonicalize ? ParamType : S.Context.getCanonicalType(ParamType), + /*isNullPtr*/ true); return false; case NPV_NotNullPointer: break; @@ -6827,8 +8049,10 @@ if (Arg->isTypeDependent() || Arg->isValueDependent()) { Converted = TemplateArgument(Arg); } else { - ValueDecl *D = cast(DRE->getDecl()->getCanonicalDecl()); - Converted = TemplateArgument(D, S.Context.getCanonicalType(ParamType)); + ValueDecl *D = DRE->getDecl(); + Converted = TemplateArgument( + DontCanonicalize ? D : cast(D->getCanonicalDecl()), + DontCanonicalize ? ParamType : S.Context.getCanonicalType(ParamType)); } return Invalid; } @@ -6850,7 +8074,8 @@ ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *Arg, TemplateArgument &Converted, - CheckTemplateArgumentKind CTAK) { + CheckTemplateArgumentKind CTAK, + bool DontCanonicalize) { SourceLocation StartLoc = Arg->getBeginLoc(); // If the parameter type somehow involves auto, deduce the type now. @@ -7001,7 +8226,8 @@ Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) { NamedDecl *ND = cast(InnerArg)->getDecl(); if (auto *TPO = dyn_cast(ND)) { - Converted = TemplateArgument(TPO, CanonParamType); + Converted = TemplateArgument(TPO, DontCanonicalize ? ParamType + : CanonParamType); return Arg; } if (isa(ND)) { @@ -7030,14 +8256,17 @@ switch (Value.getKind()) { case APValue::None: assert(ParamType->isNullPtrType()); - Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true); + Converted = TemplateArgument( + DontCanonicalize ? ParamType : CanonParamType, /*isNullPtr*/ true); break; case APValue::Indeterminate: llvm_unreachable("result of constant evaluation should be initialized"); break; case APValue::Int: assert(ParamType->isIntegralOrEnumerationType()); - Converted = TemplateArgument(Context, Value.getInt(), CanonParamType); + Converted = + TemplateArgument(Context, Value.getInt(), + DontCanonicalize ? ParamType : CanonParamType); break; case APValue::MemberPointer: { assert(ParamType->isMemberPointerType()); @@ -7051,9 +8280,10 @@ return ExprError(); } + QualType T = DontCanonicalize ? ParamType : CanonParamType; auto *VD = const_cast(Value.getMemberPointerDecl()); - Converted = VD ? TemplateArgument(VD, CanonParamType) - : TemplateArgument(CanonParamType, /*isNullPtr*/true); + Converted = VD ? TemplateArgument(VD, T) + : TemplateArgument(T, /*isNullPtr=*/true); break; } case APValue::LValue: { @@ -7093,17 +8323,19 @@ "null reference should not be a constant expression"); assert((!VD || !ParamType->isNullPtrType()) && "non-null value of type nullptr_t?"); - Converted = VD ? TemplateArgument(VD, CanonParamType) - : TemplateArgument(CanonParamType, /*isNullPtr*/true); + QualType T = DontCanonicalize ? ParamType : CanonParamType; + Converted = VD ? TemplateArgument(VD, T) + : TemplateArgument(T, /*isNullPtr=*/true); break; } case APValue::Struct: - case APValue::Union: + case APValue::Union: { // Get or create the corresponding template parameter object. - Converted = TemplateArgument( - Context.getTemplateParamObjectDecl(CanonParamType, Value), - CanonParamType); + QualType T = DontCanonicalize ? ParamType : CanonParamType; + Converted = + TemplateArgument(Context.getTemplateParamObjectDecl(T, Value), T); break; + } case APValue::AddrLabelDiff: return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff); case APValue::FixedPoint: @@ -7167,8 +8399,9 @@ ? Context.getIntWidth(IntegerType) : Context.getTypeSize(IntegerType)); - Converted = TemplateArgument(Context, Value, - Context.getCanonicalType(ParamType)); + Converted = TemplateArgument( + Context, Value, + DontCanonicalize ? ParamType : Context.getCanonicalType(ParamType)); return ArgResult; } @@ -7242,9 +8475,13 @@ return Arg; } - QualType IntegerType = Context.getCanonicalType(ParamType); - if (const EnumType *Enum = IntegerType->getAs()) - IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType()); + QualType IntegerType = + DontCanonicalize ? ParamType : Context.getCanonicalType(ParamType); + if (const EnumType *Enum = IntegerType->getAs()) { + IntegerType = Enum->getDecl()->getIntegerType(); + if (!DontCanonicalize) + IntegerType = Context.getCanonicalType(IntegerType); + } if (ParamType->isBooleanType()) { // Value must be zero or one. @@ -7290,10 +8527,10 @@ } } + QualType T = + DontCanonicalize ? ParamType : Context.getCanonicalType(ParamType); Converted = TemplateArgument(Context, Value, - ParamType->isEnumeralType() - ? Context.getCanonicalType(ParamType) - : IntegerType); + ParamType->isEnumeralType() ? T : IntegerType); return Arg; } @@ -7331,22 +8568,22 @@ if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc())) return ExprError(); - Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn); + // FIXME: resugar + Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn, nullptr); ArgType = Arg->getType(); } else return ExprError(); } if (!ParamType->isMemberPointerType()) { - if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, - ParamType, - Arg, Converted)) + if (CheckTemplateArgumentAddressOfObjectOrFunction( + *this, Param, ParamType, Arg, Converted, DontCanonicalize)) return ExprError(); return Arg; } if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg, - Converted)) + Converted, DontCanonicalize)) return ExprError(); return Arg; } @@ -7359,9 +8596,8 @@ assert(ParamType->getPointeeType()->isIncompleteOrObjectType() && "Only object pointers allowed here"); - if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, - ParamType, - Arg, Converted)) + if (CheckTemplateArgumentAddressOfObjectOrFunction( + *this, Param, ParamType, Arg, Converted, DontCanonicalize)) return ExprError(); return Arg; } @@ -7384,15 +8620,15 @@ if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc())) return ExprError(); - Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn); + // FIXME: resugar + Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn, nullptr); ArgType = Arg->getType(); } else return ExprError(); } - if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, - ParamType, - Arg, Converted)) + if (CheckTemplateArgumentAddressOfObjectOrFunction( + *this, Param, ParamType, Arg, Converted, DontCanonicalize)) return ExprError(); return Arg; } @@ -7416,8 +8652,9 @@ case NPV_NullPointer: Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); - Converted = TemplateArgument(Context.getCanonicalType(ParamType), - /*isNullPtr*/true); + Converted = TemplateArgument( + DontCanonicalize ? ParamType : Context.getCanonicalType(ParamType), + /*isNullPtr*/ true); return Arg; } } @@ -7427,7 +8664,7 @@ assert(ParamType->isMemberPointerType() && "Only pointers to members remain"); if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg, - Converted)) + Converted, DontCanonicalize)) return ExprError(); return Arg; } @@ -10479,7 +11716,7 @@ // Strangely, non-type results are not ignored by this lookup, so the // program is ill-formed if it finds an injected-class-name. if (TypenameLoc.isValid()) { - auto *LookupRD = + const auto *LookupRD = dyn_cast_or_null(computeDeclContext(SS, false)); if (LookupRD && LookupRD->getIdentifier() == TemplateII) { Diag(TemplateIILoc, @@ -10498,10 +11735,9 @@ // Construct a dependent template specialization type. assert(DTN && "dependent template has non-dependent name?"); assert(DTN->getQualifier() == SS.getScopeRep()); - QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename, - DTN->getQualifier(), - DTN->getIdentifier(), - TemplateArgs); + QualType T = Context.getDependentTemplateSpecializationType( + ETK_Typename, DTN->getQualifier(), DTN->getIdentifier(), + TemplateArgs.arguments()); // Create source-location information for this type. TypeLocBuilder Builder; @@ -10518,7 +11754,7 @@ return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); } - QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs); + QualType T = CheckTemplateIdType(SS, Template, TemplateIILoc, TemplateArgs); if (T.isNull()) return true; @@ -10538,8 +11774,7 @@ TL.setElaboratedKeywordLoc(TypenameLoc); TL.setQualifierLoc(SS.getWithLocInContext(Context)); - TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T); - return CreateParsedType(T, TSI); + return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); } @@ -10745,9 +11980,9 @@ // We found a type. Build an ElaboratedType, since the // typename-specifier was just sugar. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); - return Context.getElaboratedType(Keyword, - QualifierLoc.getNestedNameSpecifier(), - Context.getTypeDeclType(Type)); + return Context.getElaboratedType( + Keyword, QualifierLoc.getNestedNameSpecifier(), + resugar(SS, Context.getTypeDeclType(Type))); } // C++ [dcl.type.simple]p2: diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp b/clang/lib/Sema/SemaTemplateDeduction.cpp --- a/clang/lib/Sema/SemaTemplateDeduction.cpp +++ b/clang/lib/Sema/SemaTemplateDeduction.cpp @@ -2574,13 +2574,10 @@ /// Convert the given deduced template argument and add it to the set of /// fully-converted template arguments. -static bool -ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param, - DeducedTemplateArgument Arg, - NamedDecl *Template, - TemplateDeductionInfo &Info, - bool IsDeduced, - SmallVectorImpl &Output) { +static bool ConvertDeducedTemplateArgument( + Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template, + TemplateDeductionInfo &Info, bool IsDeduced, + SmallVectorImpl &Output, bool DontCanonicalize) { auto ConvertArg = [&](DeducedTemplateArgument Arg, unsigned ArgumentPackIndex) { // Convert the deduced template argument into a template @@ -2596,7 +2593,8 @@ IsDeduced ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound : Sema::CTAK_Deduced) - : Sema::CTAK_Specified); + : Sema::CTAK_Specified, + DontCanonicalize); }; if (Arg.getKind() == TemplateArgument::Pack) { @@ -2633,7 +2631,7 @@ if (PackedArgsBuilder.empty()) { LocalInstantiationScope Scope(S); TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output); - MultiLevelTemplateArgumentList Args(TemplateArgs); + MultiLevelTemplateArgumentList Args(Template, TemplateArgs.asArray()); if (auto *NTTP = dyn_cast(Param)) { Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template, @@ -2665,13 +2663,14 @@ // FIXME: This should not be a template, but // ClassTemplatePartialSpecializationDecl sadly does not derive from // TemplateDecl. -template +template static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments( Sema &S, TemplateDeclT *Template, bool IsDeduced, SmallVectorImpl &Deduced, TemplateDeductionInfo &Info, SmallVectorImpl &Builder, LocalInstantiationScope *CurrentInstantiationScope = nullptr, - unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) { + unsigned NumAlreadyConverted = 0, bool PartialOverloading = false, + bool DontCanonicalize = false) { TemplateParameterList *TemplateParams = Template->getTemplateParameters(); for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { @@ -2711,7 +2710,8 @@ // We may have deduced this argument, so it still needs to be // checked and converted. if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info, - IsDeduced, Builder)) { + IsDeduced, Builder, + DontCanonicalize)) { Info.Param = makeTemplateParameter(Param); // FIXME: These template arguments are temporary. Free them! Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder)); @@ -2763,7 +2763,7 @@ // Check whether we can actually use the default argument. if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(), 0, Builder, - Sema::CTAK_Specified)) { + Sema::CTAK_Specified, DontCanonicalize)) { Info.Param = makeTemplateParameter( const_cast(TemplateParams->getParam(I))); // FIXME: These template arguments are temporary. Free them! @@ -2820,7 +2820,7 @@ Sema &S, T *Partial, bool IsPartialOrdering, const TemplateArgumentList &TemplateArgs, SmallVectorImpl &Deduced, - TemplateDeductionInfo &Info) { + TemplateDeductionInfo &Info, bool DontCanonicalize) { // Unevaluated SFINAE context. EnterExpressionEvaluationContext Unevaluated( S, Sema::ExpressionEvaluationContext::Unevaluated); @@ -2833,7 +2833,10 @@ // explicitly specified, template argument deduction fails. SmallVector Builder; if (auto Result = ConvertDeducedTemplateArguments( - S, Partial, IsPartialOrdering, Deduced, Info, Builder)) + S, Partial, IsPartialOrdering, Deduced, Info, Builder, + /*CurrentInstantiationScope=*/nullptr, + /*NumAlreadyConverted=*/0U, + /*PartialOverloading=*/false, DontCanonicalize)) return Result; // Form the template argument list from the deduced template arguments. @@ -2842,6 +2845,9 @@ Info.reset(DeducedArgumentList); + if (DontCanonicalize) + return Sema::TDK_Success; + // Substitute the deduced template arguments into the template // arguments of the class template partial specialization, and // verify that the instantiated template arguments are both valid @@ -2857,7 +2863,9 @@ if (S.SubstTemplateArguments( PartialTemplArgInfo->arguments(), - MultiLevelTemplateArgumentList(*DeducedArgumentList), InstArgs)) { + MultiLevelTemplateArgumentList(Partial, // FIXME: Partial or Template? + DeducedArgumentList->asArray()), + InstArgs)) { unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx; if (ParamIdx >= Partial->getTemplateParameters()->size()) ParamIdx = Partial->getTemplateParameters()->size() - 1; @@ -2905,7 +2913,7 @@ Sema &S, TemplateDecl *Template, bool PartialOrdering, const TemplateArgumentList &TemplateArgs, SmallVectorImpl &Deduced, - TemplateDeductionInfo &Info) { + TemplateDeductionInfo &Info, bool DontCanonicalize) { // Unevaluated SFINAE context. EnterExpressionEvaluationContext Unevaluated( S, Sema::ExpressionEvaluationContext::Unevaluated); @@ -2918,9 +2926,15 @@ // explicitly specified, template argument deduction fails. SmallVector Builder; if (auto Result = ConvertDeducedTemplateArguments( - S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder)) + S, Template, /*IsDeduced*/ PartialOrdering, Deduced, Info, Builder, + /*CurrentInstantiationScope=*/nullptr, + /*NumAlreadyConverted=*/0U, /*PartialOverloading=*/false, + DontCanonicalize)) return Result; + if (DontCanonicalize) + return Sema::TDK_Success; + // Check that we produced the correct argument list. TemplateParameterList *TemplateParams = Template->getTemplateParameters(); for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) { @@ -2950,7 +2964,8 @@ Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, - TemplateDeductionInfo &Info) { + TemplateDeductionInfo &Info, + bool DontCanonicalize) { if (Partial->isInvalidDecl()) return TDK_Invalid; @@ -2991,7 +3006,8 @@ runWithSufficientStackSpace(Info.getLocation(), [&] { Result = ::FinishTemplateArgumentDeduction(*this, Partial, /*IsPartialOrdering=*/false, - TemplateArgs, Deduced, Info); + TemplateArgs, Deduced, Info, + DontCanonicalize); }); return Result; } @@ -3002,7 +3018,8 @@ Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, - TemplateDeductionInfo &Info) { + TemplateDeductionInfo &Info, + bool DontCanonicalize) { if (Partial->isInvalidDecl()) return TDK_Invalid; @@ -3041,7 +3058,8 @@ runWithSufficientStackSpace(Info.getLocation(), [&] { Result = ::FinishTemplateArgumentDeduction(*this, Partial, /*IsPartialOrdering=*/false, - TemplateArgs, Deduced, Info); + TemplateArgs, Deduced, Info, + DontCanonicalize); }); return Result; } @@ -3193,7 +3211,8 @@ if (Proto->hasTrailingReturn()) { if (SubstParmTypes(Function->getLocation(), Function->parameters(), Proto->getExtParameterInfosOrNull(), - MultiLevelTemplateArgumentList(*ExplicitArgumentList), + MultiLevelTemplateArgumentList( + FunctionTemplate, ExplicitArgumentList->asArray()), ParamTypes, /*params*/ nullptr, ExtParamInfos)) return TDK_SubstitutionFailure; } @@ -3219,7 +3238,8 @@ ResultType = SubstType(Proto->getReturnType(), - MultiLevelTemplateArgumentList(*ExplicitArgumentList), + MultiLevelTemplateArgumentList( + FunctionTemplate, ExplicitArgumentList->asArray()), Function->getTypeSpecStartLoc(), Function->getDeclName()); if (ResultType.isNull() || Trap.hasErrorOccurred()) return TDK_SubstitutionFailure; @@ -3237,7 +3257,8 @@ if (!Proto->hasTrailingReturn() && SubstParmTypes(Function->getLocation(), Function->parameters(), Proto->getExtParameterInfosOrNull(), - MultiLevelTemplateArgumentList(*ExplicitArgumentList), + MultiLevelTemplateArgumentList( + FunctionTemplate, ExplicitArgumentList->asArray()), ParamTypes, /*params*/ nullptr, ExtParamInfos)) return TDK_SubstitutionFailure; @@ -3252,7 +3273,8 @@ if (getLangOpts().CPlusPlus17 && SubstExceptionSpec( Function->getLocation(), EPI.ExceptionSpec, ExceptionStorage, - MultiLevelTemplateArgumentList(*ExplicitArgumentList))) + MultiLevelTemplateArgumentList(FunctionTemplate, + ExplicitArgumentList->asArray()))) return TDK_SubstitutionFailure; *FunctionType = BuildFunctionType(ResultType, ParamTypes, @@ -3492,7 +3514,8 @@ DeclContext *Owner = FunctionTemplate->getDeclContext(); if (FunctionTemplate->getFriendObjectKind()) Owner = FunctionTemplate->getLexicalDeclContext(); - MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList); + MultiLevelTemplateArgumentList SubstArgs(FunctionTemplate, + DeducedArgumentList->asArray()); Specialization = cast_or_null( SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs)); if (!Specialization || Specialization->isInvalidDecl()) @@ -3598,12 +3621,18 @@ /// Gets the type of a function for template-argument-deducton /// purposes when it's considered as part of an overload set. static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R, - FunctionDecl *Fn) { + FunctionDecl *Fn, + const TemplateArgumentListInfo *Args) { // We may need to deduce the return type of the function now. if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() && S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false)) return {}; + // FIXME: get SS. + QualType FT = Fn->getType(); + if (Args) + FT = S.resugar(CXXScopeSpec(), Fn, Args->arguments(), FT); + if (CXXMethodDecl *Method = dyn_cast(Fn)) if (Method->isInstance()) { // An instance method that's referenced in a form that doesn't @@ -3611,12 +3640,14 @@ if (!R.HasFormOfMemberPointer) return {}; - return S.Context.getMemberPointerType(Fn->getType(), - S.Context.getTypeDeclType(Method->getParent()).getTypePtr()); + // FIXME: resugar the class type here. + return S.Context.getMemberPointerType( + FT, S.Context.getTypeDeclType(Method->getParent()).getTypePtr()); } - if (!R.IsAddressOfOperand) return Fn->getType(); - return S.Context.getPointerType(Fn->getType()); + if (!R.IsAddressOfOperand) + return FT; + return S.Context.getPointerType(FT); } /// Apply the deduction rules for overload sets. @@ -3639,6 +3670,11 @@ if (R.IsAddressOfOperand) TDF |= TDF_IgnoreQualifiers; + // Gather the explicit template arguments, if any. + TemplateArgumentListInfo ExplicitTemplateArgs; + if (Ovl->hasExplicitTemplateArgs()) + Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); + // C++0x [temp.deduct.call]p6: // When P is a function type, pointer to function type, or pointer // to member function type: @@ -3648,23 +3684,20 @@ !ParamType->isMemberFunctionPointerType()) { if (Ovl->hasExplicitTemplateArgs()) { // But we can still look for an explicit specialization. - if (FunctionDecl *ExplicitSpec - = S.ResolveSingleFunctionTemplateSpecialization(Ovl)) - return GetTypeOfFunction(S, R, ExplicitSpec); + if (FunctionDecl *ExplicitSpec = + S.ResolveSingleFunctionTemplateSpecialization( + Ovl, ExplicitTemplateArgs)) + return GetTypeOfFunction(S, R, ExplicitSpec, &ExplicitTemplateArgs); } DeclAccessPair DAP; if (FunctionDecl *Viable = S.resolveAddressOfSingleOverloadCandidate(Arg, DAP)) - return GetTypeOfFunction(S, R, Viable); + return GetTypeOfFunction(S, R, Viable, nullptr); return {}; } - // Gather the explicit template arguments, if any. - TemplateArgumentListInfo ExplicitTemplateArgs; - if (Ovl->hasExplicitTemplateArgs()) - Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); QualType Match; for (UnresolvedSetIterator I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { @@ -3688,7 +3721,7 @@ } FunctionDecl *Fn = cast(D); - QualType ArgType = GetTypeOfFunction(S, R, Fn); + QualType ArgType = GetTypeOfFunction(S, R, Fn, &ExplicitTemplateArgs); if (ArgType.isNull()) continue; // Function-to-pointer conversion. @@ -5318,7 +5351,8 @@ S, P2, /*IsPartialOrdering=*/true, TemplateArgumentList(TemplateArgumentList::OnStack, TST1->template_arguments()), - Deduced, Info); + Deduced, Info, + /*DontCanonicalize=*/false); // FIXME }); return AtLeastAsSpecialized; } @@ -5791,9 +5825,8 @@ case Type::SubstTemplateTypeParmPack: { const SubstTemplateTypeParmPackType *Subst = cast(T); - MarkUsedTemplateParameters(Ctx, - QualType(Subst->getReplacedParameter(), 0), - OnlyDeduced, Depth, Used); + if (Subst->getReplacedTemplateParam()->getDepth() == Depth) + Used[Subst->getIndex()] = true; MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(), OnlyDeduced, Depth, Used); break; diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp b/clang/lib/Sema/SemaTemplateInstantiate.cpp --- a/clang/lib/Sema/SemaTemplateInstantiate.cpp +++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp @@ -64,7 +64,8 @@ MultiLevelTemplateArgumentList Result; if (Innermost) - Result.addOuterTemplateArguments(Innermost); + Result.addOuterTemplateArguments(const_cast(D), + Innermost->asArray()); const auto *Ctx = dyn_cast(D); if (!Ctx) { @@ -80,8 +81,6 @@ !isa(Spec)) return Result; - Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs()); - // If this variable template specialization was instantiated from a // specialized member that is a variable template, we're done. assert(Spec->getSpecializedTemplate() && "No variable template?"); @@ -90,10 +89,14 @@ = Spec->getSpecializedTemplateOrPartial(); if (VarTemplatePartialSpecializationDecl *Partial = Specialized.dyn_cast()) { + Result.addOuterTemplateArguments( + Partial, Spec->getTemplateInstantiationArgs().asArray()); if (Partial->isMemberSpecialization()) return Result; } else { VarTemplateDecl *Tmpl = Specialized.get(); + Result.addOuterTemplateArguments( + Tmpl, Spec->getTemplateInstantiationArgs().asArray()); if (Tmpl->isMemberSpecialization()) return Result; } @@ -123,7 +126,9 @@ !isa(Spec)) break; - Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs()); + Result.addOuterTemplateArguments( + const_cast(Spec), + Spec->getTemplateInstantiationArgs().asArray()); // If this class template specialization was instantiated from a // specialized member that is a class template, we're done. @@ -146,7 +151,8 @@ } else if (const TemplateArgumentList *TemplateArgs = Function->getTemplateSpecializationArgs()) { // Add the template arguments for this specialization. - Result.addOuterTemplateArguments(TemplateArgs); + Result.addOuterTemplateArguments(const_cast(Function), + TemplateArgs->asArray()); // If this function was instantiated from a specialized member that is // a function template, we're done. @@ -1638,9 +1644,11 @@ // Type=decltype(2))) // The call to CheckTemplateArgument here produces the ImpCast. TemplateArgument Converted; - if (SemaRef.CheckTemplateArgument(E->getParameter(), SubstType, - SubstReplacement.get(), - Converted).isInvalid()) + if (SemaRef + .CheckTemplateArgument( + E->getParameter(), SubstType, SubstReplacement.get(), Converted, + Sema::CTAK_Specified, /*DontCanonicalize=*/false) + .isInvalid()) return true; return transformNonTypeTemplateParmRef(E->getParameter(), E->getExprLoc(), Converted); @@ -1778,6 +1786,9 @@ TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB, TemplateTypeParmTypeLoc TL) { const TemplateTypeParmType *T = TL.getTypePtr(); + TemplateTypeParmDecl *NewTTPDecl = cast_or_null( + TransformDecl(TL.getNameLoc(), T->getDecl())); + if (T->getDepth() < TemplateArgs.getNumLevels()) { // Replace the template type parameter with its corresponding // template argument. @@ -1813,6 +1824,8 @@ return NewT; } + Decl *ReplacedDecl = TemplateArgs.getReplacedDecl(T->getDepth()); + Optional PackIndex; if (T->isParameterPack()) { assert(Arg.getKind() == TemplateArgument::Pack && @@ -1822,8 +1835,8 @@ // We have the template argument pack, but we're not expanding the // enclosing pack expansion yet. Just save the template argument // pack for later substitution. - QualType Result - = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg); + QualType Result = getSema().Context.getSubstTemplateTypeParmPackType( + ReplacedDecl, T->getIndex(), Arg); SubstTemplateTypeParmPackTypeLoc NewTL = TLB.push(Result); NewTL.setNameLoc(TL.getNameLoc()); @@ -1841,7 +1854,7 @@ // TODO: only do this uniquing once, at the start of instantiation. QualType Result = getSema().Context.getSubstTemplateTypeParmType( - T, Replacement, PackIndex); + Replacement, ReplacedDecl, T->getIndex(), PackIndex); SubstTemplateTypeParmTypeLoc NewTL = TLB.push(Result); NewTL.setNameLoc(TL.getNameLoc()); @@ -1852,11 +1865,6 @@ // the template parameter list of a member template inside the // template we are instantiating). Create a new template type // parameter with the template "level" reduced by one. - TemplateTypeParmDecl *NewTTPDecl = nullptr; - if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl()) - NewTTPDecl = cast_or_null( - TransformDecl(TL.getNameLoc(), OldTTPDecl)); - QualType Result = getSema().Context.getTemplateTypeParmType( T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(), T->isParameterPack(), NewTTPDecl); @@ -1865,26 +1873,32 @@ return Result; } -QualType -TemplateInstantiator::TransformSubstTemplateTypeParmPackType( - TypeLocBuilder &TLB, - SubstTemplateTypeParmPackTypeLoc TL) { +QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType( + TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL) { + const SubstTemplateTypeParmPackType *T = TL.getTypePtr(); + + Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getReplacedDecl()); + if (getSema().ArgumentPackSubstitutionIndex == -1) { // We aren't expanding the parameter pack, so just return ourselves. - SubstTemplateTypeParmPackTypeLoc NewTL - = TLB.push(TL.getType()); + QualType Result = TL.getType(); + if (NewReplaced != T->getReplacedDecl()) + Result = getSema().Context.getSubstTemplateTypeParmPackType( + NewReplaced, T->getIndex(), T->getArgumentPack()); + SubstTemplateTypeParmPackTypeLoc NewTL = + TLB.push(Result); NewTL.setNameLoc(TL.getNameLoc()); - return TL.getType(); + return Result; } - TemplateArgument Arg = TL.getTypePtr()->getArgumentPack(); - Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); + TemplateArgument Arg = + getPackSubstitutedTemplateArgument(getSema(), T->getArgumentPack()); QualType Result = getSema().Context.getSubstTemplateTypeParmType( - TL.getTypePtr()->getReplacedParameter(), Arg.getAsType(), + Arg.getAsType(), NewReplaced, T->getIndex(), getSema().ArgumentPackSubstitutionIndex); - SubstTemplateTypeParmTypeLoc NewTL - = TLB.push(Result); + SubstTemplateTypeParmTypeLoc NewTL = + TLB.push(Result); NewTL.setNameLoc(TL.getNameLoc()); return Result; } diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp --- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp +++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp @@ -4762,7 +4762,7 @@ return nullptr; ContextRAII SavedContext(*this, FD); - MultiLevelTemplateArgumentList MArgs(*Args); + MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray()); return cast_or_null(SubstDecl(FD, FD->getParent(), MArgs)); } @@ -4958,6 +4958,7 @@ Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization(); LocalInstantiationScope Scope(*this, MergeWithParentScope); + auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() { // Special members might get their TypeSourceInfo set up w.r.t the // PatternDecl context, in which case parameters could still be pointing @@ -5108,9 +5109,6 @@ if (Inst.isInvalid()) return nullptr; - MultiLevelTemplateArgumentList TemplateArgLists; - TemplateArgLists.addOuterTemplateArguments(&TemplateArgList); - // Instantiate the first declaration of the variable template: for a partial // specialization of a static data member template, the first declaration may // or may not be the declaration in the class; if it's in the class, we want @@ -5129,7 +5127,8 @@ if (!IsMemberSpec) FromVar = FromVar->getFirstDecl(); - MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList); + MultiLevelTemplateArgumentList MultiLevelList(VarTemplate, + TemplateArgList.asArray()); TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(), MultiLevelList); @@ -6162,7 +6161,8 @@ Args.addArgument( getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc)); } - QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args); + QualType T = + CheckTemplateIdType(CXXScopeSpec(), TemplateName(TD), Loc, Args); if (T.isNull()) return nullptr; auto *SubstRecord = T->getAsCXXRecordDecl(); diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp --- a/clang/lib/Sema/SemaType.cpp +++ b/clang/lib/Sema/SemaType.cpp @@ -9118,6 +9118,56 @@ return Context.getTypeOfExprType(E); } +static QualType getSameReferencedType(ASTContext &Context, QualType VT, + QualType ET) { + assert(!ET->isReferenceType()); + if (const auto *VTL = VT->getAs()) + ET = Context.getLValueReferenceType(ET, VTL->isSpelledAsLValue()); + else if (VT->isRValueReferenceType()) + ET = Context.getRValueReferenceType(ET); + + if (!Context.hasSameUnqualifiedType(ET, VT)) { + ET.dump(); + VT.dump(); + assert(false && "!hasSameUnqualifiedType"); + } + + Qualifiers ToAdd = VT.getQualifiers(), ToRemove = ET.getQualifiers(); + (void)Qualifiers::removeCommonQualifiers(ToAdd, ToRemove); + + SplitQualType Split = ET.split(); + while (!ToRemove.empty()) { + (void)Qualifiers::removeCommonQualifiers(Split.Quals, ToRemove); + if (ToRemove.empty()) + break; + QualType Next; + switch (ET->getTypeClass()) { +#define ABSTRACT_TYPE(Class, Parent) +#define TYPE(Class, Parent) \ + case Type::Class: { \ + const auto *ty = cast(ET); \ + if (!ty->isSugared()) \ + goto done; \ + Next = ty->desugar(); \ + break; \ + } +#include "clang/AST/TypeNodes.inc" + } + Split = Next.split(); + } +done: + assert(ToRemove.empty()); + Split.Quals += ToAdd; + ET = Context.getQualifiedType(Split); + + if (!Context.hasSameType(ET, VT)) { + ET.dump(); + VT.dump(); + assert(false && "!hasSameType"); + } + return ET; +} + /// getDecltypeForExpr - Given an expr, will return the decltype for /// that expression, according to the rules in C++11 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. @@ -9150,18 +9200,20 @@ // We apply the same rules for Objective-C ivar and property references. if (const auto *DRE = dyn_cast(IDExpr)) { const ValueDecl *VD = DRE->getDecl(); - QualType T = VD->getType(); + QualType T = getSameReferencedType(Context, VD->getType(), DRE->getType()); return isa(VD) ? T.getUnqualifiedType() : T; } if (const auto *ME = dyn_cast(IDExpr)) { if (const auto *VD = ME->getMemberDecl()) if (isa(VD) || isa(VD)) - return VD->getType(); + return getSameReferencedType(Context, VD->getType(), ME->getType()); } else if (const auto *IR = dyn_cast(IDExpr)) { + // FIXME: Sugar these. Breaks Modules/odr_hash.mm. return IR->getDecl()->getType(); } else if (const auto *PR = dyn_cast(IDExpr)) { if (PR->isExplicitProperty()) - return PR->getExplicitProperty()->getType(); + return getSameReferencedType( + Context, PR->getExplicitProperty()->getType(), PR->getType()); } else if (const auto *PE = dyn_cast(IDExpr)) { return PE->getType(); } diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h --- a/clang/lib/Sema/TreeTransform.h +++ b/clang/lib/Sema/TreeTransform.h @@ -1009,7 +1009,8 @@ /// By default, performs semantic analysis when building the template /// specialization type. Subclasses may override this routine to provide /// different behavior. - QualType RebuildTemplateSpecializationType(TemplateName Template, + QualType RebuildTemplateSpecializationType(const CXXScopeSpec &SS, + TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &Args); @@ -1061,15 +1062,14 @@ // If it's still dependent, make a dependent specialization. if (InstName.getAsDependentTemplateName()) - return SemaRef.Context.getDependentTemplateSpecializationType(Keyword, - QualifierLoc.getNestedNameSpecifier(), - Name, - Args); + return SemaRef.Context.getDependentTemplateSpecializationType( + Keyword, QualifierLoc.getNestedNameSpecifier(), Name, + Args.arguments()); // Otherwise, make an elaborated type wrapping a non-dependent // specialization. - QualType T = - getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args); + QualType T = getDerived().RebuildTemplateSpecializationType(SS, InstName, + NameLoc, Args); if (T.isNull()) return QualType(); return SemaRef.Context.getElaboratedType( @@ -2674,6 +2674,9 @@ NamedDecl *FirstQualifierInScope) { ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base, isArrow); + CXXScopeSpec SS; + SS.Adopt(QualifierLoc); + if (!Member->getDeclName()) { // We have a reference to an unnamed field. This is always the // base of an anonymous struct/union member access, i.e. the @@ -2689,15 +2692,14 @@ return ExprError(); Base = BaseResult.get(); - CXXScopeSpec EmptySS; + // FIXME: resugar. return getSema().BuildFieldReferenceExpr( - Base, isArrow, OpLoc, EmptySS, cast(Member), - DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo); + Base, isArrow, OpLoc, NestedNameSpecifierLoc(), + cast(Member), Member->getType(), + DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), + MemberNameInfo); } - CXXScopeSpec SS; - SS.Adopt(QualifierLoc); - Base = BaseResult.get(); QualType BaseType = Base->getType(); @@ -4854,8 +4856,8 @@ Replacement = SemaRef.Context.getQualifiedType( Replacement.getUnqualifiedType(), Qs); T = SemaRef.Context.getSubstTemplateTypeParmType( - SubstTypeParam->getReplacedParameter(), Replacement, - SubstTypeParam->getPackIndex()); + Replacement, SubstTypeParam->getReplacedDecl(), + SubstTypeParam->getIndex(), SubstTypeParam->getPackIndex()); } else if ((AutoTy = dyn_cast(T)) && AutoTy->isDeduced()) { // 'auto' types behave the same way as template parameters. QualType Deduced = AutoTy->getDeducedType(); @@ -4891,7 +4893,7 @@ return TL; TypeSourceInfo *TSI = - TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS); + getDerived().TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS); if (TSI) return TSI->getTypeLoc(); return TypeLoc(); @@ -4906,8 +4908,8 @@ if (getDerived().AlreadyTransformed(TSInfo->getType())) return TSInfo; - return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType, - UnqualLookup, SS); + return getDerived().TransformTSIInObjectScope(TSInfo->getTypeLoc(), + ObjectType, UnqualLookup, SS); } template @@ -5511,7 +5513,8 @@ TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) { const DependentAddressSpaceType *T = TL.getTypePtr(); - QualType pointeeType = getDerived().TransformType(T->getPointeeType()); + QualType pointeeType = + getDerived().TransformType(TLB, TL.getPointeeTypeLoc()); if (pointeeType.isNull()) return QualType(); @@ -5544,9 +5547,8 @@ NewTL.setAttrNameLoc(TL.getAttrNameLoc()); } else { - TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo( - Result, getDerived().getBaseLocation()); - TransformType(TLB, DI->getTypeLoc()); + // Result is just the pointee type with an extended qualifier added. + TLB.TypeWasModifiedSafely(Result); } return Result; @@ -6401,6 +6403,9 @@ SubstTemplateTypeParmTypeLoc TL) { const SubstTemplateTypeParmType *T = TL.getTypePtr(); + Decl *NewReplaced = + getDerived().TransformDecl(TL.getNameLoc(), T->getReplacedDecl()); + // Substitute into the replacement type, which itself might involve something // that needs to be transformed. This only tends to occur with default // template arguments of template template parameters. @@ -6412,7 +6417,7 @@ // Always canonicalize the replacement type. Replacement = SemaRef.Context.getCanonicalType(Replacement); QualType Result = SemaRef.Context.getSubstTemplateTypeParmType( - T->getReplacedParameter(), Replacement, T->getPackIndex()); + Replacement, NewReplaced, T->getIndex(), T->getPackIndex()); // Propagate type-source information. SubstTemplateTypeParmTypeLoc NewTL @@ -6690,10 +6695,8 @@ // FIXME: maybe don't rebuild if all the template arguments are the same. - QualType Result = - getDerived().RebuildTemplateSpecializationType(Template, - TL.getTemplateNameLoc(), - NewTemplateArgs); + QualType Result = getDerived().RebuildTemplateSpecializationType( + CXXScopeSpec(), Template, TL.getTemplateNameLoc(), NewTemplateArgs); if (!Result.isNull()) { // Specializations of template template parameters are represented as @@ -6746,12 +6749,9 @@ // FIXME: maybe don't rebuild if all the template arguments are the same. if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { - QualType Result - = getSema().Context.getDependentTemplateSpecializationType( - TL.getTypePtr()->getKeyword(), - DTN->getQualifier(), - DTN->getIdentifier(), - NewTemplateArgs); + QualType Result = getSema().Context.getDependentTemplateSpecializationType( + TL.getTypePtr()->getKeyword(), DTN->getQualifier(), + DTN->getIdentifier(), NewTemplateArgs.arguments()); DependentTemplateSpecializationTypeLoc NewTL = TLB.push(Result); @@ -6766,10 +6766,8 @@ return Result; } - QualType Result - = getDerived().RebuildTemplateSpecializationType(Template, - TL.getTemplateNameLoc(), - NewTemplateArgs); + QualType Result = getDerived().RebuildTemplateSpecializationType( + SS, Template, TL.getTemplateNameLoc(), NewTemplateArgs); if (!Result.isNull()) { /// FIXME: Wrap this in an elaborated-type-specifier? @@ -11071,8 +11069,7 @@ getSema().FpPragmaStack.CurrentValue = NewOverrides; } - return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc, - Args, + return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc, Args, E->getRParenLoc()); } @@ -14751,12 +14748,12 @@ return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc); } -template +template QualType TreeTransform::RebuildTemplateSpecializationType( - TemplateName Template, - SourceLocation TemplateNameLoc, - TemplateArgumentListInfo &TemplateArgs) { - return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs); + const CXXScopeSpec &SS, TemplateName Template, + SourceLocation TemplateNameLoc, TemplateArgumentListInfo &TemplateArgs) { + return SemaRef.CheckTemplateIdType(SS, Template, TemplateNameLoc, + TemplateArgs); } template diff --git a/clang/lib/Serialization/ASTReaderDecl.cpp b/clang/lib/Serialization/ASTReaderDecl.cpp --- a/clang/lib/Serialization/ASTReaderDecl.cpp +++ b/clang/lib/Serialization/ASTReaderDecl.cpp @@ -2386,8 +2386,6 @@ ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarTemplateSpecializationDeclImpl( VarTemplateSpecializationDecl *D) { - RedeclarableResult Redecl = VisitVarDeclImpl(D); - ASTContext &C = Reader.getContext(); if (Decl *InstD = readDecl()) { if (auto *VTD = dyn_cast(InstD)) { @@ -2424,6 +2422,8 @@ D->SpecializationKind = (TemplateSpecializationKind)Record.readInt(); D->IsCompleteDefinition = Record.readInt(); + RedeclarableResult Redecl = VisitVarDeclImpl(D); + bool writtenAsCanonicalDecl = Record.readInt(); if (writtenAsCanonicalDecl) { auto *CanonPattern = readDeclAs(); diff --git a/clang/lib/Serialization/ASTWriterDecl.cpp b/clang/lib/Serialization/ASTWriterDecl.cpp --- a/clang/lib/Serialization/ASTWriterDecl.cpp +++ b/clang/lib/Serialization/ASTWriterDecl.cpp @@ -1604,8 +1604,6 @@ VarTemplateSpecializationDecl *D) { RegisterTemplateSpecialization(D->getSpecializedTemplate(), D); - VisitVarDecl(D); - llvm::PointerUnion InstFrom = D->getSpecializedTemplateOrPartial(); if (Decl *InstFromD = InstFrom.dyn_cast()) { @@ -1626,6 +1624,9 @@ Record.AddSourceLocation(D->getPointOfInstantiation()); Record.push_back(D->getSpecializationKind()); Record.push_back(D->IsCompleteDefinition); + + VisitVarDecl(D); + Record.push_back(D->isCanonicalDecl()); if (D->isCanonicalDecl()) { diff --git a/clang/lib/StaticAnalyzer/Checkers/MismatchedIteratorChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MismatchedIteratorChecker.cpp --- a/clang/lib/StaticAnalyzer/Checkers/MismatchedIteratorChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MismatchedIteratorChecker.cpp @@ -176,8 +176,10 @@ const auto *Param = Func->getParamDecl(J); const auto *ParamType = Param->getType()->getAs(); - if (!ParamType || - ParamType->getReplacedParameter()->getDecl() != TPDecl) + if (!ParamType) + continue; + const TemplateTypeParmDecl *D = ParamType->getReplacedTemplateParam(); + if (D != TPDecl) continue; if (LHS.isUndef()) { LHS = Call.getArgSVal(J); diff --git a/clang/test/AST/ast-dump-openmp-begin-declare-variant_reference.cpp b/clang/test/AST/ast-dump-openmp-begin-declare-variant_reference.cpp --- a/clang/test/AST/ast-dump-openmp-begin-declare-variant_reference.cpp +++ b/clang/test/AST/ast-dump-openmp-begin-declare-variant_reference.cpp @@ -122,9 +122,8 @@ // CHECK-NEXT: | | | `-BuiltinType [[ADDR_8:0x[a-z0-9]*]] 'float' // CHECK-NEXT: | | |-CXXRecordDecl [[ADDR_9:0x[a-z0-9]*]] col:29 implicit struct remove_reference // CHECK-NEXT: | | `-TypedefDecl [[ADDR_10:0x[a-z0-9]*]] col:67 referenced type 'float':'float' -// CHECK-NEXT: | | `-SubstTemplateTypeParmType [[ADDR_11:0x[a-z0-9]*]] 'float' sugar -// CHECK-NEXT: | | |-TemplateTypeParmType [[ADDR_12:0x[a-z0-9]*]] '_Tp' dependent depth 0 index 0 -// CHECK-NEXT: | | | `-TemplateTypeParm [[ADDR_13:0x[a-z0-9]*]] '_Tp' +// CHECK-NEXT: | | `-SubstTemplateTypeParmType [[ADDR_11:0x[a-z0-9]*]] 'float' sugar class depth 0 index 0 _Tp +// CHECK-NEXT: | | |-ClassTemplateSpecialization [[ADDR_6]] 'remove_reference' // CHECK-NEXT: | | `-BuiltinType [[ADDR_8]] 'float' // CHECK-NEXT: | `-ClassTemplateSpecializationDecl [[ADDR_14:0x[a-z0-9]*]] col:29 struct remove_reference definition // CHECK-NEXT: | |-DefinitionData pass_in_registers empty aggregate standard_layout trivially_copyable pod trivial literal has_constexpr_non_copy_move_ctor can_const_default_init @@ -139,9 +138,8 @@ // CHECK-NEXT: | | `-BuiltinType [[ADDR_16:0x[a-z0-9]*]] 'short' // CHECK-NEXT: | |-CXXRecordDecl [[ADDR_17:0x[a-z0-9]*]] col:29 implicit struct remove_reference // CHECK-NEXT: | `-TypedefDecl [[ADDR_18:0x[a-z0-9]*]] col:67 referenced type 'short':'short' -// CHECK-NEXT: | `-SubstTemplateTypeParmType [[ADDR_19:0x[a-z0-9]*]] 'short' sugar -// CHECK-NEXT: | |-TemplateTypeParmType [[ADDR_12]] '_Tp' dependent depth 0 index 0 -// CHECK-NEXT: | | `-TemplateTypeParm [[ADDR_13]] '_Tp' +// CHECK-NEXT: | `-SubstTemplateTypeParmType [[ADDR_19:0x[a-z0-9]*]] 'short' sugar class depth 0 index 0 _Tp +// CHECK-NEXT: | |-ClassTemplateSpecialization [[ADDR_14]] 'remove_reference' // CHECK-NEXT: | `-BuiltinType [[ADDR_16]] 'short' // CHECK-NEXT: |-ClassTemplatePartialSpecializationDecl [[ADDR_20:0x[a-z0-9]*]] col:29 struct remove_reference definition // CHECK-NEXT: | |-DefinitionData empty aggregate standard_layout trivially_copyable pod trivial literal has_constexpr_non_copy_move_ctor can_const_default_init @@ -154,10 +152,10 @@ // CHECK-NEXT: | |-TemplateArgument type 'type-parameter-0-0 &' // CHECK-NEXT: | | `-LValueReferenceType [[ADDR_21:0x[a-z0-9]*]] 'type-parameter-0-0 &' dependent // CHECK-NEXT: | | `-TemplateTypeParmType [[ADDR_22:0x[a-z0-9]*]] 'type-parameter-0-0' dependent depth 0 index 0 -// CHECK-NEXT: | |-TemplateTypeParmDecl [[ADDR_13]] col:17 referenced class depth 0 index 0 _Tp +// CHECK-NEXT: | |-TemplateTypeParmDecl [[ADDR_13:0x[a-z0-9]*]] col:17 referenced class depth 0 index 0 _Tp // CHECK-NEXT: | |-CXXRecordDecl [[ADDR_23:0x[a-z0-9]*]] col:29 implicit struct remove_reference // CHECK-NEXT: | `-TypedefDecl [[ADDR_24:0x[a-z0-9]*]] col:67 type '_Tp' -// CHECK-NEXT: | `-TemplateTypeParmType [[ADDR_12]] '_Tp' dependent depth 0 index 0 +// CHECK-NEXT: | `-TemplateTypeParmType [[ADDR_12:0x[a-z0-9]*]] '_Tp' dependent depth 0 index 0 // CHECK-NEXT: | `-TemplateTypeParm [[ADDR_13]] '_Tp' // CHECK-NEXT: |-ClassTemplatePartialSpecializationDecl [[ADDR_25:0x[a-z0-9]*]] col:29 struct remove_reference definition // CHECK-NEXT: | |-DefinitionData empty aggregate standard_layout trivially_copyable pod trivial literal has_constexpr_non_copy_move_ctor can_const_default_init @@ -197,9 +195,8 @@ // CHECK-NEXT: | | | `-ElaboratedType [[ADDR_47:0x[a-z0-9]*]] 'typename remove_reference::type' sugar // CHECK-NEXT: | | | `-TypedefType [[ADDR_48:0x[a-z0-9]*]] 'remove_reference::type' sugar // CHECK-NEXT: | | | |-Typedef [[ADDR_10]] 'type' -// CHECK-NEXT: | | | `-SubstTemplateTypeParmType [[ADDR_11]] 'float' sugar -// CHECK-NEXT: | | | |-TemplateTypeParmType [[ADDR_12]] '_Tp' dependent depth 0 index 0 -// CHECK-NEXT: | | | | `-TemplateTypeParm [[ADDR_13]] '_Tp' +// CHECK-NEXT: | | | `-SubstTemplateTypeParmType [[ADDR_11]] 'float' sugar class depth 0 index 0 _Tp +// CHECK-NEXT: | | | |-ClassTemplateSpecialization [[ADDR_6]] 'remove_reference' // CHECK-NEXT: | | | `-BuiltinType [[ADDR_8]] 'float' // CHECK-NEXT: | | `-ReturnStmt [[ADDR_49:0x[a-z0-9]*]] // CHECK-NEXT: | | `-CXXStaticCastExpr [[ADDR_50:0x[a-z0-9]*]] '_Up':'float' xvalue static_cast<_Up &&> @@ -215,9 +212,8 @@ // CHECK-NEXT: | | `-ElaboratedType [[ADDR_57:0x[a-z0-9]*]] 'typename remove_reference::type' sugar // CHECK-NEXT: | | `-TypedefType [[ADDR_58:0x[a-z0-9]*]] 'remove_reference::type' sugar // CHECK-NEXT: | | |-Typedef [[ADDR_18]] 'type' -// CHECK-NEXT: | | `-SubstTemplateTypeParmType [[ADDR_19]] 'short' sugar -// CHECK-NEXT: | | |-TemplateTypeParmType [[ADDR_12]] '_Tp' dependent depth 0 index 0 -// CHECK-NEXT: | | | `-TemplateTypeParm [[ADDR_13]] '_Tp' +// CHECK-NEXT: | | `-SubstTemplateTypeParmType [[ADDR_19]] 'short' sugar class depth 0 index 0 _Tp +// CHECK-NEXT: | | |-ClassTemplateSpecialization [[ADDR_14]] 'remove_reference' // CHECK-NEXT: | | `-BuiltinType [[ADDR_16]] 'short' // CHECK-NEXT: | `-ReturnStmt [[ADDR_59:0x[a-z0-9]*]] // CHECK-NEXT: | `-CXXStaticCastExpr [[ADDR_60:0x[a-z0-9]*]] '_Up':'short' xvalue static_cast<_Up &&> diff --git a/clang/test/AST/ast-dump-template-decls.cpp b/clang/test/AST/ast-dump-template-decls.cpp --- a/clang/test/AST/ast-dump-template-decls.cpp +++ b/clang/test/AST/ast-dump-template-decls.cpp @@ -120,12 +120,12 @@ // CHECK-NEXT: TemplateArgument type 'void' // CHECK-NEXT: BuiltinType 0x{{[^ ]*}} 'void' // CHECK-NEXT: FunctionProtoType 0x{{[^ ]*}} 'void (int)' cdecl -// CHECK-NEXT: SubstTemplateTypeParmType 0x{{[^ ]*}} 'void' sugar -// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'U' dependent depth 0 index 0 -// CHECK-NEXT: TemplateTypeParm 0x{{[^ ]*}} 'U' +// CHECK-NEXT: SubstTemplateTypeParmType 0x{{[^ ]*}} 'void' sugar class depth 0 index 0 U +// CHECK-NEXT: TypeAliasTemplate 0x{{[^ ]*}} 'type1' // CHECK-NEXT: BuiltinType 0x{{[^ ]*}} 'void' -// CHECK-NEXT: SubstTemplateTypeParmType 0x{{[^ ]*}} 'int' sugar -// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'T' dependent depth 0 index 0 +// CHECK-NEXT: SubstTemplateTypeParmType 0x{{[^ ]*}} 'int' sugar class depth 0 index 0 T +// CHECK-NEXT: ClassTemplateSpecialization 0x{{[^ ]*}} 'C' +// CHECK-NEXT: BuiltinType 0x{{[^ ]*}} 'int' } // namespace PR55886 namespace PR56099 { @@ -136,14 +136,14 @@ }; using t1 = foo::bind; // CHECK: TemplateSpecializationType 0x{{[^ ]*}} 'Y' sugar Y -// CHECK: SubstTemplateTypeParmType 0x{{[^ ]*}} 'char' sugar pack_index 0 -// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'Bs' dependent contains_unexpanded_pack depth 0 index 0 pack -// CHECK: SubstTemplateTypeParmType 0x{{[^ ]*}} 'float' sugar pack_index 1 -// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'Bs' dependent contains_unexpanded_pack depth 0 index 0 pack -// CHECK: SubstTemplateTypeParmType 0x{{[^ ]*}} 'int' sugar pack_index 2 -// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'Bs' dependent contains_unexpanded_pack depth 0 index 0 pack -// CHECK: SubstTemplateTypeParmType 0x{{[^ ]*}} 'short' sugar pack_index 3 -// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'Bs' dependent contains_unexpanded_pack depth 0 index 0 pack +// CHECK: SubstTemplateTypeParmType 0x{{[^ ]*}} 'char' sugar typename depth 0 index 0 ... Bs pack_index 0 +// CHECK-NEXT: TypeAliasTemplate 0x{{[^ ]*}} 'Z' +// CHECK: SubstTemplateTypeParmType 0x{{[^ ]*}} 'float' sugar typename depth 0 index 0 ... Bs pack_index 1 +// CHECK-NEXT: TypeAliasTemplate 0x{{[^ ]*}} 'Z' +// CHECK: SubstTemplateTypeParmType 0x{{[^ ]*}} 'int' sugar typename depth 0 index 0 ... Bs pack_index 2 +// CHECK-NEXT: TypeAliasTemplate 0x{{[^ ]*}} 'Z' +// CHECK: SubstTemplateTypeParmType 0x{{[^ ]*}} 'short' sugar typename depth 0 index 0 ... Bs pack_index 3 +// CHECK-NEXT: TypeAliasTemplate 0x{{[^ ]*}} 'Z' template struct D { template using B = int(int (*...p)(T, U)); @@ -152,13 +152,13 @@ // CHECK: TemplateSpecializationType 0x{{[^ ]*}} 'B' sugar alias B // CHECK: FunctionProtoType 0x{{[^ ]*}} 'int (int (*)(float, int), int (*)(char, short))' cdecl // CHECK: FunctionProtoType 0x{{[^ ]*}} 'int (float, int)' cdecl -// CHECK: SubstTemplateTypeParmType 0x{{[^ ]*}} 'float' sugar pack_index 0 -// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'T' dependent contains_unexpanded_pack depth 0 index 0 pack -// CHECK: SubstTemplateTypeParmType 0x{{[^ ]*}} 'int' sugar pack_index 0 -// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'U' dependent contains_unexpanded_pack depth 0 index 0 pack +// CHECK: SubstTemplateTypeParmType 0x{{[^ ]*}} 'float' sugar typename depth 0 index 0 ... T pack_index 0 +// CHECK-NEXT: ClassTemplateSpecialization 0x{{[^ ]*}} 'D' +// CHECK: SubstTemplateTypeParmType 0x{{[^ ]*}} 'int' sugar typename depth 0 index 0 ... U pack_index 0 +// CHECK-NEXT: TypeAliasTemplate 0x{{[^ ]*}} 'B' // CHECK: FunctionProtoType 0x{{[^ ]*}} 'int (char, short)' cdecl -// CHECK: SubstTemplateTypeParmType 0x{{[^ ]*}} 'char' sugar pack_index 1 -// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'T' dependent contains_unexpanded_pack depth 0 index 0 pack -// CHECK: SubstTemplateTypeParmType 0x{{[^ ]*}} 'short' sugar pack_index 1 -// CHECK-NEXT: TemplateTypeParmType 0x{{[^ ]*}} 'U' dependent contains_unexpanded_pack depth 0 index 0 pack +// CHECK: SubstTemplateTypeParmType 0x{{[^ ]*}} 'char' sugar typename depth 0 index 0 ... T pack_index 1 +// CHECK-NEXT: ClassTemplateSpecialization 0x{{[^ ]*}} 'D' +// CHECK: SubstTemplateTypeParmType 0x{{[^ ]*}} 'short' sugar typename depth 0 index 0 ... U pack_index 1 +// CHECK-NEXT: TypeAliasTemplate 0x{{[^ ]*}} 'B' } // namespace PR56099 diff --git a/clang/test/AST/deduction-guides.cpp b/clang/test/AST/deduction-guides.cpp --- a/clang/test/AST/deduction-guides.cpp +++ b/clang/test/AST/deduction-guides.cpp @@ -67,9 +67,8 @@ // CHECK-NEXT: ElaboratedType {{.*}} 'typename Derived::type_alias' sugar // CHECK-NEXT: TypedefType {{.*}} 'PR48177::Base::type_alias' sugar // CHECK-NEXT: TypeAlias {{.*}} 'type_alias' -// CHECK-NEXT: SubstTemplateTypeParmType {{.*}} 'int' sugar -// CHECK-NEXT: TemplateTypeParmType {{.*}} 'A' -// CHECK-NEXT: TemplateTypeParm {{.*}} 'A' +// CHECK-NEXT: SubstTemplateTypeParmType {{.*}} 'int' sugar class depth 0 index 0 A +// CHECK-NEXT: ClassTemplateSpecialization {{.*}} 'Base' // CHECK-NEXT: BuiltinType {{.*}} 'int' // CHECK: CXXDeductionGuideDecl {{.*}} implicit 'auto (Derived &&, const typename Derived::type_alias &) -> Derived' diff --git a/clang/test/Analysis/cast-value-notes.cpp b/clang/test/Analysis/cast-value-notes.cpp --- a/clang/test/Analysis/cast-value-notes.cpp +++ b/clang/test/Analysis/cast-value-notes.cpp @@ -261,7 +261,7 @@ void evalZeroParamNonNullReturnPointer(const Shape *S) { const auto *C = S->castAs(); - // expected-note@-1 {{'S' is a 'const class clang::Circle *'}} + // expected-note@-1 {{'S' is a 'const Circle *'}} // expected-note@-2 {{'C' initialized here}} (void)(1 / !C); @@ -282,7 +282,7 @@ void evalZeroParamNullReturn(const Shape *S) { const auto &C = S->getAs(); - // expected-note@-1 {{Assuming 'S' is not a 'const class clang::Circle *'}} + // expected-note@-1 {{Assuming 'S' is not a 'const Circle *'}} // expected-note@-2 {{Storing null pointer value}} // expected-note@-3 {{'C' initialized here}} diff --git a/clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/dcl.type.elab/p3.cpp b/clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/dcl.type.elab/p3.cpp --- a/clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/dcl.type.elab/p3.cpp +++ b/clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/dcl.type.elab/p3.cpp @@ -38,8 +38,8 @@ void b1(struct B); void b2(class B); -void b3(union B); // expected-error {{use of 'B' with tag type that does not match previous declaration}} -//void b4(enum B); // this just doesn't parse; you can't template an enum directly +void b3(union B); // expected-error {{use of 'union B' with tag type that does not match previous declaration}} +// void b4(enum B); // this just doesn't parse; you can't template an enum directly void c1(struct B::Member); void c2(class B::Member); diff --git a/clang/test/CXX/temp/temp.deduct.guide/p3.cpp b/clang/test/CXX/temp/temp.deduct.guide/p3.cpp --- a/clang/test/CXX/temp/temp.deduct.guide/p3.cpp +++ b/clang/test/CXX/temp/temp.deduct.guide/p3.cpp @@ -33,7 +33,7 @@ }; A(int) -> int; // expected-error {{deduced type 'int' of deduction guide is not a specialization of template 'A'}} -template A(T) -> B; // expected-error {{deduced type 'B' (aka 'A') of deduction guide is not written as a specialization of template 'A'}} +template A(T)->B; // expected-error {{deduced type 'B' (aka 'A') of deduction guide is not written as a specialization of template 'A'}} template A(T*) -> const A; // expected-error {{deduced type 'const A' of deduction guide is not a specialization of template 'A'}} // A deduction-guide shall be declared in the same scope as the corresponding diff --git a/clang/test/CodeGenCXX/mangle-ms-back-references-pr13207.cpp b/clang/test/CodeGenCXX/mangle-ms-back-references-pr13207.cpp --- a/clang/test/CodeGenCXX/mangle-ms-back-references-pr13207.cpp +++ b/clang/test/CodeGenCXX/mangle-ms-back-references-pr13207.cpp @@ -1,4 +1,4 @@ -// RUN: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 | FileCheck %s +// RUN: %clang_cc1 -fno-resugar -emit-llvm %s -o - -triple=i386-pc-win32 | FileCheck %s template class A {}; @@ -220,6 +220,7 @@ class T20> struct Food {}; +// FIXME: Should implement resugaring cache for this. using B0 = Food; using B1 = Food; using B2 = Food; diff --git a/clang/test/CodeGenCXX/pr29160.cpp b/clang/test/CodeGenCXX/pr29160.cpp --- a/clang/test/CodeGenCXX/pr29160.cpp +++ b/clang/test/CodeGenCXX/pr29160.cpp @@ -1,8 +1,9 @@ -// RUN: %clang_cc1 -std=c++11 -triple i686-linux-gnu %s -o /dev/null -S -emit-llvm +// RUN: %clang_cc1 -std=c++11 -fno-resugar -triple i686-linux-gnu %s -o /dev/null -S -emit-llvm // // This test's failure mode is running ~forever. (For some value of "forever" // that's greater than 25 minutes on my machine) +// FIXME: Should implement resugaring cache for this. template struct Foo { template diff --git a/clang/test/Misc/diag-template-diffing.cpp b/clang/test/Misc/diag-template-diffing.cpp --- a/clang/test/Misc/diag-template-diffing.cpp +++ b/clang/test/Misc/diag-template-diffing.cpp @@ -257,24 +257,21 @@ int k9 = f9(V9()); // CHECK-ELIDE-NOTREE: no matching function for call to 'f9' -// CHECK-ELIDE-NOTREE: candidate function not viable: no known conversion from 'S9<[2 * ...], S9<[2 * ...], double>>' to 'S9<[2 * ...], S9<[2 * ...], const double>>' for 1st argument +// CHECK-ELIDE-NOTREE: candidate function not viable: no known conversion from 'S9<[2 * ...], U9>' to 'S9<[2 * ...], U9>' for 1st argument // CHECK-NOELIDE-NOTREE: no matching function for call to 'f9' -// CHECK-NOELIDE-NOTREE: candidate function not viable: no known conversion from 'S9>' to 'S9>' for 1st argument +// CHECK-NOELIDE-NOTREE: candidate function not viable: no known conversion from 'S9>' to 'S9>' for 1st argument // CHECK-ELIDE-TREE: no matching function for call to 'f9' // CHECK-ELIDE-TREE: candidate function not viable: no known conversion from argument type to parameter type for 1st argument // CHECK-ELIDE-TREE: S9< -// CHECK-ELIDE-TREE: [2 * ...], -// CHECK-ELIDE-TREE: S9< -// CHECK-ELIDE-TREE: [2 * ...], +// CHECK-ELIDE-TREE: [2 * ...], +// CHECK-ELIDE-TREE: U9< // CHECK-ELIDE-TREE: [double != const double]>> // CHECK-NOELIDE-TREE: no matching function for call to 'f9' // CHECK-NOELIDE-TREE: candidate function not viable: no known conversion from argument type to parameter type for 1st argument // CHECK-NOELIDE-TREE: S9< -// CHECK-NOELIDE-TREE: int, -// CHECK-NOELIDE-TREE: char, -// CHECK-NOELIDE-TREE: S9< -// CHECK-NOELIDE-TREE: int, -// CHECK-NOELIDE-TREE: char, +// CHECK-NOELIDE-TREE: int, +// CHECK-NOELIDE-TREE: char, +// CHECK-NOELIDE-TREE: U9< // CHECK-NOELIDE-TREE: [double != const double]>> template class class_types {}; diff --git a/clang/test/Sema/Resugar/resugar-expr.cpp b/clang/test/Sema/Resugar/resugar-expr.cpp new file mode 100644 --- /dev/null +++ b/clang/test/Sema/Resugar/resugar-expr.cpp @@ -0,0 +1,223 @@ +// RUN: %clang_cc1 -std=c++2b -fsyntax-only -verify=Y %s +// RUN: %clang_cc1 -std=c++2b -fsyntax-only -fno-resugar -verify=N %s + +enum class Foo; + +struct bar {}; + +using Int = int; +using Float = float; +using Bar = bar; + +namespace t1 { +template struct A { + static constexpr A1 a = {}; +}; + +Foo x1 = A::a; +// Y-error@-1 {{with an lvalue of type 'const Int' (aka 'const int')}} +// N-error@-2 {{with an lvalue of type 'const int'}} +} // namespace t1 + +namespace t2 { +template struct A { + static constexpr A1 A2::*a = {}; +}; + +Foo x1 = A::a; +// Y-error@-1 {{with an lvalue of type 'Int Bar::*const'}} +// N-error@-2 {{with an lvalue of type 'int bar::*const'}} +} // namespace t2 + +namespace t3 { +template struct A { + template struct B { + static constexpr A1 B1::*a = {}; + }; +}; + +Foo x1 = A::B::a; +// Y-error@-1 {{with an lvalue of type 'Float Bar::*const'}} +// N-error@-2 {{with an lvalue of type 'float bar::*const'}} +} // namespace t3 + +namespace t4 { +template A1 (*a) +(); + +Foo x1 = decltype(a){}(); +// Y-error@-1 {{with an rvalue of type 'Int' (aka 'int')}} +// N-error@-2 {{with an rvalue of type 'int'}} +} // namespace t4 + +namespace t5 { +template struct A { + A1(*a) + (); +}; + +Foo x1 = decltype(A().a){}(); +// Y-error@-1 {{with an rvalue of type 'Int' (aka 'int')}} +// N-error@-2 {{with an rvalue of type 'int'}} +} // namespace t5 + +namespace t6 { +template struct A { A2 A1::*f(); }; + +using M = int; +using N = int; + +struct B {}; +using X = B; +using Y = B; + +auto a = &A::f; +Foo x1 = a; +// Y-error@-1 {{with an lvalue of type 'M X::*(A::*)()'}} +// N-error@-2 {{with an lvalue of type 'int t6::B::*(A::*)()'}} + +A b; +Foo x2 = (b.*a)(); +// Y-error@-1 {{with an rvalue of type 'M X::*'}} +// N-error@-2 {{with an rvalue of type 'int t6::B::*'}} + +Foo x3 = decltype((b.*a)()){}; +// Y-error@-1 {{with an rvalue of type 'decltype((b .* a)())' (aka 'M X::*')}} +// N-error@-2 {{with an rvalue of type 'decltype((b .* a)())' (aka 'int t6::B::*')}} +} // namespace t6 + +namespace t7 { +template struct A { A1 a; }; +auto [a] = A{}; + +Foo x1 = a; +// Y-error@-1 {{with an lvalue of type 'Int' (aka 'int')}} +// N-error@-2 {{with an lvalue of type 'int'}} +} // namespace t7 + +namespace t8 { +template struct A { + template static constexpr B1 (*b)(A1) = nullptr; +}; + +Foo x1 = A::b; +// Y-error@-1 {{with an lvalue of type 'Int (*const)(Float)' (aka 'int (*const)(float)')}} +// N-error@-2 {{with an lvalue of type 'int (*const)(float)'}} +} // namespace t8 + +namespace t9 { +template struct A { + template static constexpr auto b = (B1(*)(A1)){}; +}; + +Foo x1 = A::b; +// Y-error@-1 {{with an lvalue of type 'Int (*const)(Float)' (aka 'int (*const)(float)'}} +// N-error@-2 {{with an lvalue of type 'int (*const)(float)'}} +} // namespace t9 + +namespace t10 { +template struct A { + template static constexpr A1 (*m)(B1) = nullptr; +}; + +Foo x1 = A().template m; +// Y-error@-1 {{with an lvalue of type 'Int (*const)(Float)' (aka 'int (*const)(float)'}} +// N-error@-2 {{with an lvalue of type 'int (*const)(float)'}} +} // namespace t10 + +namespace t11 { +template A1 a; +template A2 a; + +Foo x1 = a; +// Y-error@-1 {{with an lvalue of type 'Int' (aka 'int')}} +// N-error@-2 {{with an lvalue of type 'int'}} + +Foo x2 = a; +// Y-error@-1 {{with an lvalue of type 'Float' (aka 'float'}} +// N-error@-2 {{with an lvalue of type 'float'}} +} // namespace t11 + +namespace t12 { +template struct A { A1 foo(); }; + +Foo x1 = A().foo(); +// Y-error@-1 {{with an rvalue of type 'Int' (aka 'int')}} +// N-error@-2 {{with an rvalue of type 'int'}} +} // namespace t12 + +namespace t13 { +template struct A { + auto foo() { return A1(); }; +}; + +Foo x1 = A().foo(); +// Y-error@-1 {{with an rvalue of type 'Int' (aka 'int')}} +// N-error@-2 {{with an rvalue of type 'int'}} +} // namespace t13 + +namespace t14 { +template struct A { + template auto foo() -> A1 (*)(B1); +}; + +Foo x1 = A().template foo(); +// Y-error@-1 {{with an rvalue of type 'Int (*)(Float)' (aka 'int (*)(float)'}} +// N-error@-2 {{with an rvalue of type 'int (*)(float)'}} +} // namespace t14 + +namespace t15 { +template struct A { + static auto foo() -> A1; +}; + +Foo x1 = A().foo(); +// Y-error@-1 {{with an rvalue of type 'Int' (aka 'int')}} +// N-error@-2 {{with an rvalue of type 'int'}} +} // namespace t15 + +namespace t16 { +template struct A { + template static auto foo() -> A1 (*)(B1); +}; + +Foo x1 = A().template foo(); +// Y-error@-1 {{with an rvalue of type 'Int (*)(float)'}} // FIXME +// N-error@-2 {{with an rvalue of type 'int (*)(float)'}} + +Foo x2 = A::template foo(); +// Y-error@-1 {{with an rvalue of type 'Int (*)(float)'}} // FIXME +// N-error@-2 {{with an rvalue of type 'int (*)(float)'}} +} // namespace t16 + +namespace t17 { +template struct A { + A1 m; +}; + +Foo x1 = A().m; +// Y-error@-1 {{with an rvalue of type 'Int' (aka 'int')}} +// N-error@-2 {{with an rvalue of type 'int'}} +} // namespace t17 + +namespace t18 { +template struct A { + static A1 m; +}; + +Foo x1 = A().m; +// Y-error@-1 {{with an lvalue of type 'Int' (aka 'int')}} +// N-error@-2 {{with an lvalue of type 'int'}} +} // namespace t18 + +namespace t19 { +template struct A { + struct { + A1 m; + }; +}; + +Foo x1 = A().m; +// Y-error@-1 {{with an rvalue of type 'Int' (aka 'int')}} +// N-error@-2 {{with an rvalue of type 'int'}} +} // namespace t19 diff --git a/clang/test/Sema/Resugar/resugar-types.cpp b/clang/test/Sema/Resugar/resugar-types.cpp new file mode 100644 --- /dev/null +++ b/clang/test/Sema/Resugar/resugar-types.cpp @@ -0,0 +1,186 @@ +// RUN: %clang_cc1 -std=c++2b -verify %s +// expected-no-diagnostics + +static constexpr int alignment = 64; // Suitable large alignment. + +struct Baz {}; +using Bar [[gnu::aligned(alignment)]] = Baz; +using Int [[gnu::aligned(alignment)]] = int; + +#define TEST(X) static_assert(alignof(X) == alignment) +#define TEST_NOT(X) static_assert(alignof(X) != alignment) + +// Sanity checks. +TEST_NOT(Baz); +TEST(Bar); + +namespace t1 { +template struct foo { using type = T; }; +template struct foo { using type = U; }; + +TEST(typename foo::type); +TEST(typename foo::type); +} // namespace t1 + +namespace t2 { +template struct foo1 { using type = T; }; +template struct foo2 { using type = typename foo1<1, T>::type; }; +TEST(typename foo2::type); +} // namespace t2 + +namespace t3 { +template struct foo1 { + template struct foo2 { using type1 = T; }; + using type2 = typename foo2<1, int>::type1; +}; +TEST(typename foo1::type2); +} // namespace t3 + +namespace t4 { +template struct foo { + template using type1 = T; + using type2 = type1; +}; +TEST(typename foo::type2); +} // namespace t4 + +namespace t5 { +template struct foo { + template using type1 = U; + using type2 = type1<1, T>; +}; +TEST(typename foo::type2); +} // namespace t5 + +namespace t6 { +template struct foo1 { + template struct foo2 { using type = U; }; + using type2 = typename foo2<1, T>::type; +}; +TEST(typename foo1::type2); +}; // namespace t6 + +namespace t7 { +template struct foo { + template using type1 = U; +}; +using type2 = typename foo::template type1<1, Bar>; +TEST(type2); +} // namespace t7 + +namespace t8 { +template struct foo { + using type1 = T; +}; +template using type2 = T; +using type3 = typename type2, int>::type1; +TEST(type3); +} // namespace t8 + +namespace t9 { +template struct Y { + using type1 = A; + using type2 = B; +}; +template using Z = Y; +template struct foo { + template using apply = Z; +}; +using T1 = foo::apply; +TEST_NOT(T1::type1); +TEST(T1::type2); + +using T2 = foo::apply; +TEST(T2::type1); +TEST_NOT(T2::type2); +} // namespace t9 + +namespace t10 { +template struct Y { + using type1 = A1; + using type2 = A2; +}; +template using Z = Y; +template struct foo { + template using bind = Z; +}; +using T1 = foo::bind; +TEST_NOT(T1::type1); +TEST(T1::type2); + +using T2 = foo::bind; +TEST(T2::type1); +TEST_NOT(T2::type2); +} // namespace t10 + +namespace t11 { +template struct A { using type1 = A2; }; +TEST(A::type1); +} // namespace t11 + +namespace t12 { +template struct W { + template class TT> + struct X { + using type1 = TT; + }; +}; + +template struct Y { + using type2 = Y2; + using type3 = Y3; +}; + +using T1 = typename W::X::type1; +TEST_NOT(typename T1::type2); // FIXME +TEST(typename T1::type3); +} // namespace t12 + +namespace t13 { +template