44#include "llvm/ADT/APInt.h"
45#include "llvm/ADT/APSInt.h"
46#include "llvm/ADT/ArrayRef.h"
47#include "llvm/ADT/DenseMap.h"
48#include "llvm/ADT/FoldingSet.h"
49#include "llvm/ADT/SmallBitVector.h"
50#include "llvm/ADT/SmallPtrSet.h"
51#include "llvm/ADT/SmallVector.h"
52#include "llvm/Support/Casting.h"
53#include "llvm/Support/Compiler.h"
54#include "llvm/Support/ErrorHandling.h"
112using namespace clang;
118 if (Y.getBitWidth() >
X.getBitWidth())
119 X =
X.extend(Y.getBitWidth());
120 else if (Y.getBitWidth() <
X.getBitWidth())
121 Y = Y.extend(
X.getBitWidth());
124 if (
X.isSigned() != Y.isSigned()) {
126 if ((Y.isSigned() && Y.isNegative()) || (
X.isSigned() &&
X.isNegative()))
149 bool NumberOfArgumentsMustMatch,
154 bool OnlyDeduced,
unsigned Depth,
155 llvm::SmallBitVector &
Used);
158 bool OnlyDeduced,
unsigned Level,
159 llvm::SmallBitVector &Deduced);
169 if (
const auto *IC = dyn_cast<ImplicitCastExpr>(
E))
170 E = IC->getSubExpr();
171 else if (
const auto *CE = dyn_cast<ConstantExpr>(
E))
172 E = CE->getSubExpr();
173 else if (
const auto *Subst = dyn_cast<SubstNonTypeTemplateParmExpr>(
E))
174 E = Subst->getReplacement();
175 else if (
const auto *CCE = dyn_cast<CXXConstructExpr>(
E)) {
177 if (CCE->getParenOrBraceRange().isValid())
180 assert(CCE->getNumArgs() >= 1 &&
"implicit construct expr should have 1 arg");
186 if (
const auto *DRE = dyn_cast<DeclRefExpr>(
E))
187 if (
const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
188 if (NTTP->getDepth() == Depth)
203 X = NX->getUnderlyingDecl();
204 if (
NamedDecl *NY = dyn_cast<NamedDecl>(Y))
205 Y = NY->getUnderlyingDecl();
218 bool AggregateCandidateDeduction =
false) {
231 QualType XType =
X.getNonTypeTemplateArgumentType();
239 switch (
X.getKind()) {
241 llvm_unreachable(
"Non-deduced template arguments handled above");
248 X.wasDeducedFromArrayBound() ||
254 return X.wasDeducedFromArrayBound() ? Y :
X;
268 return X.wasDeducedFromArrayBound() ? Y :
X;
277 X.structurallyEquals(Y)))
305 llvm::FoldingSetNodeID ID1, ID2;
306 X.getAsExpr()->Profile(ID1, Context,
true);
309 return X.wasDeducedFromArrayBound() ? Y :
X;
316 assert(!
X.wasDeducedFromArrayBound());
329 X.getParamTypeForDecl());
366 (!AggregateCandidateDeduction &&
X.pack_size() != Y.
pack_size()))
373 XA != XAEnd; ++XA, ++YA) {
378 if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
380 NewPack.push_back(Merged);
382 NewPack.push_back(*XA);
392 llvm_unreachable(
"Invalid TemplateArgument Kind!");
405 "deducing non-type template argument with wrong depth");
409 if (Result.isNull()) {
413 return TemplateDeductionResult::Inconsistent;
418 return TemplateDeductionResult::Success;
425 return TemplateDeductionResult::Success;
430 if (
auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
431 ParamType = Expansion->getPattern();
445 S, TemplateParams, ParamType, ValueType, Info, Deduced,
458 S, TemplateParams, NTTP,
460 DeducedFromArrayBound),
461 ValueType, Info, Deduced);
519 case Decl::TemplateTypeParm: {
520 auto *
T = cast<TemplateTypeParmDecl>(A);
523 T->getDepth(),
T->getIndex(),
T->getIdentifier(),
524 T->wasDeclaredWithTypename(),
T->isParameterPack(),
525 T->hasTypeConstraint());
526 R->setDefaultArgument(
529 if (R->hasTypeConstraint()) {
530 auto *
C = R->getTypeConstraint();
531 R->setTypeConstraint(
C->getConceptReference(),
532 C->getImmediatelyDeclaredConstraint());
536 case Decl::NonTypeTemplateParm: {
537 auto *
T = cast<NonTypeTemplateParmDecl>(A);
540 T->getDepth(),
T->getIndex(),
T->getIdentifier(),
T->getType(),
541 T->isParameterPack(),
T->getTypeSourceInfo());
542 R->setDefaultArgument(S.
Context,
546 if (
auto *PTC =
T->getPlaceholderTypeConstraint())
547 R->setPlaceholderTypeConstraint(PTC);
550 case Decl::TemplateTemplateParm: {
551 auto *
T = cast<TemplateTemplateParmDecl>(A);
554 T->getIndex(),
T->isParameterPack(),
T->getIdentifier(),
555 T->wasDeclaredWithTypename(),
T->getTemplateParameters());
556 R->setDefaultArgument(
562 llvm_unreachable(
"Unexpected Decl Kind");
576 return TemplateDeductionResult::Success;
579 if (
auto *TempParam = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
582 return TemplateDeductionResult::Success;
589 if (
auto *TempArg = dyn_cast_or_null<TemplateTemplateParmDecl>(
591 assert(!TempArg->isExpandedParameterPack());
594 if (DefaultArguments.size() != 0) {
595 assert(DefaultArguments.size() <= As->
size());
597 for (
unsigned I = 0; I < DefaultArguments.size(); ++I)
599 DefaultArguments[I]);
600 for (
unsigned I = DefaultArguments.size(); I < As->size(); ++I)
605 auto *TPL = TemplateParameterList::Create(
611 TempArg->getDepth(), TempArg->getPosition(),
612 TempArg->isParameterPack(), TempArg->getIdentifier(),
613 TempArg->wasDeclaredWithTypename(), TPL)));
618 Deduced[TempParam->getIndex()],
620 if (Result.isNull()) {
621 Info.
Param = TempParam;
622 Info.
FirstArg = Deduced[TempParam->getIndex()];
624 return TemplateDeductionResult::Inconsistent;
627 Deduced[TempParam->getIndex()] = Result;
628 return TemplateDeductionResult::Success;
633 return TemplateDeductionResult::Success;
638 return TemplateDeductionResult::NonDeducedMismatch;
664 assert(TST &&
"Expected a TemplateSpecializationType");
678 UP = IP->getInjectedSpecializationType();
686 return TemplateDeductionResult::Success;
693 ->template_arguments();
696 std::optional<NestedNameSpecifier *> NNS;
699 NNS = Elaborated->getQualifier();
701 UA = Injected->getInjectedSpecializationType();
712 return TemplateDeductionResult::Success;
719 ->template_arguments();
724 Result != TemplateDeductionResult::Success)
740 RA ? dyn_cast<ClassTemplateSpecializationDecl>(RA->getDecl()) :
nullptr;
744 return TemplateDeductionResult::NonDeducedMismatch;
750 *NNS,
false,
TemplateName(SA->getSpecializedTemplate()));
755 SA->getTemplateArgs().asArray(), Deduced);
756 Result != TemplateDeductionResult::Success)
761 SA->getTemplateArgs().asArray(), Info, Deduced,
769 case Type::TypeOfExpr:
771 case Type::DependentName:
773 case Type::PackIndexing:
774 case Type::UnresolvedUsing:
775 case Type::TemplateTypeParm:
779 case Type::ConstantArray:
780 case Type::IncompleteArray:
781 case Type::VariableArray:
782 case Type::DependentSizedArray:
784 cast<ArrayType>(
T)->getElementType().getTypePtr());
833class PackDeductionScope {
839 bool DeducePackIfNotAlreadyDeduced =
false)
840 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info),
841 DeducePackIfNotAlreadyDeduced(DeducePackIfNotAlreadyDeduced){
842 unsigned NumNamedPacks = addPacks(Pattern);
843 finishConstruction(NumNamedPacks);
850 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
852 finishConstruction(1);
856 void addPack(
unsigned Index) {
859 DeducedFromEarlierParameter = !Deduced[Index].isNull();
861 Pack.Saved = Deduced[Index];
867 if (std::optional<unsigned> ExpandedPackExpansions =
869 FixedNumExpansions = ExpandedPackExpansions;
871 Packs.push_back(Pack);
877 llvm::SmallBitVector SawIndices(TemplateParams->size());
880 auto AddPack = [&](
unsigned Index) {
881 if (SawIndices[Index])
883 SawIndices[Index] =
true;
890 if (
auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
891 TemplateParams->getParam(Index))) {
892 if (!NTTP->isExpandedParameterPack())
893 if (
auto *Expansion = dyn_cast<PackExpansionType>(NTTP->getType()))
894 ExtraDeductions.push_back(Expansion->getPattern());
903 for (
unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
904 unsigned Depth, Index;
906 if (Depth == Info.getDeducedDepth())
913 assert(!Packs.empty() &&
"Pack expansion without unexpanded packs?");
915 unsigned NumNamedPacks = Packs.size();
919 while (!ExtraDeductions.empty())
920 Collect(ExtraDeductions.pop_back_val());
922 return NumNamedPacks;
925 void finishConstruction(
unsigned NumNamedPacks) {
928 unsigned NumPartialPackArgs = 0;
929 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
931 if (
auto *Partial =
Scope->getPartiallySubstitutedPack(
932 &PartialPackArgs, &NumPartialPackArgs))
938 bool IsExpanded =
true;
939 for (
unsigned I = 0; I != NumNamedPacks; ++I) {
940 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
942 IsPartiallyExpanded =
false;
945 if (PartialPackDepthIndex ==
946 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
947 IsPartiallyExpanded =
true;
955 if (IsPartiallyExpanded)
956 PackElements += NumPartialPackArgs;
957 else if (IsExpanded && FixedNumExpansions)
958 PackElements += *FixedNumExpansions;
960 for (
auto &Pack : Packs) {
961 if (Info.PendingDeducedPacks.size() > Pack.Index)
962 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
964 Info.PendingDeducedPacks.resize(Pack.Index + 1);
965 Info.PendingDeducedPacks[Pack.Index] = &Pack;
967 if (PartialPackDepthIndex ==
968 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
969 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
978 if (!IsPartiallyExpanded)
979 Deduced[Pack.Index] = Pack.New[PackElements];
985 ~PackDeductionScope() {
986 for (
auto &Pack : Packs)
987 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
991 std::optional<unsigned> getSavedPackSizeIfAllEqual()
const {
992 unsigned PackSize = Packs[0].Saved.pack_size();
994 if (std::all_of(Packs.begin() + 1, Packs.end(), [&PackSize](
const auto &
P) {
995 return P.Saved.pack_size() == PackSize;
1003 bool isDeducedFromEarlierParameter()
const {
1004 return DeducedFromEarlierParameter;
1009 bool isPartiallyExpanded() {
return IsPartiallyExpanded; }
1014 bool hasFixedArity() {
return FixedNumExpansions.has_value(); }
1019 bool hasNextElement() {
1020 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
1024 void nextPackElement() {
1028 for (
auto &Pack : Packs) {
1030 if (!Pack.New.empty() || !DeducedArg.
isNull()) {
1031 while (Pack.New.size() < PackElements)
1033 if (Pack.New.size() == PackElements)
1034 Pack.New.push_back(DeducedArg);
1036 Pack.New[PackElements] = DeducedArg;
1037 DeducedArg = Pack.New.size() > PackElements + 1
1038 ? Pack.New[PackElements + 1]
1051 for (
auto &Pack : Packs) {
1053 Deduced[Pack.Index] = Pack.Saved;
1068 Pack.New.resize(PackElements);
1072 if (Pack.New.empty()) {
1078 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
1086 Pack.New[0].wasDeducedFromArrayBound());
1092 if (Pack.Outer->DeferredDeduction.isNull()) {
1095 Pack.Outer->DeferredDeduction = NewPack;
1098 Loc = &Pack.Outer->DeferredDeduction;
1100 Loc = &Deduced[Pack.Index];
1106 S.
Context, OldPack, NewPack, DeducePackIfNotAlreadyDeduced);
1108 Info.AggregateDeductionCandidateHasMismatchedArity =
1114 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
1116 NewPack = Pack.DeferredDeduction;
1120 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
1121 if (Result.isNull()) {
1123 Info.FirstArg = OldPack;
1124 Info.SecondArg = NewPack;
1125 return TemplateDeductionResult::Inconsistent;
1131 if (*Expansions != PackElements) {
1133 Info.FirstArg = Result;
1134 return TemplateDeductionResult::IncompletePack;
1141 return TemplateDeductionResult::Success;
1149 unsigned PackElements = 0;
1150 bool IsPartiallyExpanded =
false;
1151 bool DeducePackIfNotAlreadyDeduced =
false;
1152 bool DeducedFromEarlierParameter =
false;
1154 std::optional<unsigned> FixedNumExpansions;
1193 const QualType *Params,
unsigned NumParams,
1194 const QualType *Args,
unsigned NumArgs,
1207 = dyn_cast<PackExpansionType>(Params[
ParamIdx]);
1212 if (ArgIdx >= NumArgs)
1213 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1215 if (isa<PackExpansionType>(Args[ArgIdx])) {
1220 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1224 S, TemplateParams, Params[
ParamIdx].getUnqualifiedType(),
1225 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, TDF,
1228 Result != TemplateDeductionResult::Success)
1243 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
1247 if (
ParamIdx + 1 == NumParams || PackScope.hasFixedArity()) {
1248 for (; ArgIdx < NumArgs && PackScope.hasNextElement(); ++ArgIdx) {
1254 Result != TemplateDeductionResult::Success)
1257 PackScope.nextPackElement();
1278 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1279 for (
unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs;
1281 PackScope.nextPackElement();
1287 if (
auto Result = PackScope.finish();
1288 Result != TemplateDeductionResult::Success)
1299 isa<PackExpansionType>(Args[ArgIdx]))
1300 return TemplateDeductionResult::Success;
1303 if (ArgIdx < NumArgs)
1304 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1306 return TemplateDeductionResult::Success;
1318 if (ParamQs == ArgQs)
1362 if (!Guide || !Guide->isImplicit())
1364 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1374 if (ParamRef->getPointeeType().getQualifiers())
1377 return TypeParm && TypeParm->
getIndex() >= FirstInnerIndex;
1435 assert(
T->
isRecordType() &&
"Base class that isn't a record?");
1437 ToVisit.push_back(
T);
1446 while (!ToVisit.empty()) {
1447 QualType NextT = ToVisit.pop_back_val();
1453 S, TemplateParams,
P, NextT, BaseInfo, DeducedCopy);
1459 Matches.insert({RD, DeducedCopy});
1470 if (Matches.size() > 1) {
1472 for (
const auto &Match : Matches)
1473 AddBases(Match.first);
1477 while (Matches.size() > 1 && !ToVisit.empty()) {
1478 const CXXRecordDecl *RD = ToVisit.pop_back_val()->getAsCXXRecordDecl();
1487 if (Matches.empty())
1489 if (Matches.size() > 1)
1492 std::swap(Matches.front().second, Deduced);
1528 if (
const auto *AExp = dyn_cast<PackExpansionType>(A))
1529 A = AExp->getPattern();
1610 TDF &= ~TDF_TopLevelParameterTypeList;
1613 P =
P->getPointeeType();
1630 unsigned Index = TTP->getIndex();
1645 Info.
Param = cast<TemplateTypeParmDecl>(TemplateParams->
getParam(Index));
1657 "saw template type parameter with wrong depth");
1659 "Unresolved overloaded function");
1679 Info.
Param = cast<TemplateTypeParmDecl>(TemplateParams->
getParam(Index));
1699 Info.
Param = cast<TemplateTypeParmDecl>(TemplateParams->
getParam(Index));
1744 if (!
P->isDependentType()) {
1760 switch (
P.getCanonicalType()->getTypeClass()) {
1762#define NON_CANONICAL_TYPE(Class, Base) \
1763 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1764#define TYPE(Class, Base)
1765#include "clang/AST/TypeNodes.inc"
1767 case Type::TemplateTypeParm:
1768 case Type::SubstTemplateTypeParmPack:
1769 llvm_unreachable(
"Type nodes handled above");
1777 if (
P->isDependentType())
1781 case Type::VariableArray:
1783 case Type::FunctionNoProto:
1786 case Type::ObjCObject:
1787 case Type::ObjCInterface:
1788 case Type::ObjCObjectPointer:
1798 case Type::Complex: {
1803 S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
1808 case Type::Atomic: {
1813 S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
1818 case Type::Pointer: {
1829 PointeeType, Info, Deduced,
1834 case Type::LValueReference: {
1841 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1846 case Type::RValueReference: {
1853 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1858 case Type::IncompleteArray: {
1864 assert(IAP &&
"Template parameter not of incomplete array type");
1867 S, TemplateParams, IAP->getElementType(), IAA->getElementType(), Info,
1872 case Type::ConstantArray: {
1876 if (!CAA || CAA->getSize() != CAP->getSize())
1880 S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
1885 case Type::DependentSizedArray: {
1894 S, TemplateParams, DAP->getElementType(), AA->getElementType(),
1908 "saw non-type template parameter with wrong depth");
1909 if (
const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
1910 llvm::APSInt Size(CAA->getSize());
1913 true, Info, Deduced);
1915 if (
const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
1916 if (DAA->getSizeExpr())
1918 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info, Deduced);
1927 case Type::FunctionProto: {
1933 if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
1934 FPP->getRefQualifier() != FPA->getRefQualifier() ||
1935 FPP->isVariadic() != FPA->isVariadic())
1940 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
1949 S, TemplateParams, FPP->param_type_begin(), FPP->getNumParams(),
1950 FPA->param_type_begin(), FPA->getNumParams(), Info, Deduced,
1961 Expr *NoexceptExpr = FPP->getNoexceptExpr();
1966 "saw non-type template parameter with wrong depth");
1968 llvm::APSInt Noexcept(1);
1969 switch (FPA->canThrow()) {
1979 true, Info, Deduced);
1982 if (
Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
1984 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
1997 case Type::InjectedClassName:
2006 case Type::TemplateSpecialization: {
2032 Deduced = DeducedOrig;
2050 case Type::MemberPointer: {
2067 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF);
2071 S, TemplateParams,
QualType(MPP->getClass(), 0),
2072 QualType(MPA->getClass(), 0), Info, Deduced, SubTDF);
2080 case Type::BlockPointer: {
2086 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
2093 case Type::ExtVector: {
2098 if (VP->getNumElements() != VA->getNumElements())
2100 ElementType = VA->getElementType();
2105 ElementType = VA->getElementType();
2111 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
2115 case Type::DependentVector: {
2121 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2122 Info, Deduced, TDF);
2133 ArgSize = VA->getNumElements();
2145 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2146 Info, Deduced, TDF);
2157 VA->getSizeExpr(), Info, Deduced);
2166 case Type::DependentSizedExtVector: {
2172 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2173 Info, Deduced, TDF);
2184 ArgSize = VA->getNumElements();
2196 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2197 Info, Deduced, TDF);
2208 VA->getSizeExpr(), Info, Deduced);
2218 case Type::ConstantMatrix: {
2225 if (MP->getNumRows() != MA->getNumRows() ||
2226 MP->getNumColumns() != MA->getNumColumns()) {
2231 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2235 case Type::DependentSizedMatrix: {
2244 Info, Deduced, TDF);
2249 auto DeduceMatrixArg =
2250 [&S, &Info, &Deduced, &TemplateParams](
2254 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2255 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
2256 if (!ParamExpr->isValueDependent()) {
2257 std::optional<llvm::APSInt> ParamConst =
2258 ParamExpr->getIntegerConstantExpr(S.
Context);
2263 if ((ACM->*GetArgDimension)() == *ParamConst)
2268 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2269 if (std::optional<llvm::APSInt> ArgConst =
2271 if (*ArgConst == *ParamConst)
2282 llvm::APSInt ArgConst(
2284 ArgConst = (ACM->*GetArgDimension)();
2287 true, Info, Deduced);
2291 (ADM->*GetArgDimensionExpr)(),
2295 if (
auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
2301 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2309 case Type::DependentAddressSpace: {
2315 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2316 Info, Deduced, TDF);
2327 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info, Deduced);
2337 S, TemplateParams, ASP->getPointeeType(),
2350 true, Info, Deduced);
2355 case Type::DependentBitInt: {
2359 if (IP->isUnsigned() != IA->isUnsigned())
2368 ArgSize = IA->getNumBits();
2376 if (IP->isUnsigned() != IA->isUnsigned())
2384 case Type::TypeOfExpr:
2386 case Type::DependentName:
2387 case Type::UnresolvedUsing:
2388 case Type::Decltype:
2389 case Type::UnaryTransform:
2390 case Type::DeducedTemplateSpecialization:
2391 case Type::DependentTemplateSpecialization:
2392 case Type::PackExpansion:
2394 case Type::ArrayParameter:
2398 case Type::PackIndexing: {
2408 llvm_unreachable(
"Invalid Type Class!");
2422 switch (
P.getKind()) {
2424 llvm_unreachable(
"Null template argument in parameter list");
2429 S, TemplateParams,
P.getAsType(), A.
getAsType(), Info, Deduced, 0);
2444 llvm_unreachable(
"caller should handle pack expansions");
2511 llvm_unreachable(
"Unknown template argument kind");
2517 llvm_unreachable(
"Argument packs should be expanded by the caller!");
2520 llvm_unreachable(
"Invalid TemplateArgument Kind!");
2533 if (ArgIdx == Args.size())
2540 assert(ArgIdx == Args.size() - 1 &&
"Pack not at the end of argument list?");
2543 return ArgIdx < Args.size();
2549 bool FoundPackExpansion =
false;
2550 for (
const auto &A : Args) {
2551 if (FoundPackExpansion)
2559 if (A.isPackExpansion())
2560 FoundPackExpansion =
true;
2573 if (
PackFold == PackFold::ArgumentToParameter)
2589 if (!
P.isPackExpansion()) {
2594 return NumberOfArgumentsMustMatch
2601 if (As[ArgIdx].isPackExpansion())
2606 if (
PackFold == PackFold::ArgumentToParameter)
2628 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2634 PackScope.hasNextElement();
2637 if (
PackFold == PackFold::ArgumentToParameter)
2645 PackScope.nextPackElement();
2650 if (
auto Result = PackScope.finish();
2662 bool NumberOfArgumentsMustMatch) {
2663 return ::DeduceTemplateArguments(*
this, TemplateParams, Ps, As, Info, Deduced,
2664 NumberOfArgumentsMustMatch);
2672 bool PackExpansionMatchesPack =
false) {
2675 if (PackExpansionMatchesPack &&
X.isPackExpansion() && !Y.
isPackExpansion())
2676 X =
X.getPackExpansionPattern();
2681 switch (
X.getKind()) {
2683 llvm_unreachable(
"Comparing NULL template argument");
2706 return X.structurallyEquals(Y);
2709 llvm::FoldingSetNodeID XID, YID;
2710 X.getAsExpr()->Profile(XID, Context,
true);
2716 unsigned PackIterationSize =
X.pack_size();
2725 bool XHasMoreArg =
X.pack_size() > Y.
pack_size();
2726 if (!(XHasMoreArg &&
X.pack_elements().back().isPackExpansion()) &&
2727 !(!XHasMoreArg && Y.
pack_elements().back().isPackExpansion()))
2736 for (
unsigned i = 0; i < PackIterationSize; ++i)
2738 PackExpansionMatchesPack))
2744 llvm_unreachable(
"Invalid TemplateArgument Kind!");
2753 llvm_unreachable(
"Can't get a NULL template argument here");
2788 Builder.MakeTrivial(
Context, DTN->getQualifier(),
Loc);
2791 Builder.MakeTrivial(
Context, QTN->getQualifier(),
Loc);
2808 llvm_unreachable(
"Invalid TemplateArgument Kind!");
2826 unsigned ArgumentPackIndex) {
2848 CanonicalPackedArgsBuilder;
2856 "deduced nested pack");
2863 diag::err_template_arg_deduced_incomplete_pack)
2867 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
2871 SugaredPackedArgsBuilder.push_back(SugaredOutput.pop_back_val());
2872 CanonicalPackedArgsBuilder.push_back(CanonicalOutput.pop_back_val());
2877 if (SugaredPackedArgsBuilder.empty()) {
2882 if (
auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2884 NTTP, SugaredOutput,
2887 S.
SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2888 NTTP->getDeclName()).isNull())
2890 }
else if (
auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2901 SugaredOutput.push_back(
2904 S.
Context, CanonicalPackedArgsBuilder));
2908 return ConvertArg(Arg, 0);
2914template <
typename TemplateDeclT>
2916 Sema &S, TemplateDeclT *Template,
bool IsDeduced,
2922 unsigned NumAlreadyConverted = 0,
bool PartialOverloading =
false) {
2925 for (
unsigned I = 0, N = TemplateParams->
size(); I != N; ++I) {
2934 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish();
2939 if (!Deduced[I].isNull()) {
2940 if (I < NumAlreadyConverted) {
2945 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2948 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2955 SugaredBuilder.push_back(Deduced[I]);
2956 CanonicalBuilder.push_back(
2965 IsDeduced, SugaredBuilder,
2966 CanonicalBuilder)) {
2979 bool HasDefaultArg =
false;
2982 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2983 isa<VarTemplatePartialSpecializationDecl>(Template));
2992 if (Rec->isLambda())
2993 if (
auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
2995 ThisTypeQuals = Method->getMethodQualifiers();
3003 SugaredBuilder, CanonicalBuilder, HasDefaultArg);
3012 if (PartialOverloading)
break;
3037 if (
auto *DC = dyn_cast<DeclContext>(
D))
3043 static constexpr bool value =
false;
3047 static constexpr bool value =
true;
3051 static constexpr bool value =
true;
3053template <
typename TemplateDeclT>
3068template <
typename TemplateDeclT>
3075 Template->getAssociatedConstraints(AssociatedConstraints);
3077 std::optional<ArrayRef<TemplateArgument>> Innermost;
3081 Innermost = CanonicalDeducedArgs;
3084 Template, Template->getDeclContext(),
false, Innermost,
3108template <
typename T>
3109static std::enable_if_t<IsPartialSpecialization<T>::value,
3112 Sema &S,
T *Partial,
bool IsPartialOrdering,
3128 S, Partial, IsPartialOrdering, Deduced, Info, SugaredBuilder,
3139 Info.
reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3147 auto *Template = Partial->getSpecializedTemplate();
3149 Partial->getTemplateArgsAsWritten();
3160 if (
ParamIdx >= Partial->getTemplateParameters()->size())
3161 ParamIdx = Partial->getTemplateParameters()->size() - 1;
3164 Partial->getTemplateParameters()->getParam(
ParamIdx));
3166 Info.
FirstArg = (*PartialTemplArgInfo)[ArgIdx].getArgument();
3172 CanonicalConvertedInstArgs;
3174 Template, Partial->getLocation(), InstArgs,
false,
3175 SugaredConvertedInstArgs, CanonicalConvertedInstArgs,
3182 for (
unsigned I = 0,
E = TemplateParams->
size(); I !=
E; ++I) {
3185 IsPartialOrdering)) {
3197 CanonicalBuilder, Info);
3225 SugaredBuilder, CanonicalBuilder,
3233 for (
unsigned I = 0,
E = TemplateParams->
size(); I !=
E; ++I) {
3248 CanonicalBuilder, Info);
3273 S, TD,
false, Deduced, Info, SugaredBuilder,
3282 CanonicalBuilder, Info);
3292template <
typename T>
3293static std::enable_if_t<IsPartialSpecialization<T>::value,
3298 if (Partial->isInvalidDecl())
3317 Deduced.resize(Partial->getTemplateParameters()->size());
3319 S, Partial->getTemplateParameters(),
3320 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3336 Result = ::FinishTemplateArgumentDeduction(S, Partial,
3338 TemplateArgs, Deduced, Info);
3347 return ::DeduceTemplateArguments(*
this, Partial, TemplateArgs, Info);
3353 return ::DeduceTemplateArguments(*
this, Partial, TemplateArgs, Info);
3363 if (
const auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
3366 }
else if (
const auto *
AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(TD)) {
3367 PType =
AliasTemplate->getTemplatedDecl()->getUnderlyingType();
3369 assert(
false &&
"Expected a class or alias template");
3388 return DeducedResult;
3401 Result = ::FinishTemplateArgumentDeduction(*this, TD, Deduced, Info);
3410 return Spec->getTemplateName().getAsTemplateDecl() !=
nullptr;
3436 if (ExplicitTemplateArgs.
size() == 0) {
3440 ParamTypes.push_back(
P->getType());
3470 ExplicitTemplateArgs,
true, SugaredBuilder,
3474 unsigned Index = SugaredBuilder.size();
3475 if (Index >= TemplateParams->
size())
3488 CanonicalExplicitArgumentList);
3500 unsigned PartiallySubstitutedPackIndex = -1u;
3501 if (!SugaredBuilder.empty()) {
3504 auto *Param = TemplateParams->
getParam(SugaredBuilder.size() - 1);
3508 if (!Expansions || Arg.
pack_size() < *Expansions) {
3509 PartiallySubstitutedPackIndex = SugaredBuilder.size() - 1;
3518 assert(Proto &&
"Function template does not have a prototype?");
3526 SugaredExplicitArgumentList->
asArray(),
3536 nullptr, ExtParamInfos))
3553 ThisTypeQuals = Method->getMethodQualifiers();
3567 Diag(
Function->getLocation(), diag::err_kern_type_not_void_return)
3578 nullptr, ExtParamInfos))
3602 Deduced.reserve(TemplateParams->
size());
3603 for (
unsigned I = 0, N = SugaredExplicitArgumentList->
size(); I != N; ++I) {
3605 if (I == PartiallySubstitutedPackIndex)
3608 Deduced.push_back(Arg);
3677 if (AQuals == DeducedAQuals) {
3695 bool ObjCLifetimeConversion =
false;
3699 ObjCLifetimeConversion) ||
3745 if (PD->isParameterPack()) {
3746 unsigned NumExpansions =
3748 if (Idx + NumExpansions >
ParamIdx)
3750 Idx += NumExpansions;
3758 llvm_unreachable(
"parameter index would not be produced from template");
3770 return isa<CXXConstructorDecl>(
D)
3771 ? cast<CXXConstructorDecl>(
D)->getExplicitSpecifier()
3772 : cast<CXXConversionDecl>(
D)->getExplicitSpecifier();
3775 isa<CXXConstructorDecl>(
D)
3776 ? cast<CXXConstructorDecl>(
D)->setExplicitSpecifier(ES)
3777 : cast<CXXConversionDecl>(
D)->setExplicitSpecifier(ES);
3788 S, Info.
getLocation(), FunctionTemplate, DeducedArgs,
3809 bool PartialOverloading, llvm::function_ref<
bool()> CheckNonDependent) {
3833 NumExplicitlySpecified, PartialOverloading);
3846 if (CheckNonDependent())
3854 Info.
reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3892 CanonicalDeducedArgumentList &&
3912 if (!PartialOverloading ||
3913 (CanonicalBuilder.size() ==
3930 if (isa<CXXConstructorDecl, CXXConversionDecl>(
Specialization)) {
3939 if (OriginalCallArgs) {
3944 llvm::SmallDenseMap<std::pair<unsigned, QualType>,
QualType> DeducedATypes;
3945 for (
unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3949 unsigned ExplicitOffset =
3969 if (CacheEntry.
isNull()) {
3978 DeducedA = CacheEntry;
3993 SuppressedDiagnosticsMap::iterator
4008 if (S.
getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
4013 if (Method->isImplicitObjectMemberFunction()) {
4034 bool ParamWasReference,
4043 if (ParamWasReference)
4060 nullptr, FailedTSC))
4101 if (ArgType.
isNull())
continue;
4121 Deduced(TemplateParams->
size());
4124 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF);
4162 assert(Arg &&
"expected a non-null arg expression");
4164 ParamRefType !=
nullptr, FailedTSC);
4172 assert(Arg &&
"expected a non-null arg expression");
4227 (isa<PointerType>(ParamType) &&
4246 bool DecomposedParam,
unsigned ArgIdx,
unsigned TDF,
4271 ElTy = ArrTy->getElementType();
4281 if (isa<DesignatedInitExpr>(
E))
4288 S, TemplateParams, 0, ElTy,
E->
getType(),
4290 OriginalCallArgs,
true, ArgIdx, TDF);
4298 if (
auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
4309 S, TemplateParams, NTTP, llvm::APSInt(Size),
T,
4310 true, Info, Deduced);
4328 bool DecomposedParam,
unsigned ArgIdx,
unsigned TDF,
4331 QualType OrigParamType = ParamType;
4336 S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
4337 ArgClassification, Arg, TDF, FailedTSC))
4341 if (
InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
4343 Deduced, OriginalCallArgs, ArgIdx, TDF);
4351 OriginalCallArgs.push_back(
4354 ArgType, Info, Deduced, TDF);
4361 bool PartialOverloading,
bool AggregateDeductionCandidate,
4368 unsigned NumParams =
Function->getNumParams();
4369 bool HasExplicitObject =
false;
4370 int ExplicitObjectOffset = 0;
4371 if (
Function->hasCXXExplicitFunctionObjectParameter()) {
4372 HasExplicitObject =
true;
4373 ExplicitObjectOffset = 1;
4382 if (Args.size() <
Function->getMinRequiredExplicitArguments() &&
4383 !PartialOverloading)
4386 PartialOverloading)) {
4388 if (Proto->isTemplateVariadic())
4390 else if (!Proto->isVariadic())
4401 unsigned NumExplicitlySpecified = 0;
4402 if (ExplicitTemplateArgs) {
4405 Result = SubstituteExplicitTemplateArguments(
4406 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4412 NumExplicitlySpecified = Deduced.size();
4415 for (
unsigned I = 0; I != NumParams; ++I)
4416 ParamTypes.push_back(
Function->getParamDecl(I)->getType());
4422 auto DeduceCallArgument = [&](
QualType ParamType,
unsigned ArgIdx,
4423 bool ExplicitObjectArgument) {
4431 if (ExplicitObjectArgument) {
4434 *
this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
4435 ObjectClassification,
4436 nullptr, Info, Deduced, OriginalCallArgs,
4442 *
this, TemplateParams, FirstInnerIndex, ParamType,
4443 Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(
getASTContext()),
4444 Args[ArgIdx], Info, Deduced, OriginalCallArgs,
false,
4449 Deduced.resize(TemplateParams->
size());
4451 for (
unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4456 dyn_cast<PackExpansionType>(ParamType);
4457 if (!ParamExpansion) {
4459 if (ArgIdx >= Args.size() && !(HasExplicitObject &&
ParamIdx == 0))
4462 ParamTypesForArgChecking.push_back(ParamType);
4464 if (
ParamIdx == 0 && HasExplicitObject) {
4465 if (
auto Result = DeduceCallArgument(ParamType, 0,
4472 if (
auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4480 bool IsTrailingPack =
ParamIdx + 1 == NumParamTypes;
4483 PackDeductionScope PackScope(*
this, TemplateParams, Deduced, Info,
4485 AggregateDeductionCandidate && IsTrailingPack);
4503 if (IsTrailingPack || PackScope.hasFixedArity()) {
4504 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4505 PackScope.nextPackElement(), ++ArgIdx) {
4506 ParamTypesForArgChecking.push_back(ParamPattern);
4507 if (
auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4516 std::optional<unsigned> NumExpansions =
4518 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4519 for (
unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4521 ParamTypesForArgChecking.push_back(ParamPattern);
4524 PackScope.nextPackElement();
4526 }
else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4527 PackScope.isDeducedFromEarlierParameter()) {
4540 std::optional<unsigned> ArgPosAfterSubstitution =
4541 PackScope.getSavedPackSizeIfAllEqual();
4542 if (!ArgPosAfterSubstitution)
4545 unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4546 for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4547 ParamTypesForArgChecking.push_back(ParamPattern);
4549 DeduceCallArgument(ParamPattern, ArgIdx,
4554 PackScope.nextPackElement();
4561 if (
auto Result = PackScope.finish();
4572 Result = FinishTemplateArgumentDeduction(
4573 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4574 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
4575 ContextRAII SavedContext(*this, CallingCtx);
4576 return CheckNonDependent(ParamTypesForArgChecking);
4584 bool AdjustExceptionSpec) {
4585 if (ArgFunctionType.
isNull())
4586 return ArgFunctionType;
4591 bool Rebuild =
false;
4594 if (EPI.ExtInfo.getCC() != CC) {
4595 EPI.
ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4599 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4600 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4601 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4605 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4607 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4612 return ArgFunctionType;
4622 bool IsAddressOfFunction) {
4634 unsigned NumExplicitlySpecified = 0;
4636 if (ExplicitTemplateArgs) {
4639 Result = SubstituteExplicitTemplateArguments(
4640 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4641 &FunctionType, Info);
4646 NumExplicitlySpecified = Deduced.size();
4652 if (!IsAddressOfFunction)
4661 Deduced.resize(TemplateParams->
size());
4665 bool HasDeducedReturnType =
false;
4667 Function->getReturnType()->getContainedAutoType()) {
4669 HasDeducedReturnType =
true;
4677 *
this, TemplateParams,
FunctionType, ArgFunctionType, Info, Deduced,
4685 Result = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
4686 NumExplicitlySpecified,
4687 Specialization, Info);
4694 if (HasDeducedReturnType && IsAddressOfFunction &&
4715 if (!IsAddressOfFunction) {
4721 if (HasDeducedReturnType) {
4730 if (!ArgFunctionType.
isNull()) {
4732 SpecializationType, ArgFunctionType)
4734 SpecializationType, ArgFunctionType)) {
4755 bool IsReferenceP =
P->isReferenceType();
4762 P = PRef->getPointeeType();
4772 if (!IsReferenceP) {
4774 P =
P.getUnqualifiedType();
4781 assert(!A->
isReferenceType() &&
"Reference types were handled above");
4786 if (
P->isArrayType())
4791 else if (
P->isFunctionType())
4796 P =
P.getUnqualifiedType();
4818 Deduced.resize(TemplateParams->
size());
4847 ParamType, ObjectType, ObjectClassification,
4848 nullptr, Info, Deduced, OriginalCallArgs,
4855 *
this, TemplateParams,
P, A, Info, Deduced, TDF);
4865 Result = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
4866 ConversionSpecialized, Info,