clang 24.0.0git
SemaTemplateDeduction.cpp
Go to the documentation of this file.
1//===- SemaTemplateDeduction.cpp - Template Argument Deduction ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TreeTransform.h"
14#include "TypeLocBuilder.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
29#include "clang/AST/Type.h"
30#include "clang/AST/TypeLoc.h"
34#include "clang/Basic/LLVM.h"
42#include "clang/Sema/Sema.h"
43#include "clang/Sema/Template.h"
45#include "llvm/ADT/APInt.h"
46#include "llvm/ADT/APSInt.h"
47#include "llvm/ADT/ArrayRef.h"
48#include "llvm/ADT/DenseMap.h"
49#include "llvm/ADT/FoldingSet.h"
50#include "llvm/ADT/SmallBitVector.h"
51#include "llvm/ADT/SmallPtrSet.h"
52#include "llvm/ADT/SmallVector.h"
53#include "llvm/Support/Casting.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/Support/ErrorHandling.h"
56#include "llvm/Support/SaveAndRestore.h"
57#include <algorithm>
58#include <cassert>
59#include <optional>
60#include <tuple>
61#include <type_traits>
62#include <utility>
63
64namespace clang {
65
66 /// Various flags that control template argument deduction.
67 ///
68 /// These flags can be bitwise-OR'd together.
70 /// No template argument deduction flags, which indicates the
71 /// strictest results for template argument deduction (as used for, e.g.,
72 /// matching class template partial specializations).
74
75 /// Within template argument deduction from a function call, we are
76 /// matching with a parameter type for which the original parameter was
77 /// a reference.
79
80 /// Within template argument deduction from a function call, we
81 /// are matching in a case where we ignore cv-qualifiers.
83
84 /// Within template argument deduction from a function call,
85 /// we are matching in a case where we can perform template argument
86 /// deduction from a template-id of a derived class of the argument type.
88
89 /// Allow non-dependent types to differ, e.g., when performing
90 /// template argument deduction from a function call where conversions
91 /// may apply.
93
94 /// Whether we are performing template argument deduction for
95 /// parameters and arguments in a top-level template argument
97
98 /// Within template argument deduction from overload resolution per
99 /// C++ [over.over] allow matching function types that are compatible in
100 /// terms of noreturn and default calling convention adjustments, or
101 /// similarly matching a declared template specialization against a
102 /// possible template, per C++ [temp.deduct.decl]. In either case, permit
103 /// deduction where the parameter is a function type that can be converted
104 /// to the argument type.
106
107 /// Within template argument deduction for a conversion function, we are
108 /// matching with an argument type for which the original argument was
109 /// a reference.
111 };
112}
113
114using namespace clang;
115using namespace sema;
116
117/// The kind of PartialOrdering we're performing template argument deduction
118/// for (C++11 [temp.deduct.partial]).
120
122 Sema &S, TemplateParameterList *TemplateParams, QualType Param,
125 PartialOrderingKind POK, bool DeducedFromArrayBound,
126 bool *HasDeducedAnyParam);
127
128/// What directions packs are allowed to match non-packs.
130
137 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
138 PackFold PackFold, bool *HasDeducedAnyParam);
139
142 bool OnlyDeduced, unsigned Depth,
143 llvm::SmallBitVector &Used);
144
146 bool OnlyDeduced, unsigned Level,
147 llvm::SmallBitVector &Deduced);
148
149static const Expr *unwrapExpressionForDeduction(const Expr *E) {
150 // If we are within an alias template, the expression may have undergone
151 // any number of parameter substitutions already.
152 while (true) {
153 if (const auto *IC = dyn_cast<ImplicitCastExpr>(E))
154 E = IC->getSubExpr();
155 else if (const auto *CE = dyn_cast<ConstantExpr>(E))
156 E = CE->getSubExpr();
157 else if (const auto *Subst = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
158 E = Subst->getReplacement();
159 else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) {
160 // Look through implicit copy construction from an lvalue of the same type.
161 if (CCE->getParenOrBraceRange().isValid())
162 break;
163 // Note, there could be default arguments.
164 assert(CCE->getNumArgs() >= 1 && "implicit construct expr should have 1 arg");
165 E = CCE->getArg(0);
166 } else
167 break;
168 }
169 return E;
170}
171
173public:
174 NonTypeOrVarTemplateParmDecl(const NamedDecl *Template) : Template(Template) {
175 assert(
176 !Template || isa<NonTypeTemplateParmDecl>(Template) ||
178 (cast<TemplateTemplateParmDecl>(Template)->templateParameterKind() ==
180 cast<TemplateTemplateParmDecl>(Template)->templateParameterKind() ==
182 }
183
185 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
186 return NTTP->getType();
190 }
191
192 unsigned getDepth() const {
193 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
194 return NTTP->getDepth();
195 return getTemplate()->getDepth();
196 }
197
198 unsigned getIndex() const {
199 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
200 return NTTP->getIndex();
201 return getTemplate()->getIndex();
202 }
203
205 return cast<TemplateTemplateParmDecl>(Template);
206 }
207
209 return cast<NonTypeTemplateParmDecl>(Template);
210 }
211
213 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
214 return const_cast<NonTypeTemplateParmDecl *>(NTTP);
215 return const_cast<TemplateTemplateParmDecl *>(getTemplate());
216 }
217
219 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
220 return NTTP->isExpandedParameterPack();
222 }
223
225 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
226 return NTTP->getLocation();
227 return getTemplate()->getLocation();
228 }
229
230 operator bool() const { return Template; }
231
232private:
233 const NamedDecl *Template;
234};
235
236/// If the given expression is of a form that names a non-type template
237/// parameter, return the declaration of that parameter. A null \p Depth
238/// accepts a parameter at any depth.
241 // If we are within an alias template, the expression may have undergone
242 // any number of parameter substitutions already.
244 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
245 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
246 if (!Depth || NTTP->getDepth() == *Depth)
247 return NTTP;
248
249 // A pack-index-template-name is not deducible.
250 if (const auto *DTI = dyn_cast<DependentTemplateIdExpr>(E))
251 if (!DTI->getTemplateName().getAsPackIndexingTemplate() &&
252 (!Depth || DTI->getParameter()->getDepth() == *Depth))
253 return DTI->getParameter();
254
255 return nullptr;
256}
257
261 getNTTParameterFromExpr(Arg.getAsExpr(), std::nullopt))
262 return NTTP.getType();
264}
265
270
271/// Determine whether two declaration pointers refer to the same
272/// declaration.
273static bool isSameDeclaration(Decl *X, Decl *Y) {
274 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
275 X = NX->getUnderlyingDecl();
276 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
277 Y = NY->getUnderlyingDecl();
278
279 return X->getCanonicalDecl() == Y->getCanonicalDecl();
280}
281
282/// Verify that the given, deduced template arguments are compatible.
283///
284/// \returns The deduced template argument, or a NULL template argument if
285/// the deduced template arguments were incompatible.
290 bool AggregateCandidateDeduction = false) {
291 // We have no deduction for one or both of the arguments; they're compatible.
292 if (X.isNull())
293 return Y;
294 if (Y.isNull())
295 return X;
296
297 // If we have two non-type template argument values deduced for the same
298 // parameter, they must both match the type of the parameter, and thus must
299 // match each other's type. As we're only keeping one of them, we must check
300 // for that now. The exception is that if either was deduced from an array
301 // bound, the type is permitted to differ.
302 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
303 QualType XType = X.getNonTypeTemplateArgumentType();
304 if (!XType.isNull()) {
306 if (YType.isNull() || !Context.hasSameType(XType, YType))
308 }
309 }
310
311 switch (X.getKind()) {
313 llvm_unreachable("Non-deduced template arguments handled above");
314
316 // If two template type arguments have the same type, they're compatible.
317 QualType TX = X.getAsType(), TY = Y.getAsType();
318 if (Y.getKind() == TemplateArgument::Type && Context.hasSameType(TX, TY))
319 return DeducedTemplateArgument(Context.getCommonSugaredType(TX, TY),
320 X.wasDeducedFromArrayBound() ||
322
323 // If one of the two arguments was deduced from an array bound, the other
324 // supersedes it.
325 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
326 return X.wasDeducedFromArrayBound() ? Y : X;
327
328 // The arguments are not compatible.
330 }
331
333 // If we deduced a constant in one case and either a dependent expression or
334 // declaration in another case, keep the integral constant.
335 // If both are integral constants with the same value, keep that value.
339 llvm::APSInt::isSameValue(X.getAsIntegral(), Y.getAsIntegral())))
340 return X.wasDeducedFromArrayBound() ? Y : X;
341
342 // All other combinations are incompatible.
344
346 // If we deduced a value and a dependent expression, keep the value.
349 X.structurallyEquals(Y)))
350 return X;
351
352 // All other combinations are incompatible.
354
357 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
358 return X;
359
360 // All other combinations are incompatible.
362
365 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
367 return X;
368
369 // All other combinations are incompatible.
371
374 return checkDeducedTemplateArguments(Context, Y, X);
375
376 // Compare the expressions for equality
377 llvm::FoldingSetNodeID ID1, ID2;
378 X.getAsExpr()->Profile(ID1, Context, true);
379 Y.getAsExpr()->Profile(ID2, Context, true);
380 if (ID1 == ID2)
381 return X.wasDeducedFromArrayBound() ? Y : X;
382
383 // Differing dependent expressions are incompatible.
385 }
386
388 assert(!X.wasDeducedFromArrayBound());
389
390 // If we deduced a declaration and a dependent expression, keep the
391 // declaration.
393 return X;
394
395 // If we deduced a declaration and an integral constant, keep the
396 // integral constant and whichever type did not come from an array
397 // bound.
400 return TemplateArgument(Context, Y.getAsIntegral(),
401 X.getParamTypeForDecl());
402 return Y;
403 }
404
405 // If we deduced two declarations, make sure that they refer to the
406 // same declaration.
408 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
409 return X;
410
411 // All other combinations are incompatible.
413
415 // If we deduced a null pointer and a dependent expression, keep the
416 // null pointer.
418 return TemplateArgument(Context.getCommonSugaredType(
419 X.getNullPtrType(), Y.getAsExpr()->getType()),
420 true);
421
422 // If we deduced a null pointer and an integral constant, keep the
423 // integral constant.
425 return Y;
426
427 // If we deduced two null pointers, they are the same.
429 return TemplateArgument(
430 Context.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
431 true);
432
433 // All other combinations are incompatible.
435
437 if (Y.getKind() != TemplateArgument::Pack ||
438 (!AggregateCandidateDeduction && X.pack_size() != Y.pack_size()))
440
443 XA = X.pack_begin(),
444 XAEnd = X.pack_end(), YA = Y.pack_begin(), YAEnd = Y.pack_end();
445 XA != XAEnd; ++XA) {
446 if (YA != YAEnd) {
448 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
450 if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
452 NewPack.push_back(Merged);
453 ++YA;
454 } else {
455 NewPack.push_back(*XA);
456 }
457 }
458
460 TemplateArgument::CreatePackCopy(Context, NewPack),
461 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
462 }
463 }
464
465 llvm_unreachable("Invalid TemplateArgument Kind!");
466}
467
468/// Deduce the value of the given non-type template parameter
469/// as the given deduced template argument. All non-type template parameter
470/// deduction is funneled through here.
474 const DeducedTemplateArgument &NewDeduced,
475 QualType ValueType, TemplateDeductionInfo &Info,
476 bool PartialOrdering,
478 bool *HasDeducedAnyParam) {
479 assert(NTTP.getDepth() == Info.getDeducedDepth() &&
480 "deducing non-type template argument with wrong depth");
481
483 S.Context, Deduced[NTTP.getIndex()], NewDeduced);
484 if (Result.isNull()) {
485 Info.Param = NTTP.asTemplateParam();
486 Info.FirstArg = Deduced[NTTP.getIndex()];
487 Info.SecondArg = NewDeduced;
489 }
490 Deduced[NTTP.getIndex()] = Result;
491 if (!S.getLangOpts().CPlusPlus17 && !PartialOrdering)
493
494 if (NTTP.isExpandedParameterPack())
495 // FIXME: We may still need to deduce parts of the type here! But we
496 // don't have any way to find which slice of the type to use, and the
497 // type stored on the NTTP itself is nonsense. Perhaps the type of an
498 // expanded NTTP should be a pack expansion type?
500
501 // Get the type of the parameter for deduction. If it's a (dependent) array
502 // or function type, we will not have decayed it yet, so do that now.
503 QualType ParamType = S.Context.getAdjustedParameterType(NTTP.getType());
504 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
505 ParamType = Expansion->getPattern();
506
507 // FIXME: It's not clear how deduction of a parameter of reference type from
508 // an argument should be performed. For now, we just make the argument have
509 // the same kind of reference type as the parameter.
510 if (ParamType->isReferenceType()) {
511 ValueType = ValueType.getNonReferenceType();
512 ValueType = ParamType->isRValueReferenceType()
513 ? S.Context.getRValueReferenceType(ValueType)
514 : S.Context.getLValueReferenceType(ValueType);
515 }
516
518 S, TemplateParams, ParamType, ValueType, Info, Deduced,
522 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound(), HasDeducedAnyParam);
523}
524
525/// Deduce the value of the given non-type template parameter
526/// from the given integral constant.
528 Sema &S, TemplateParameterList *TemplateParams,
529 NonTypeOrVarTemplateParmDecl NTTP, const llvm::APSInt &Value,
530 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
532 bool *HasDeducedAnyParam) {
534 S, TemplateParams, NTTP,
536 DeducedFromArrayBound),
537 ValueType, Info, PartialOrdering, Deduced, HasDeducedAnyParam);
538}
539
540/// Deduce the value of the given non-type template parameter
541/// from the given null pointer template argument type.
545 QualType NullPtrType, TemplateDeductionInfo &Info,
546 bool PartialOrdering,
548 bool *HasDeducedAnyParam) {
551 NTTP.getLocation()),
552 NullPtrType,
553 NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer
554 : CK_NullToPointer)
555 .get();
557 S, TemplateParams, NTTP, TemplateArgument(Value, /*IsCanonical=*/false),
558 Value->getType(), Info, PartialOrdering, Deduced, HasDeducedAnyParam);
559}
560
561/// Deduce the value of the given non-type template parameter
562/// from the given type- or value-dependent expression.
563///
564/// \returns true if deduction succeeded, false otherwise.
570 bool *HasDeducedAnyParam) {
572 S, TemplateParams, NTTP, TemplateArgument(Value, /*IsCanonical=*/false),
573 Value->getType(), Info, PartialOrdering, Deduced, HasDeducedAnyParam);
574}
575
576/// Deduce the value of the given non-type template parameter
577/// from the given declaration.
578///
579/// \returns true if deduction succeeded, false otherwise.
584 bool PartialOrdering,
586 bool *HasDeducedAnyParam) {
587 TemplateArgument New(D, T);
589 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info,
590 PartialOrdering, Deduced, HasDeducedAnyParam);
591}
592
594 Sema &S, TemplateParameterList *TemplateParams, TemplateName Param,
598 bool *HasDeducedAnyParam) {
599 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
600 if (!ParamDecl) {
601 // The parameter type is dependent and is not a template template parameter,
602 // so there is nothing that we can deduce.
604 }
605
606 if (auto *TempParam = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
607 // If we're not deducing at this depth, there's nothing to deduce.
608 if (TempParam->getDepth() != Info.getDeducedDepth())
610
611 ArrayRef<NamedDecl *> Params =
612 ParamDecl->getTemplateParameters()->asArray();
613 unsigned StartPos = 0;
614 for (unsigned I = 0, E = std::min(Params.size(), DefaultArguments.size());
615 I < E; ++I) {
616 if (Params[I]->isParameterPack()) {
617 StartPos = DefaultArguments.size();
618 break;
619 }
620 StartPos = I + 1;
621 }
622
623 // Provisional resolution for CWG2398: If Arg names a template
624 // specialization, then we deduce a synthesized template name
625 // based on A, but using the TS's extra arguments, relative to P, as
626 // defaults.
627 DeducedTemplateArgument NewDeduced =
630 Arg, {StartPos, DefaultArguments.drop_front(StartPos)}))
631 : Arg;
632
634 S.Context, Deduced[TempParam->getIndex()], NewDeduced);
635 if (Result.isNull()) {
636 Info.Param = TempParam;
637 Info.FirstArg = Deduced[TempParam->getIndex()];
638 Info.SecondArg = NewDeduced;
640 }
641
642 Deduced[TempParam->getIndex()] = Result;
643 if (HasDeducedAnyParam)
644 *HasDeducedAnyParam = true;
646 }
647
648 // Verify that the two template names are equivalent.
650 Param, Arg, /*IgnoreDeduced=*/DefaultArguments.size() != 0))
652
653 // Mismatch of non-dependent template parameter to argument.
654 Info.FirstArg = TemplateArgument(Param);
655 Info.SecondArg = TemplateArgument(Arg);
657}
658
659/// Deduce the template arguments by comparing the template parameter
660/// type (which is a template-id) with the template argument type.
661///
662/// \param S the Sema
663///
664/// \param TemplateParams the template parameters that we are deducing
665///
666/// \param P the parameter type
667///
668/// \param A the argument type
669///
670/// \param Info information about the template argument deduction itself
671///
672/// \param Deduced the deduced template arguments
673///
674/// \returns the result of template argument deduction so far. Note that a
675/// "success" result means that template argument deduction has not yet failed,
676/// but it may still fail, later, for other reasons.
677
678static const TemplateSpecializationType *getLastTemplateSpecType(QualType QT) {
679 const TemplateSpecializationType *LastTST = nullptr;
680 for (const Type *T = QT.getTypePtr(); /**/; /**/) {
681 const TemplateSpecializationType *TST =
682 T->getAs<TemplateSpecializationType>();
683 if (!TST)
684 return LastTST;
685 if (!TST->isSugared())
686 return TST;
687 LastTST = TST;
688 T = TST->desugar().getTypePtr();
689 }
690}
691
694 const QualType P, QualType A,
697 bool *HasDeducedAnyParam) {
698 TemplateName TNP;
701 const TemplateSpecializationType *TP = ::getLastTemplateSpecType(P);
702 TNP = TP->getTemplateName();
703
704 // No deduction for specializations of dependent template names.
707
708 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
709 // arguments.
710 PResolved =
711 TP->castAsCanonical<TemplateSpecializationType>()->template_arguments();
712 } else {
713 const auto *TT = P->castAs<InjectedClassNameType>();
714 TNP = TT->getTemplateName(S.Context);
715 PResolved = TT->getTemplateArgs(S.Context);
716 }
717
718 // If the parameter is an alias template, there is nothing to deduce.
719 if (const auto *TD = TNP.getAsTemplateDecl(); TD && TD->isTypeAlias())
721 // Pack-producing templates can only be matched after substitution.
724
725 // Check whether the template argument is a dependent template-id.
727 const TemplateSpecializationType *SA = ::getLastTemplateSpecType(A);
728 TemplateName TNA = SA->getTemplateName();
729
730 // If the argument is an alias template, there is nothing to deduce.
731 if (const auto *TD = TNA.getAsTemplateDecl(); TD && TD->isTypeAlias())
733
734 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
735 // arguments.
737 SA->getCanonicalTypeInternal()
738 ->castAs<TemplateSpecializationType>()
739 ->template_arguments();
740
741 // Perform template argument deduction for the template name.
742 if (auto Result = DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
743 /*DefaultArguments=*/AResolved,
745 HasDeducedAnyParam);
747 return Result;
748
749 // Perform template argument deduction on each template
750 // argument. Ignore any missing/extra arguments, since they could be
751 // filled in by default arguments.
753 S, TemplateParams, PResolved, AResolved, Info, Deduced,
754 /*NumberOfArgumentsMustMatch=*/false, PartialOrdering,
755 PackFold::ParameterToArgument, HasDeducedAnyParam);
756 }
757
758 // If the argument type is a class template specialization, we
759 // perform template argument deduction using its template
760 // arguments.
761 const auto *TA = A->getAs<TagType>();
762 TemplateName TNA;
763 if (TA) {
764 // FIXME: Can't use the template arguments from this TST, as they are not
765 // resolved.
766 if (const auto *TST = A->getAsNonAliasTemplateSpecializationType())
767 TNA = TST->getTemplateName();
768 else
769 TNA = TA->getTemplateName(S.Context);
770 }
771 if (TNA.isNull()) {
772 Info.FirstArg = TemplateArgument(P);
773 Info.SecondArg = TemplateArgument(A);
775 }
776
777 ArrayRef<TemplateArgument> AResolved = TA->getTemplateArgs(S.Context);
778 // Perform template argument deduction for the template name.
779 if (auto Result =
780 DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
781 /*DefaultArguments=*/AResolved,
782 PartialOrdering, Deduced, HasDeducedAnyParam);
784 return Result;
785
786 // Perform template argument deduction for the template arguments.
788 S, TemplateParams, PResolved, AResolved, Info, Deduced,
789 /*NumberOfArgumentsMustMatch=*/true, PartialOrdering,
790 PackFold::ParameterToArgument, HasDeducedAnyParam);
791}
792
794 assert(T->isCanonicalUnqualified());
795
796 switch (T->getTypeClass()) {
797 case Type::TypeOfExpr:
798 case Type::TypeOf:
799 case Type::DependentName:
800 case Type::Decltype:
801 case Type::PackIndexing:
802 case Type::UnresolvedUsing:
803 case Type::TemplateTypeParm:
804 case Type::Auto:
805 return true;
806
807 case Type::ConstantArray:
808 case Type::IncompleteArray:
809 case Type::VariableArray:
810 case Type::DependentSizedArray:
812 cast<ArrayType>(T)->getElementType().getTypePtr());
813
814 default:
815 return false;
816 }
817}
818
819/// Determines whether the given type is an opaque type that
820/// might be more qualified when instantiated.
823 T->getCanonicalTypeInternal().getTypePtr());
824}
825
826/// Helper function to build a TemplateParameter when we don't
827/// know its type statically.
829 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
830 return TemplateParameter(TTP);
831 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
832 return TemplateParameter(NTTP);
833
835}
836
837/// A pack that we're currently deducing.
839 // The index of the pack.
840 unsigned Index;
841
842 // The old value of the pack before we started deducing it.
844
845 // A deferred value of this pack from an inner deduction, that couldn't be
846 // deduced because this deduction hadn't happened yet.
848
849 // The new value of the pack.
851
852 // The outer deduction for this pack, if any.
853 DeducedPack *Outer = nullptr;
854
855 DeducedPack(unsigned Index) : Index(Index) {}
856};
857
858namespace {
859
860/// A scope in which we're performing pack deduction.
861class PackDeductionScope {
862public:
863 /// Prepare to deduce the packs named within Pattern.
864 /// \param FinishingDeduction Don't attempt to deduce the pack. Useful when
865 /// just checking a previous deduction of the pack.
866 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
869 bool DeducePackIfNotAlreadyDeduced = false,
870 bool FinishingDeduction = false)
871 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info),
872 DeducePackIfNotAlreadyDeduced(DeducePackIfNotAlreadyDeduced),
873 FinishingDeduction(FinishingDeduction) {
874 unsigned NumNamedPacks = addPacks(Pattern);
875 finishConstruction(NumNamedPacks);
876 }
877
878 /// Prepare to directly deduce arguments of the parameter with index \p Index.
879 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
880 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
881 TemplateDeductionInfo &Info, unsigned Index)
882 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
883 addPack(Index);
884 finishConstruction(1);
885 }
886
887private:
888 void addPack(unsigned Index) {
889 // Save the deduced template argument for the parameter pack expanded
890 // by this pack expansion, then clear out the deduction.
891 DeducedFromEarlierParameter = !Deduced[Index].isNull();
892 DeducedPack Pack(Index);
893 if (!FinishingDeduction) {
894 Pack.Saved = Deduced[Index];
895 Deduced[Index] = TemplateArgument();
896 }
897
898 // FIXME: What if we encounter multiple packs with different numbers of
899 // pre-expanded expansions? (This should already have been diagnosed
900 // during substitution.)
901 if (UnsignedOrNone ExpandedPackExpansions =
902 getExpandedPackSize(TemplateParams->getParam(Index)))
903 FixedNumExpansions = ExpandedPackExpansions;
904
905 Packs.push_back(Pack);
906 }
907
908 unsigned addPacks(TemplateArgument Pattern) {
909 // Compute the set of template parameter indices that correspond to
910 // parameter packs expanded by the pack expansion.
911 llvm::SmallBitVector SawIndices(TemplateParams->size());
912 llvm::SmallVector<TemplateArgument, 4> ExtraDeductions;
913
914 auto AddPack = [&](unsigned Index) {
915 if (SawIndices[Index])
916 return;
917 SawIndices[Index] = true;
918 addPack(Index);
919
920 // Deducing a parameter pack that is a pack expansion also constrains the
921 // packs appearing in that parameter to have the same deduced arity. Also,
922 // in C++17 onwards, deducing a non-type template parameter deduces its
923 // type, so we need to collect the pending deduced values for those packs.
924 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
925 TemplateParams->getParam(Index))) {
926 if (!NTTP->isExpandedParameterPack())
927 // FIXME: CWG2982 suggests a type-constraint forms a non-deduced
928 // context, however it is not yet resolved.
929 if (auto *Expansion = dyn_cast<PackExpansionType>(
930 S.Context.getUnconstrainedType(NTTP->getType())))
931 ExtraDeductions.push_back(Expansion->getPattern());
932 }
933 // FIXME: Also collect the unexpanded packs in any type and template
934 // parameter packs that are pack expansions.
935 };
936
937 auto Collect = [&](TemplateArgument Pattern) {
938 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
939 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
940 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
941 unsigned Depth, Index;
942
943 // Function parameter packs cannot be deduced.
944 if (isa_and_present<ParmVarDecl>(
945 dyn_cast<NamedDecl *>(Unexpanded[I].first)))
946 continue;
947 if (auto DI = getDepthAndIndex(Unexpanded[I]))
948 std::tie(Depth, Index) = *DI;
949 else
950 continue;
951
952 if (Depth == Info.getDeducedDepth())
953 AddPack(Index);
954 }
955 };
956
957 // Look for unexpanded packs in the pattern.
958 Collect(Pattern);
959
960 unsigned NumNamedPacks = Packs.size();
961
962 // Also look for unexpanded packs that are indirectly deduced by deducing
963 // the sizes of the packs in this pattern.
964 while (!ExtraDeductions.empty())
965 Collect(ExtraDeductions.pop_back_val());
966
967 return NumNamedPacks;
968 }
969
970 void finishConstruction(unsigned NumNamedPacks) {
971 // Dig out the partially-substituted pack, if there is one.
972 const TemplateArgument *PartialPackArgs = nullptr;
973 unsigned NumPartialPackArgs = 0;
974 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
975 if (auto *Scope = S.CurrentInstantiationScope)
976 if (auto *Partial = Scope->getPartiallySubstitutedPack(
977 &PartialPackArgs, &NumPartialPackArgs))
978 PartialPackDepthIndex = getDepthAndIndex(Partial);
979
980 // This pack expansion will have been partially or fully expanded if
981 // it only names explicitly-specified parameter packs (including the
982 // partially-substituted one, if any).
983 bool IsExpanded = true;
984 for (unsigned I = 0; I != NumNamedPacks; ++I) {
985 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
986 IsExpanded = false;
987 IsPartiallyExpanded = false;
988 break;
989 }
990 if (PartialPackDepthIndex ==
991 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
992 IsPartiallyExpanded = true;
993 }
994 }
995
996 // Skip over the pack elements that were expanded into separate arguments.
997 // If we partially expanded, this is the number of partial arguments.
998 // FIXME: `&& FixedNumExpansions` is a workaround for UB described in
999 // https://github.com/llvm/llvm-project/issues/100095
1000 if (IsPartiallyExpanded)
1001 PackElements += NumPartialPackArgs;
1002 else if (IsExpanded && FixedNumExpansions)
1003 PackElements += *FixedNumExpansions;
1004
1005 for (auto &Pack : Packs) {
1006 if (Info.PendingDeducedPacks.size() > Pack.Index)
1007 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
1008 else
1009 Info.PendingDeducedPacks.resize(Pack.Index + 1);
1010 Info.PendingDeducedPacks[Pack.Index] = &Pack;
1011
1012 if (PartialPackDepthIndex ==
1013 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
1014 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
1015 }
1016 }
1017 }
1018
1019public:
1020 ~PackDeductionScope() {
1021 for (auto &Pack : Packs)
1022 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
1023 }
1024
1025 // Return the size of the saved packs if all of them has the same size.
1026 UnsignedOrNone getSavedPackSizeIfAllEqual() const {
1027 unsigned PackSize = Packs[0].Saved.pack_size();
1028
1029 if (std::all_of(Packs.begin() + 1, Packs.end(), [&PackSize](const auto &P) {
1030 return P.Saved.pack_size() == PackSize;
1031 }))
1032 return PackSize;
1033 return std::nullopt;
1034 }
1035
1036 /// Determine whether this pack has already been deduced from a previous
1037 /// argument.
1038 bool isDeducedFromEarlierParameter() const {
1039 return DeducedFromEarlierParameter;
1040 }
1041
1042 /// Determine whether this pack has already been partially expanded into a
1043 /// sequence of (prior) function parameters / template arguments.
1044 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
1045
1046 /// Determine whether this pack expansion scope has a known, fixed arity.
1047 /// This happens if it involves a pack from an outer template that has
1048 /// (notionally) already been expanded.
1049 bool hasFixedArity() { return static_cast<bool>(FixedNumExpansions); }
1050
1051 /// Determine whether the next element of the argument is still part of this
1052 /// pack. This is the case unless the pack is already expanded to a fixed
1053 /// length.
1054 bool hasNextElement() {
1055 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
1056 }
1057
1058 /// Move to deducing the next element in each pack that is being deduced.
1059 void nextPackElement() {
1060 // Capture the deduced template arguments for each parameter pack expanded
1061 // by this pack expansion, add them to the list of arguments we've deduced
1062 // for that pack, then clear out the deduced argument.
1063 if (!FinishingDeduction) {
1064 for (auto &Pack : Packs) {
1065 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
1066 if (!Pack.New.empty() || !DeducedArg.isNull()) {
1067 while (Pack.New.size() < PackElements)
1068 Pack.New.push_back(DeducedTemplateArgument());
1069 if (Pack.New.size() == PackElements)
1070 Pack.New.push_back(DeducedArg);
1071 else
1072 Pack.New[PackElements] = DeducedArg;
1073 DeducedArg = Pack.New.size() > PackElements + 1
1074 ? Pack.New[PackElements + 1]
1075 : DeducedTemplateArgument();
1076 }
1077 }
1078 }
1079 ++PackElements;
1080 }
1081
1082 /// Finish template argument deduction for a set of argument packs,
1083 /// producing the argument packs and checking for consistency with prior
1084 /// deductions.
1085 TemplateDeductionResult finish() {
1086 if (FinishingDeduction)
1087 return TemplateDeductionResult::Success;
1088 // Build argument packs for each of the parameter packs expanded by this
1089 // pack expansion.
1090 for (auto &Pack : Packs) {
1091 // Put back the old value for this pack.
1092 if (!FinishingDeduction)
1093 Deduced[Pack.Index] = Pack.Saved;
1094
1095 // Always make sure the size of this pack is correct, even if we didn't
1096 // deduce any values for it.
1097 //
1098 // FIXME: This isn't required by the normative wording, but substitution
1099 // and post-substitution checking will always fail if the arity of any
1100 // pack is not equal to the number of elements we processed. (Either that
1101 // or something else has gone *very* wrong.) We're permitted to skip any
1102 // hard errors from those follow-on steps by the intent (but not the
1103 // wording) of C++ [temp.inst]p8:
1104 //
1105 // If the function selected by overload resolution can be determined
1106 // without instantiating a class template definition, it is unspecified
1107 // whether that instantiation actually takes place
1108 Pack.New.resize(PackElements);
1109
1110 // Build or find a new value for this pack.
1111 DeducedTemplateArgument NewPack;
1112 if (Pack.New.empty()) {
1113 // If we deduced an empty argument pack, create it now.
1114 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
1115 } else {
1116 TemplateArgument *ArgumentPack =
1117 new (S.Context) TemplateArgument[Pack.New.size()];
1118 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
1119 NewPack = DeducedTemplateArgument(
1120 TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())),
1121 // FIXME: This is wrong, it's possible that some pack elements are
1122 // deduced from an array bound and others are not:
1123 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
1124 // g({1, 2, 3}, {{}, {}});
1125 // ... should deduce T = {int, size_t (from array bound)}.
1126 Pack.New[0].wasDeducedFromArrayBound());
1127 }
1128
1129 // Pick where we're going to put the merged pack.
1130 DeducedTemplateArgument *Loc;
1131 if (Pack.Outer) {
1132 if (Pack.Outer->DeferredDeduction.isNull()) {
1133 // Defer checking this pack until we have a complete pack to compare
1134 // it against.
1135 Pack.Outer->DeferredDeduction = NewPack;
1136 continue;
1137 }
1138 Loc = &Pack.Outer->DeferredDeduction;
1139 } else {
1140 Loc = &Deduced[Pack.Index];
1141 }
1142
1143 // Check the new pack matches any previous value.
1144 DeducedTemplateArgument OldPack = *Loc;
1145 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
1146 S.Context, OldPack, NewPack, DeducePackIfNotAlreadyDeduced);
1147
1148 Info.AggregateDeductionCandidateHasMismatchedArity =
1149 OldPack.getKind() == TemplateArgument::Pack &&
1150 NewPack.getKind() == TemplateArgument::Pack &&
1151 OldPack.pack_size() != NewPack.pack_size() && !Result.isNull();
1152
1153 // If we deferred a deduction of this pack, check that one now too.
1154 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
1155 OldPack = Result;
1156 NewPack = Pack.DeferredDeduction;
1157 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
1158 }
1159
1160 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
1161 if (Result.isNull()) {
1162 Info.Param = makeTemplateParameter(Param);
1163 Info.FirstArg = OldPack;
1164 Info.SecondArg = NewPack;
1165 return TemplateDeductionResult::Inconsistent;
1166 }
1167
1168 // If we have a pre-expanded pack and we didn't deduce enough elements
1169 // for it, fail deduction.
1170 if (UnsignedOrNone Expansions = getExpandedPackSize(Param)) {
1171 if (*Expansions != PackElements) {
1172 Info.Param = makeTemplateParameter(Param);
1173 Info.FirstArg = Result;
1174 return TemplateDeductionResult::IncompletePack;
1175 }
1176 }
1177
1178 *Loc = Result;
1179 }
1180
1181 return TemplateDeductionResult::Success;
1182 }
1183
1184private:
1185 Sema &S;
1186 TemplateParameterList *TemplateParams;
1187 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
1188 TemplateDeductionInfo &Info;
1189 unsigned PackElements = 0;
1190 bool IsPartiallyExpanded = false;
1191 bool DeducePackIfNotAlreadyDeduced = false;
1192 bool DeducedFromEarlierParameter = false;
1193 bool FinishingDeduction = false;
1194 /// The number of expansions, if we have a fully-expanded pack in this scope.
1195 UnsignedOrNone FixedNumExpansions = std::nullopt;
1196
1197 SmallVector<DeducedPack, 2> Packs;
1198};
1199
1200} // namespace
1201
1202template <class T>
1204 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1207 bool FinishingDeduction, T &&DeductFunc) {
1208 // C++0x [temp.deduct.type]p10:
1209 // Similarly, if P has a form that contains (T), then each parameter type
1210 // Pi of the respective parameter-type- list of P is compared with the
1211 // corresponding parameter type Ai of the corresponding parameter-type-list
1212 // of A. [...]
1213 unsigned ArgIdx = 0, ParamIdx = 0;
1214 for (; ParamIdx != Params.size(); ++ParamIdx) {
1215 // Check argument types.
1216 const PackExpansionType *Expansion
1217 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1218 if (!Expansion) {
1219 // Simple case: compare the parameter and argument types at this point.
1220
1221 // Make sure we have an argument.
1222 if (ArgIdx >= Args.size())
1224
1225 if (isa<PackExpansionType>(Args[ArgIdx])) {
1226 // C++0x [temp.deduct.type]p22:
1227 // If the original function parameter associated with A is a function
1228 // parameter pack and the function parameter associated with P is not
1229 // a function parameter pack, then template argument deduction fails.
1231 }
1232
1234 DeductFunc(S, TemplateParams, ParamIdx, ArgIdx,
1235 Params[ParamIdx].getUnqualifiedType(),
1236 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, POK);
1238 return Result;
1239
1240 ++ArgIdx;
1241 continue;
1242 }
1243
1244 // C++0x [temp.deduct.type]p10:
1245 // If the parameter-declaration corresponding to Pi is a function
1246 // parameter pack, then the type of its declarator- id is compared with
1247 // each remaining parameter type in the parameter-type-list of A. Each
1248 // comparison deduces template arguments for subsequent positions in the
1249 // template parameter packs expanded by the function parameter pack.
1250
1251 QualType Pattern = Expansion->getPattern();
1252 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern,
1253 /*DeducePackIfNotAlreadyDeduced=*/false,
1254 FinishingDeduction);
1255
1256 // A pack scope with fixed arity is not really a pack any more, so is not
1257 // a non-deduced context.
1258 if (ParamIdx + 1 == Params.size() || PackScope.hasFixedArity()) {
1259 for (; ArgIdx < Args.size() && PackScope.hasNextElement(); ++ArgIdx) {
1260 // Deduce template arguments from the pattern.
1261 if (TemplateDeductionResult Result = DeductFunc(
1262 S, TemplateParams, ParamIdx, ArgIdx,
1263 Pattern.getUnqualifiedType(), Args[ArgIdx].getUnqualifiedType(),
1264 Info, Deduced, POK);
1266 return Result;
1267 PackScope.nextPackElement();
1268 }
1269 } else {
1270 // C++0x [temp.deduct.type]p5:
1271 // The non-deduced contexts are:
1272 // - A function parameter pack that does not occur at the end of the
1273 // parameter-declaration-clause.
1274 //
1275 // FIXME: There is no wording to say what we should do in this case. We
1276 // choose to resolve this by applying the same rule that is applied for a
1277 // function call: that is, deduce all contained packs to their
1278 // explicitly-specified values (or to <> if there is no such value).
1279 //
1280 // This is seemingly-arbitrarily different from the case of a template-id
1281 // with a non-trailing pack-expansion in its arguments, which renders the
1282 // entire template-argument-list a non-deduced context.
1283
1284 // If the parameter type contains an explicitly-specified pack that we
1285 // could not expand, skip the number of parameters notionally created
1286 // by the expansion.
1287 UnsignedOrNone NumExpansions = Expansion->getNumExpansions();
1288 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1289 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
1290 ++I, ++ArgIdx)
1291 PackScope.nextPackElement();
1292 }
1293 }
1294
1295 // Build argument packs for each of the parameter packs expanded by this
1296 // pack expansion.
1297 if (auto Result = PackScope.finish();
1299 return Result;
1300 }
1301
1302 // DR692, DR1395
1303 // C++0x [temp.deduct.type]p10:
1304 // If the parameter-declaration corresponding to P_i ...
1305 // During partial ordering, if Ai was originally a function parameter pack:
1306 // - if P does not contain a function parameter type corresponding to Ai then
1307 // Ai is ignored;
1308 if (POK == PartialOrderingKind::Call && ArgIdx + 1 == Args.size() &&
1309 isa<PackExpansionType>(Args[ArgIdx]))
1311
1312 // Make sure we don't have any extra arguments.
1313 if (ArgIdx < Args.size())
1315
1317}
1318
1319/// Deduce the template arguments by comparing the list of parameter
1320/// types to the list of argument types, as in the parameter-type-lists of
1321/// function types (C++ [temp.deduct.type]p10).
1322///
1323/// \param S The semantic analysis object within which we are deducing
1324///
1325/// \param TemplateParams The template parameters that we are deducing
1326///
1327/// \param Params The list of parameter types
1328///
1329/// \param Args The list of argument types
1330///
1331/// \param Info information about the template argument deduction itself
1332///
1333/// \param Deduced the deduced template arguments
1334///
1335/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1336/// how template argument deduction is performed.
1337///
1338/// \param PartialOrdering If true, we are performing template argument
1339/// deduction for during partial ordering for a call
1340/// (C++0x [temp.deduct.partial]).
1341///
1342/// \param HasDeducedAnyParam If set, the object pointed at will indicate
1343/// whether any template parameter was deduced.
1344///
1345/// \param HasDeducedParam If set, the bit vector will be used to represent
1346/// which template parameters were deduced, in order.
1347///
1348/// \returns the result of template argument deduction so far. Note that a
1349/// "success" result means that template argument deduction has not yet failed,
1350/// but it may still fail, later, for other reasons.
1352 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1355 PartialOrderingKind POK, bool *HasDeducedAnyParam,
1356 llvm::SmallBitVector *HasDeducedParam) {
1357 return ::DeduceForEachType(
1358 S, TemplateParams, Params, Args, Info, Deduced, POK,
1359 /*FinishingDeduction=*/false,
1360 [&](Sema &S, TemplateParameterList *TemplateParams, int ParamIdx,
1361 int ArgIdx, QualType P, QualType A, TemplateDeductionInfo &Info,
1363 PartialOrderingKind POK) {
1364 bool HasDeducedAnyParamCopy = false;
1366 S, TemplateParams, P, A, Info, Deduced, TDF, POK,
1367 /*DeducedFromArrayBound=*/false, &HasDeducedAnyParamCopy);
1368 if (HasDeducedAnyParam && HasDeducedAnyParamCopy)
1369 *HasDeducedAnyParam = true;
1370 if (HasDeducedParam && HasDeducedAnyParamCopy)
1371 (*HasDeducedParam)[ParamIdx] = true;
1372 return TDR;
1373 });
1374}
1375
1376/// Determine whether the parameter has qualifiers that the argument
1377/// lacks. Put another way, determine whether there is no way to add
1378/// a deduced set of qualifiers to the ParamType that would result in
1379/// its qualifiers matching those of the ArgType.
1381 QualType ArgType) {
1382 Qualifiers ParamQs = ParamType.getQualifiers();
1383 Qualifiers ArgQs = ArgType.getQualifiers();
1384
1385 if (ParamQs == ArgQs)
1386 return false;
1387
1388 // Mismatched (but not missing) Objective-C GC attributes.
1389 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1390 ParamQs.hasObjCGCAttr())
1391 return true;
1392
1393 // Mismatched (but not missing) address spaces.
1394 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1395 ParamQs.hasAddressSpace())
1396 return true;
1397
1398 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1399 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1400 ParamQs.hasObjCLifetime())
1401 return true;
1402
1403 // CVR qualifiers inconsistent or a superset.
1404 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1405}
1406
1408 const FunctionType *PF = P->getAs<FunctionType>(),
1409 *AF = A->getAs<FunctionType>();
1410
1411 // Just compare if not functions.
1412 if (!PF || !AF)
1413 return Context.hasSameType(P, A);
1414
1415 // Noreturn and noexcept adjustment.
1416 if (QualType AdjustedParam; TryFunctionConversion(P, A, AdjustedParam))
1417 P = AdjustedParam;
1418
1419 // FIXME: Compatible calling conventions.
1420 return Context.hasSameFunctionTypeIgnoringExceptionSpec(P, A);
1421}
1422
1423/// Get the index of the first template parameter that was originally from the
1424/// innermost template-parameter-list. This is 0 except when we concatenate
1425/// the template parameter lists of a class template and a constructor template
1426/// when forming an implicit deduction guide.
1428 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1429 if (!Guide || !Guide->isImplicit())
1430 return 0;
1431 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1432}
1433
1434/// Determine whether a type denotes a forwarding reference.
1435static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1436 // C++1z [temp.deduct.call]p3:
1437 // A forwarding reference is an rvalue reference to a cv-unqualified
1438 // template parameter that does not represent a template parameter of a
1439 // class template.
1440 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1441 if (ParamRef->getPointeeType().getQualifiers())
1442 return false;
1443 auto *TypeParm =
1444 ParamRef->getPointeeType()->getAsCanonical<TemplateTypeParmType>();
1445 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1446 }
1447 return false;
1448}
1449
1450/// Attempt to deduce the template arguments by checking the base types
1451/// according to (C++20 [temp.deduct.call] p4b3.
1452///
1453/// \param S the semantic analysis object within which we are deducing.
1454///
1455/// \param RD the top level record object we are deducing against.
1456///
1457/// \param TemplateParams the template parameters that we are deducing.
1458///
1459/// \param P the template specialization parameter type.
1460///
1461/// \param Info information about the template argument deduction itself.
1462///
1463/// \param Deduced the deduced template arguments.
1464///
1465/// \returns the result of template argument deduction with the bases. "invalid"
1466/// means no matches, "success" found a single item, and the
1467/// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
1470 TemplateParameterList *TemplateParams, QualType P,
1473 bool *HasDeducedAnyParam) {
1474 // C++14 [temp.deduct.call] p4b3:
1475 // If P is a class and P has the form simple-template-id, then the
1476 // transformed A can be a derived class of the deduced A. Likewise if
1477 // P is a pointer to a class of the form simple-template-id, the
1478 // transformed A can be a pointer to a derived class pointed to by the
1479 // deduced A. However, if there is a class C that is a (direct or
1480 // indirect) base class of D and derived (directly or indirectly) from a
1481 // class B and that would be a valid deduced A, the deduced A cannot be
1482 // B or pointer to B, respectively.
1483 //
1484 // These alternatives are considered only if type deduction would
1485 // otherwise fail. If they yield more than one possible deduced A, the
1486 // type deduction fails.
1487
1488 // Use a breadth-first search through the bases to collect the set of
1489 // successful matches. Visited contains the set of nodes we have already
1490 // visited, while ToVisit is our stack of records that we still need to
1491 // visit. Matches contains a list of matches that have yet to be
1492 // disqualified.
1495 // We iterate over this later, so we have to use MapVector to ensure
1496 // determinism.
1497 struct MatchValue {
1499 bool HasDeducedAnyParam;
1500 };
1501 llvm::MapVector<const CXXRecordDecl *, MatchValue> Matches;
1502
1503 auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
1504 for (const auto &Base : RD->bases()) {
1505 QualType T = Base.getType();
1506 assert(T->isRecordType() && "Base class that isn't a record?");
1507 if (Visited.insert(T->getAsCXXRecordDecl()).second)
1508 ToVisit.push_back(T);
1509 }
1510 };
1511
1512 // Set up the loop by adding all the bases.
1513 AddBases(RD);
1514
1515 // Search each path of bases until we either run into a successful match
1516 // (where all bases of it are invalid), or we run out of bases.
1517 while (!ToVisit.empty()) {
1518 QualType NextT = ToVisit.pop_back_val();
1519
1521 Deduced.end());
1523 bool HasDeducedAnyParamCopy = false;
1525 S, TemplateParams, P, NextT, BaseInfo, PartialOrdering, DeducedCopy,
1526 &HasDeducedAnyParamCopy);
1527
1528 // If this was a successful deduction, add it to the list of matches,
1529 // otherwise we need to continue searching its bases.
1530 const CXXRecordDecl *RD = NextT->getAsCXXRecordDecl();
1532 Matches.insert({RD, {DeducedCopy, HasDeducedAnyParamCopy}});
1533 else
1534 AddBases(RD);
1535 }
1536
1537 // At this point, 'Matches' contains a list of seemingly valid bases, however
1538 // in the event that we have more than 1 match, it is possible that the base
1539 // of one of the matches might be disqualified for being a base of another
1540 // valid match. We can count on cyclical instantiations being invalid to
1541 // simplify the disqualifications. That is, if A & B are both matches, and B
1542 // inherits from A (disqualifying A), we know that A cannot inherit from B.
1543 if (Matches.size() > 1) {
1544 Visited.clear();
1545 for (const auto &Match : Matches)
1546 AddBases(Match.first);
1547
1548 // We can give up once we have a single item (or have run out of things to
1549 // search) since cyclical inheritance isn't valid.
1550 while (Matches.size() > 1 && !ToVisit.empty()) {
1551 const CXXRecordDecl *RD = ToVisit.pop_back_val()->getAsCXXRecordDecl();
1552 Matches.erase(RD);
1553
1554 // Always add all bases, since the inheritance tree can contain
1555 // disqualifications for multiple matches.
1556 AddBases(RD);
1557 }
1558 }
1559
1560 if (Matches.empty())
1562 if (Matches.size() > 1)
1564
1565 std::swap(Matches.front().second.Deduced, Deduced);
1566 if (bool HasDeducedAnyParamCopy = Matches.front().second.HasDeducedAnyParam;
1567 HasDeducedAnyParamCopy && HasDeducedAnyParam)
1568 *HasDeducedAnyParam = HasDeducedAnyParamCopy;
1570}
1571
1572/// When propagating a partial ordering kind into a NonCall context,
1573/// this is used to downgrade a 'Call' into a 'NonCall', so that
1574/// the kind still reflects whether we are in a partial ordering context.
1579
1580/// Deduce the template arguments by comparing the parameter type and
1581/// the argument type (C++ [temp.deduct.type]).
1582///
1583/// \param S the semantic analysis object within which we are deducing
1584///
1585/// \param TemplateParams the template parameters that we are deducing
1586///
1587/// \param P the parameter type
1588///
1589/// \param A the argument type
1590///
1591/// \param Info information about the template argument deduction itself
1592///
1593/// \param Deduced the deduced template arguments
1594///
1595/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1596/// how template argument deduction is performed.
1597///
1598/// \param PartialOrdering Whether we're performing template argument deduction
1599/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1600///
1601/// \returns the result of template argument deduction so far. Note that a
1602/// "success" result means that template argument deduction has not yet failed,
1603/// but it may still fail, later, for other reasons.
1605 Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
1608 PartialOrderingKind POK, bool DeducedFromArrayBound,
1609 bool *HasDeducedAnyParam) {
1610
1611 // If the argument type is a pack expansion, look at its pattern.
1612 // This isn't explicitly called out
1613 if (const auto *AExp = dyn_cast<PackExpansionType>(A))
1614 A = AExp->getPattern();
1616
1617 if (POK == PartialOrderingKind::Call) {
1618 // C++11 [temp.deduct.partial]p5:
1619 // Before the partial ordering is done, certain transformations are
1620 // performed on the types used for partial ordering:
1621 // - If P is a reference type, P is replaced by the type referred to.
1622 const ReferenceType *PRef = P->getAs<ReferenceType>();
1623 if (PRef)
1624 P = PRef->getPointeeType();
1625
1626 // - If A is a reference type, A is replaced by the type referred to.
1627 const ReferenceType *ARef = A->getAs<ReferenceType>();
1628 if (ARef)
1629 A = A->getPointeeType();
1630
1631 if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
1632 // C++11 [temp.deduct.partial]p9:
1633 // If, for a given type, deduction succeeds in both directions (i.e.,
1634 // the types are identical after the transformations above) and both
1635 // P and A were reference types [...]:
1636 // - if [one type] was an lvalue reference and [the other type] was
1637 // not, [the other type] is not considered to be at least as
1638 // specialized as [the first type]
1639 // - if [one type] is more cv-qualified than [the other type],
1640 // [the other type] is not considered to be at least as specialized
1641 // as [the first type]
1642 // Objective-C ARC adds:
1643 // - [one type] has non-trivial lifetime, [the other type] has
1644 // __unsafe_unretained lifetime, and the types are otherwise
1645 // identical
1646 //
1647 // A is "considered to be at least as specialized" as P iff deduction
1648 // succeeds, so we model this as a deduction failure. Note that
1649 // [the first type] is P and [the other type] is A here; the standard
1650 // gets this backwards.
1651 Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
1652 if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
1653 PQuals.isStrictSupersetOf(AQuals) ||
1654 (PQuals.hasNonTrivialObjCLifetime() &&
1655 AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1656 PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
1657 Info.FirstArg = TemplateArgument(P);
1658 Info.SecondArg = TemplateArgument(A);
1660 }
1661 }
1662 Qualifiers DiscardedQuals;
1663 // C++11 [temp.deduct.partial]p7:
1664 // Remove any top-level cv-qualifiers:
1665 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1666 // version of P.
1667 P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
1668 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1669 // version of A.
1670 A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
1671 } else {
1672 // C++0x [temp.deduct.call]p4 bullet 1:
1673 // - If the original P is a reference type, the deduced A (i.e., the type
1674 // referred to by the reference) can be more cv-qualified than the
1675 // transformed A.
1676 if (TDF & TDF_ParamWithReferenceType) {
1677 Qualifiers Quals;
1678 QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
1680 P = S.Context.getQualifiedType(UnqualP, Quals);
1681 }
1682
1683 if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
1684 // C++0x [temp.deduct.type]p10:
1685 // If P and A are function types that originated from deduction when
1686 // taking the address of a function template (14.8.2.2) or when deducing
1687 // template arguments from a function declaration (14.8.2.6) and Pi and
1688 // Ai are parameters of the top-level parameter-type-list of P and A,
1689 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1690 // is an lvalue reference, in
1691 // which case the type of Pi is changed to be the template parameter
1692 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1693 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1694 // deduced as X&. - end note ]
1696 if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
1698 P = P->getPointeeType();
1699 }
1700 }
1701
1702 // C++ [temp.deduct.type]p9:
1703 // A template type argument T, a template template argument TT or a
1704 // template non-type argument i can be deduced if P and A have one of
1705 // the following forms:
1706 //
1707 // T
1708 // cv-list T
1709 if (const auto *TTP = P->getAsCanonical<TemplateTypeParmType>()) {
1710 // Just skip any attempts to deduce from a placeholder type or a parameter
1711 // at a different depth.
1712 if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
1714
1715 unsigned Index = TTP->getIndex();
1716
1717 // If the argument type is an array type, move the qualifiers up to the
1718 // top level, so they can be matched with the qualifiers on the parameter.
1719 if (A->isArrayType()) {
1720 Qualifiers Quals;
1721 A = S.Context.getUnqualifiedArrayType(A, Quals);
1722 if (Quals)
1723 A = S.Context.getQualifiedType(A, Quals);
1724 }
1725
1726 // The argument type can not be less qualified than the parameter
1727 // type.
1728 if (!(TDF & TDF_IgnoreQualifiers) &&
1730 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1731 Info.FirstArg = TemplateArgument(P);
1732 Info.SecondArg = TemplateArgument(A);
1734 }
1735
1736 // Do not match a function type with a cv-qualified type.
1737 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1738 if (A->isFunctionType() && P.hasQualifiers())
1740
1741 assert(TTP->getDepth() == Info.getDeducedDepth() &&
1742 "saw template type parameter with wrong depth");
1743 assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&
1744 "Unresolved overloaded function");
1745 QualType DeducedType = A;
1746
1747 // Remove any qualifiers on the parameter from the deduced type.
1748 // We checked the qualifiers for consistency above.
1749 Qualifiers DeducedQs = DeducedType.getQualifiers();
1750 Qualifiers ParamQs = P.getQualifiers();
1751 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1752 if (ParamQs.hasObjCGCAttr())
1753 DeducedQs.removeObjCGCAttr();
1754 if (ParamQs.hasAddressSpace())
1755 DeducedQs.removeAddressSpace();
1756 if (ParamQs.hasObjCLifetime())
1757 DeducedQs.removeObjCLifetime();
1758
1759 // Objective-C ARC:
1760 // If template deduction would produce a lifetime qualifier on a type
1761 // that is not a lifetime type, template argument deduction fails.
1762 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1763 !DeducedType->isDependentType()) {
1764 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1765 Info.FirstArg = TemplateArgument(P);
1766 Info.SecondArg = TemplateArgument(A);
1768 }
1769
1770 // Objective-C ARC:
1771 // If template deduction would produce an argument type with lifetime type
1772 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1773 if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
1774 !DeducedQs.hasObjCLifetime())
1776
1777 DeducedType =
1778 S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
1779
1780 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1782 checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
1783 if (Result.isNull()) {
1784 // We can also get inconsistencies when matching NTTP type.
1785 switch (NamedDecl *Param = TemplateParams->getParam(Index);
1786 Param->getKind()) {
1787 case Decl::TemplateTypeParm:
1788 Info.Param = cast<TemplateTypeParmDecl>(Param);
1789 break;
1790 case Decl::NonTypeTemplateParm:
1792 break;
1793 case Decl::TemplateTemplateParm:
1795 break;
1796 default:
1797 llvm_unreachable("unexpected kind");
1798 }
1799 Info.FirstArg = Deduced[Index];
1800 Info.SecondArg = NewDeduced;
1802 }
1803
1804 Deduced[Index] = Result;
1805 if (HasDeducedAnyParam)
1806 *HasDeducedAnyParam = true;
1808 }
1809
1810 // Set up the template argument deduction information for a failure.
1811 Info.FirstArg = TemplateArgument(P);
1812 Info.SecondArg = TemplateArgument(A);
1813
1814 // If the parameter is an already-substituted template parameter
1815 // pack, do nothing: we don't know which of its arguments to look
1816 // at, so we have to wait until all of the parameter packs in this
1817 // expansion have arguments.
1818 if (P->getAs<SubstTemplateTypeParmPackType>())
1820
1821 // Check the cv-qualifiers on the parameter and argument types.
1822 if (!(TDF & TDF_IgnoreQualifiers)) {
1823 if (TDF & TDF_ParamWithReferenceType) {
1826 } else if (TDF & TDF_ArgWithReferenceType) {
1827 // C++ [temp.deduct.conv]p4:
1828 // If the original A is a reference type, A can be more cv-qualified
1829 // than the deduced A
1831 S.getASTContext()))
1833
1834 // Strip out all extra qualifiers from the argument to figure out the
1835 // type we're converting to, prior to the qualification conversion.
1836 Qualifiers Quals;
1837 A = S.Context.getUnqualifiedArrayType(A, Quals);
1839 } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
1840 if (P.getCVRQualifiers() != A.getCVRQualifiers())
1842 }
1843 }
1844
1845 // If the parameter type is not dependent, there is nothing to deduce.
1846 if (!P->isDependentType()) {
1847 if (TDF & TDF_SkipNonDependent)
1850 : S.Context.hasSameType(P, A))
1855 if (!(TDF & TDF_IgnoreQualifiers))
1857 // Otherwise, when ignoring qualifiers, the types not having the same
1858 // unqualified type does not mean they do not match, so in this case we
1859 // must keep going and analyze with a non-dependent parameter type.
1860 }
1861
1862 switch (P.getCanonicalType()->getTypeClass()) {
1863 // Non-canonical types cannot appear here.
1864#define NON_CANONICAL_TYPE(Class, Base) \
1865 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1866#define TYPE(Class, Base)
1867#include "clang/AST/TypeNodes.inc"
1868
1869 case Type::TemplateTypeParm:
1870 case Type::SubstTemplateTypeParmPack:
1871 case Type::SubstBuiltinTemplatePack:
1872 llvm_unreachable("Type nodes handled above");
1873
1874 case Type::Auto:
1875 // C++23 [temp.deduct.funcaddr]/3:
1876 // A placeholder type in the return type of a function template is a
1877 // non-deduced context.
1878 // There's no corresponding wording for [temp.deduct.decl], but we treat
1879 // it the same to match other compilers.
1880 if (P->isDependentType())
1882 [[fallthrough]];
1883 case Type::Builtin:
1884 case Type::VariableArray:
1885 case Type::Vector:
1886 case Type::FunctionNoProto:
1887 case Type::Record:
1888 case Type::Enum:
1889 case Type::ObjCObject:
1890 case Type::ObjCInterface:
1891 case Type::ObjCObjectPointer:
1892 case Type::BitInt:
1893 return (TDF & TDF_SkipNonDependent) ||
1894 ((TDF & TDF_IgnoreQualifiers)
1896 : S.Context.hasSameType(P, A))
1899
1900 // _Complex T [placeholder extension]
1901 case Type::Complex: {
1902 const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
1903 if (!CA)
1906 S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
1908 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1909 }
1910
1911 // _Atomic T [extension]
1912 case Type::Atomic: {
1913 const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
1914 if (!AA)
1917 S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
1919 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1920 }
1921
1922 // T *
1923 case Type::Pointer: {
1924 QualType PointeeType;
1925 if (const auto *PA = A->getAs<PointerType>()) {
1926 PointeeType = PA->getPointeeType();
1927 } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
1928 PointeeType = PA->getPointeeType();
1929 } else {
1931 }
1933 S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
1934 PointeeType, Info, Deduced,
1937 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1938 }
1939
1940 // T &
1941 case Type::LValueReference: {
1942 const auto *RP = P->castAs<LValueReferenceType>(),
1943 *RA = A->getAs<LValueReferenceType>();
1944 if (!RA)
1946
1948 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1950 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1951 }
1952
1953 // T && [C++0x]
1954 case Type::RValueReference: {
1955 const auto *RP = P->castAs<RValueReferenceType>(),
1956 *RA = A->getAs<RValueReferenceType>();
1957 if (!RA)
1959
1961 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1963 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1964 }
1965
1966 // T [] (implied, but not stated explicitly)
1967 case Type::IncompleteArray: {
1968 const auto *IAA = S.Context.getAsIncompleteArrayType(A);
1969 if (!IAA)
1971
1972 const auto *IAP = S.Context.getAsIncompleteArrayType(P);
1973 assert(IAP && "Template parameter not of incomplete array type");
1974
1976 S, TemplateParams, IAP->getElementType(), IAA->getElementType(), Info,
1979 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1980 }
1981
1982 // T [integer-constant]
1983 case Type::ConstantArray: {
1984 const auto *CAA = S.Context.getAsConstantArrayType(A),
1985 *CAP = S.Context.getAsConstantArrayType(P);
1986 assert(CAP);
1987 if (!CAA || CAA->getSize() != CAP->getSize())
1989
1991 S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
1994 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1995 }
1996
1997 // type [i]
1998 case Type::DependentSizedArray: {
1999 const auto *AA = S.Context.getAsArrayType(A);
2000 if (!AA)
2002
2003 // Check the element type of the arrays
2004 const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
2005 assert(DAP);
2007 S, TemplateParams, DAP->getElementType(), AA->getElementType(),
2008 Info, Deduced, TDF & TDF_IgnoreQualifiers,
2010 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2012 return Result;
2013
2014 // Determine the array bound is something we can deduce.
2016 getNTTParameterFromExpr(Info, DAP->getSizeExpr());
2017 if (!NTTP)
2019
2020 // We can perform template argument deduction for the given non-type
2021 // template parameter.
2022 assert(NTTP.getDepth() == Info.getDeducedDepth() &&
2023 "saw non-type template parameter with wrong depth");
2024 if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
2025 llvm::APSInt Size(CAA->getSize());
2027 S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
2028 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
2029 Deduced, HasDeducedAnyParam);
2030 }
2031 if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
2032 if (DAA->getSizeExpr())
2034 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info,
2035 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2036
2037 // Incomplete type does not match a dependently-sized array type
2039 }
2040
2041 // type(*)(T)
2042 // T(*)()
2043 // T(*)(T)
2044 case Type::FunctionProto: {
2045 const auto *FPP = P->castAs<FunctionProtoType>(),
2046 *FPA = A->getAs<FunctionProtoType>();
2047 if (!FPA)
2049
2050 if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
2051 FPP->getRefQualifier() != FPA->getRefQualifier() ||
2052 FPP->isVariadic() != FPA->isVariadic())
2054
2055 // Check return types.
2057 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
2059 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2061 return Result;
2062
2063 // Check parameter types.
2065 S, TemplateParams, FPP->param_types(), FPA->param_types(), Info,
2067 HasDeducedAnyParam,
2068 /*HasDeducedParam=*/nullptr);
2070 return Result;
2071
2074
2075 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
2076 // deducing through the noexcept-specifier if it's part of the canonical
2077 // type. libstdc++ relies on this.
2078 Expr *NoexceptExpr = FPP->getNoexceptExpr();
2080 NoexceptExpr ? getNTTParameterFromExpr(Info, NoexceptExpr)
2081 : nullptr) {
2082 assert(NTTP.getDepth() == Info.getDeducedDepth() &&
2083 "saw non-type template parameter with wrong depth");
2084
2085 llvm::APSInt Noexcept(1);
2086 switch (FPA->canThrow()) {
2087 case CT_Cannot:
2088 Noexcept = 1;
2089 [[fallthrough]];
2090
2091 case CT_Can:
2092 // We give E in noexcept(E) the "deduced from array bound" treatment.
2093 // FIXME: Should we?
2095 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
2096 /*DeducedFromArrayBound=*/true, Info,
2097 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2098
2099 case CT_Dependent:
2100 if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
2102 S, TemplateParams, NTTP, ArgNoexceptExpr, Info,
2103 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2104 // Can't deduce anything from throw(T...).
2105 break;
2106 }
2107 }
2108 // FIXME: Detect non-deduced exception specification mismatches?
2109 //
2110 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
2111 // top-level differences in noexcept-specifications.
2112
2114 }
2115
2116 case Type::InjectedClassName:
2117 // Treat a template's injected-class-name as if the template
2118 // specialization type had been used.
2119
2120 // template-name<T> (where template-name refers to a class template)
2121 // template-name<i>
2122 // TT<T>
2123 // TT<i>
2124 // TT<>
2125 case Type::TemplateSpecialization: {
2126 // When Arg cannot be a derived class, we can just try to deduce template
2127 // arguments from the template-id.
2128 if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
2129 return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
2131 Deduced, HasDeducedAnyParam);
2132
2134 Deduced.end());
2135
2137 S, TemplateParams, P, A, Info, POK != PartialOrderingKind::None,
2138 Deduced, HasDeducedAnyParam);
2140 return Result;
2141
2142 // We cannot inspect base classes as part of deduction when the type
2143 // is incomplete, so either instantiate any templates necessary to
2144 // complete the type, or skip over it if it cannot be completed.
2145 if (!S.isCompleteType(Info.getLocation(), A))
2146 return Result;
2147
2148 const CXXRecordDecl *RD = A->getAsCXXRecordDecl();
2149 if (RD->isInvalidDecl())
2150 return Result;
2151
2152 // Reset the incorrectly deduced argument from above.
2153 Deduced = DeducedOrig;
2154
2155 // Check bases according to C++14 [temp.deduct.call] p4b3:
2156 auto BaseResult = DeduceTemplateBases(S, RD, TemplateParams, P, Info,
2158 Deduced, HasDeducedAnyParam);
2160 : Result;
2161 }
2162
2163 // T type::*
2164 // T T::*
2165 // T (type::*)()
2166 // type (T::*)()
2167 // type (type::*)(T)
2168 // type (T::*)(T)
2169 // T (type::*)(T)
2170 // T (T::*)()
2171 // T (T::*)(T)
2172 case Type::MemberPointer: {
2173 const auto *MPP = P->castAs<MemberPointerType>(),
2174 *MPA = A->getAs<MemberPointerType>();
2175 if (!MPA)
2177
2178 QualType PPT = MPP->getPointeeType();
2179 if (PPT->isFunctionType())
2180 S.adjustMemberFunctionCC(PPT, /*HasThisPointer=*/false,
2181 /*IsCtorOrDtor=*/false, Info.getLocation());
2182 QualType APT = MPA->getPointeeType();
2183 if (APT->isFunctionType())
2184 S.adjustMemberFunctionCC(APT, /*HasThisPointer=*/false,
2185 /*IsCtorOrDtor=*/false, Info.getLocation());
2186
2187 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
2189 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF,
2191 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2193 return Result;
2194
2195 QualType TP =
2196 MPP->isSugared()
2197 ? S.Context.getCanonicalTagType(MPP->getMostRecentCXXRecordDecl())
2198 : QualType(MPP->getQualifier().getAsType(), 0);
2199 assert(!TP.isNull() && "member pointer with non-type class");
2200
2201 QualType TA =
2202 MPA->isSugared()
2203 ? S.Context.getCanonicalTagType(MPA->getMostRecentCXXRecordDecl())
2204 : QualType(MPA->getQualifier().getAsType(), 0)
2206 assert(!TA.isNull() && "member pointer with non-type class");
2207
2209 S, TemplateParams, TP, TA, Info, Deduced, SubTDF,
2211 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2212 }
2213
2214 // (clang extension)
2215 //
2216 // type(^)(T)
2217 // T(^)()
2218 // T(^)(T)
2219 case Type::BlockPointer: {
2220 const auto *BPP = P->castAs<BlockPointerType>(),
2221 *BPA = A->getAs<BlockPointerType>();
2222 if (!BPA)
2225 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
2227 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2228 }
2229
2230 // (clang extension)
2231 //
2232 // T __attribute__(((ext_vector_type(<integral constant>))))
2233 case Type::ExtVector: {
2234 const auto *VP = P->castAs<ExtVectorType>();
2235 QualType ElementType;
2236 if (const auto *VA = A->getAs<ExtVectorType>()) {
2237 // Make sure that the vectors have the same number of elements.
2238 if (VP->getNumElements() != VA->getNumElements())
2240 ElementType = VA->getElementType();
2241 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2242 // We can't check the number of elements, since the argument has a
2243 // dependent number of elements. This can only occur during partial
2244 // ordering.
2245 ElementType = VA->getElementType();
2246 } else {
2248 }
2249 // Perform deduction on the element types.
2251 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
2253 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2254 }
2255
2256 case Type::DependentVector: {
2257 const auto *VP = P->castAs<DependentVectorType>();
2258
2259 if (const auto *VA = A->getAs<VectorType>()) {
2260 // Perform deduction on the element types.
2262 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2263 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2264 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2266 return Result;
2267
2268 // Perform deduction on the vector size, if we can.
2270 getNTTParameterFromExpr(Info, VP->getSizeExpr());
2271 if (!NTTP)
2273
2274 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2275 ArgSize = VA->getNumElements();
2276 // Note that we use the "array bound" rules here; just like in that
2277 // case, we don't have any particular type for the vector size, but
2278 // we can provide one if necessary.
2280 S, TemplateParams, NTTP, ArgSize, S.Context.UnsignedIntTy, true,
2281 Info, POK != PartialOrderingKind::None, Deduced,
2282 HasDeducedAnyParam);
2283 }
2284
2285 if (const auto *VA = A->getAs<DependentVectorType>()) {
2286 // Perform deduction on the element types.
2288 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2289 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2290 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2292 return Result;
2293
2294 // Perform deduction on the vector size, if we can.
2296 getNTTParameterFromExpr(Info, VP->getSizeExpr());
2297 if (!NTTP)
2299
2301 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2302 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2303 }
2304
2306 }
2307
2308 // (clang extension)
2309 //
2310 // T __attribute__(((ext_vector_type(N))))
2311 case Type::DependentSizedExtVector: {
2312 const auto *VP = P->castAs<DependentSizedExtVectorType>();
2313
2314 if (const auto *VA = A->getAs<ExtVectorType>()) {
2315 // Perform deduction on the element types.
2317 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2318 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2319 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2321 return Result;
2322
2323 // Perform deduction on the vector size, if we can.
2325 getNTTParameterFromExpr(Info, VP->getSizeExpr());
2326 if (!NTTP)
2328
2329 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2330 ArgSize = VA->getNumElements();
2331 // Note that we use the "array bound" rules here; just like in that
2332 // case, we don't have any particular type for the vector size, but
2333 // we can provide one if necessary.
2335 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2336 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2337 }
2338
2339 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2340 // Perform deduction on the element types.
2342 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2343 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2344 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2346 return Result;
2347
2348 // Perform deduction on the vector size, if we can.
2350 getNTTParameterFromExpr(Info, VP->getSizeExpr());
2351 if (!NTTP)
2353
2355 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2356 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2357 }
2358
2360 }
2361
2362 // (clang extension)
2363 //
2364 // T __attribute__((matrix_type(<integral constant>,
2365 // <integral constant>)))
2366 case Type::ConstantMatrix: {
2367 const auto *MP = P->castAs<ConstantMatrixType>(),
2368 *MA = A->getAs<ConstantMatrixType>();
2369 if (!MA)
2371
2372 // Check that the dimensions are the same
2373 if (MP->getNumRows() != MA->getNumRows() ||
2374 MP->getNumColumns() != MA->getNumColumns()) {
2376 }
2377 // Perform deduction on element types.
2379 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2381 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2382 }
2383
2384 case Type::DependentSizedMatrix: {
2385 const auto *MP = P->castAs<DependentSizedMatrixType>();
2386 const auto *MA = A->getAs<MatrixType>();
2387 if (!MA)
2389
2390 // Check the element type of the matrixes.
2392 S, TemplateParams, MP->getElementType(), MA->getElementType(),
2393 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2394 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2396 return Result;
2397
2398 // Try to deduce a matrix dimension.
2399 auto DeduceMatrixArg =
2400 [&S, &Info, &Deduced, &TemplateParams, &HasDeducedAnyParam, POK](
2401 Expr *ParamExpr, const MatrixType *A,
2402 unsigned (ConstantMatrixType::*GetArgDimension)() const,
2403 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2404 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2405 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
2406 if (!ParamExpr->isValueDependent()) {
2407 std::optional<llvm::APSInt> ParamConst =
2408 ParamExpr->getIntegerConstantExpr(S.Context);
2409 if (!ParamConst)
2411
2412 if (ACM) {
2413 if ((ACM->*GetArgDimension)() == *ParamConst)
2416 }
2417
2418 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2419 if (std::optional<llvm::APSInt> ArgConst =
2420 ArgExpr->getIntegerConstantExpr(S.Context))
2421 if (*ArgConst == *ParamConst)
2424 }
2425
2427 getNTTParameterFromExpr(Info, ParamExpr);
2428 if (!NTTP)
2430
2431 if (ACM) {
2432 llvm::APSInt ArgConst(
2434 ArgConst = (ACM->*GetArgDimension)();
2436 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
2437 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
2438 Deduced, HasDeducedAnyParam);
2439 }
2440
2442 S, TemplateParams, NTTP, (ADM->*GetArgDimensionExpr)(), Info,
2443 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2444 };
2445
2446 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
2450 return Result;
2451
2452 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2455 }
2456
2457 // (clang extension)
2458 //
2459 // T __attribute__((coop_mat_type(<integral constant>,
2460 // <integral constant>,
2461 // <integral constant>,
2462 // <integral constant>)))
2463 case Type::CooperativeMatrix: {
2464 const auto *MP = P->castAs<CooperativeMatrixType>(),
2465 *MA = A->getAs<CooperativeMatrixType>();
2466 if (!MA)
2468
2469 // Check that the dimensions, scope and use are the same
2470 if (MP->getScope() != MA->getScope() ||
2471 MP->getNumRows() != MA->getNumRows() ||
2472 MP->getNumColumns() != MA->getNumColumns() ||
2473 MP->getUse() != MA->getUse()) {
2475 }
2476 // Perform deduction on element types.
2478 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2480 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2481 }
2482
2483 // (clang extension)
2484 //
2485 // T __attribute__(((address_space(N))))
2486 case Type::DependentAddressSpace: {
2487 const auto *ASP = P->castAs<DependentAddressSpaceType>();
2488
2489 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
2490 // Perform deduction on the pointer type.
2492 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2493 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2494 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2496 return Result;
2497
2498 // Perform deduction on the address space, if we can.
2500 getNTTParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2501 if (!NTTP)
2503
2505 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info,
2506 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2507 }
2508
2510 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2511 false);
2512 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
2513
2514 // Perform deduction on the pointer types.
2516 S, TemplateParams, ASP->getPointeeType(),
2517 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF,
2519 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2521 return Result;
2522
2523 // Perform deduction on the address space, if we can.
2525 getNTTParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2526 if (!NTTP)
2528
2530 S, TemplateParams, NTTP, ArgAddressSpace, S.Context.IntTy, true,
2531 Info, POK != PartialOrderingKind::None, Deduced,
2532 HasDeducedAnyParam);
2533 }
2534
2536 }
2537 case Type::DependentBitInt: {
2538 const auto *IP = P->castAs<DependentBitIntType>();
2539
2540 if (const auto *IA = A->getAs<BitIntType>()) {
2541 if (IP->isUnsigned() != IA->isUnsigned())
2543
2545 getNTTParameterFromExpr(Info, IP->getNumBitsExpr());
2546 if (!NTTP)
2548
2549 // Deduce the size parameter of _BitInt as std::size_t
2551 llvm::APSInt ArgSize(S.Context.getTypeSize(T), /*IsUnsigned=*/true);
2552 ArgSize = IA->getNumBits();
2553
2555 S, TemplateParams, NTTP, ArgSize, T, true, Info,
2556 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2557 }
2558
2559 if (const auto *IA = A->getAs<DependentBitIntType>()) {
2560 if (IP->isUnsigned() != IA->isUnsigned())
2563 }
2564
2566 }
2567
2568 case Type::TypeOfExpr:
2569 case Type::TypeOf:
2570 case Type::DependentName:
2571 case Type::UnresolvedUsing:
2572 case Type::Decltype:
2573 case Type::UnaryTransform:
2574 case Type::DeducedTemplateSpecialization:
2575 case Type::PackExpansion:
2576 case Type::Pipe:
2577 case Type::ArrayParameter:
2578 case Type::HLSLAttributedResource:
2579 case Type::HLSLInlineSpirv:
2580 case Type::OverflowBehavior:
2581 // No template argument deduction for these types
2583
2584 case Type::PackIndexing:
2585 // C++26 [temp.deduct.type]p5.2:
2586 // The non-deduced contexts are:
2587 // [...]
2588 // - A pack-index-specifier or a pack-index-expression.
2589 assert(!P->getAs<PackIndexingType>()->hasSelectedType() &&
2590 "a pack-index-specifier with a selected type canonicalizes to "
2591 "the selected type and should not dispatch here");
2593 }
2594
2595 llvm_unreachable("Invalid Type Class!");
2596}
2597
2598/// C++26 [temp.deduct.type]p13:
2599/// When the value of the argument corresponding to a constant template
2600/// parameter P that is declared with a dependent type is deduced from an
2601/// expression, the template parameters in the type of P are deduced from the
2602/// type of the value.
2604 const TemplateArgument &A) {
2605 const Expr *E = A.getAsExpr();
2608 return NTTP.getType();
2610}
2611
2617 bool *HasDeducedAnyParam) {
2618 // If the template argument is a pack expansion, perform template argument
2619 // deduction against the pattern of that expansion. This only occurs during
2620 // partial ordering.
2621 if (A.isPackExpansion())
2623
2624 switch (P.getKind()) {
2626 llvm_unreachable("Null template argument in parameter list");
2627
2631 S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0,
2634 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2635 Info.FirstArg = P;
2636 Info.SecondArg = A;
2638
2640 // PartialOrdering does not matter here, since template specializations are
2641 // not being deduced.
2644 S, TemplateParams, P.getAsTemplate(), A.getAsTemplate(), Info,
2645 /*DefaultArguments=*/{}, /*PartialOrdering=*/false, Deduced,
2646 HasDeducedAnyParam);
2647 Info.FirstArg = P;
2648 Info.SecondArg = A;
2650
2652 llvm_unreachable("caller should handle pack expansions");
2653
2658
2659 Info.FirstArg = P;
2660 Info.SecondArg = A;
2662
2664 // 'nullptr' has only one possible value, so it always matches.
2667 Info.FirstArg = P;
2668 Info.SecondArg = A;
2670
2673 if (llvm::APSInt::isSameValue(P.getAsIntegral(), A.getAsIntegral()))
2675 }
2676 Info.FirstArg = P;
2677 Info.SecondArg = A;
2679
2681 // FIXME: structural equality will also compare types,
2682 // but they should match iff they have the same value.
2684 A.structurallyEquals(P))
2686
2687 Info.FirstArg = P;
2688 Info.SecondArg = A;
2690
2694 switch (A.getKind()) {
2697 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2699 Deduced, HasDeducedAnyParam);
2700 }
2704 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2706 HasDeducedAnyParam);
2707
2710 S, TemplateParams, NTTP, A.getNullPtrType(), Info, PartialOrdering,
2711 Deduced, HasDeducedAnyParam);
2712
2715 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
2716 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
2717
2723 Info.FirstArg = P;
2724 Info.SecondArg = A;
2726 }
2727 llvm_unreachable("Unknown template argument kind");
2728 }
2729 // Can't deduce anything, but that's okay.
2732 llvm_unreachable("Argument packs should be expanded by the caller!");
2733 }
2734
2735 llvm_unreachable("Invalid TemplateArgument Kind!");
2736}
2737
2738/// Determine whether there is a template argument to be used for
2739/// deduction.
2740///
2741/// This routine "expands" argument packs in-place, overriding its input
2742/// parameters so that \c Args[ArgIdx] will be the available template argument.
2743///
2744/// \returns true if there is another template argument (which will be at
2745/// \c Args[ArgIdx]), false otherwise.
2747 unsigned &ArgIdx) {
2748 if (ArgIdx == Args.size())
2749 return false;
2750
2751 const TemplateArgument &Arg = Args[ArgIdx];
2752 if (Arg.getKind() != TemplateArgument::Pack)
2753 return true;
2754
2755 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2756 Args = Arg.pack_elements();
2757 ArgIdx = 0;
2758 return ArgIdx < Args.size();
2759}
2760
2761/// Determine whether the given set of template arguments has a pack
2762/// expansion that is not the last template argument.
2764 bool FoundPackExpansion = false;
2765 for (const auto &A : Args) {
2766 if (FoundPackExpansion)
2767 return true;
2768
2769 if (A.getKind() == TemplateArgument::Pack)
2770 return hasPackExpansionBeforeEnd(A.pack_elements());
2771
2772 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2773 // templates, it should not be treated as a pack expansion.
2774 if (A.isPackExpansion())
2775 FoundPackExpansion = true;
2776 }
2777
2778 return false;
2779}
2780
2787 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
2788 PackFold PackFold, bool *HasDeducedAnyParam) {
2789 bool FoldPackParameter = PackFold == PackFold::ParameterToArgument ||
2791 FoldPackArgument = PackFold == PackFold::ArgumentToParameter ||
2793
2794 // C++0x [temp.deduct.type]p9:
2795 // If the template argument list of P contains a pack expansion that is not
2796 // the last template argument, the entire template argument list is a
2797 // non-deduced context.
2798 if (FoldPackParameter && hasPackExpansionBeforeEnd(Ps))
2800
2801 // C++0x [temp.deduct.type]p9:
2802 // If P has a form that contains <T> or <i>, then each argument Pi of the
2803 // respective template argument list P is compared with the corresponding
2804 // argument Ai of the corresponding template argument list of A.
2805 for (unsigned ArgIdx = 0, ParamIdx = 0; /**/; /**/) {
2807 return !FoldPackParameter && hasTemplateArgumentForDeduction(As, ArgIdx)
2810
2811 if (!Ps[ParamIdx].isPackExpansion()) {
2812 // The simple case: deduce template arguments by matching Pi and Ai.
2813
2814 // Check whether we have enough arguments.
2815 if (!hasTemplateArgumentForDeduction(As, ArgIdx))
2816 return !FoldPackArgument && NumberOfArgumentsMustMatch
2819
2820 if (As[ArgIdx].isPackExpansion()) {
2821 // C++1z [temp.deduct.type]p9:
2822 // During partial ordering, if Ai was originally a pack expansion
2823 // [and] Pi is not a pack expansion, template argument deduction
2824 // fails.
2825 if (!FoldPackArgument)
2827
2828 TemplateArgument Pattern = As[ArgIdx].getPackExpansionPattern();
2829 for (;;) {
2830 // Deduce template parameters from the pattern.
2832 S, TemplateParams, Ps[ParamIdx], Pattern, Info,
2833 PartialOrdering, Deduced, HasDeducedAnyParam);
2835 return Result;
2836
2837 ++ParamIdx;
2840 if (Ps[ParamIdx].isPackExpansion())
2841 break;
2842 }
2843 } else {
2844 // Perform deduction for this Pi/Ai pair.
2846 S, TemplateParams, Ps[ParamIdx], As[ArgIdx], Info,
2847 PartialOrdering, Deduced, HasDeducedAnyParam);
2849 return Result;
2850
2851 ++ArgIdx;
2852 ++ParamIdx;
2853 continue;
2854 }
2855 }
2856
2857 // The parameter is a pack expansion.
2858
2859 // C++0x [temp.deduct.type]p9:
2860 // If Pi is a pack expansion, then the pattern of Pi is compared with
2861 // each remaining argument in the template argument list of A. Each
2862 // comparison deduces template arguments for subsequent positions in the
2863 // template parameter packs expanded by Pi.
2864 TemplateArgument Pattern = Ps[ParamIdx].getPackExpansionPattern();
2865
2866 // Prepare to deduce the packs within the pattern.
2867 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2868
2869 // Keep track of the deduced template arguments for each parameter pack
2870 // expanded by this pack expansion (the outer index) and for each
2871 // template argument (the inner SmallVectors).
2872 for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
2873 PackScope.hasNextElement();
2874 ++ArgIdx) {
2875 if (!As[ArgIdx].isPackExpansion()) {
2876 if (!FoldPackParameter)
2878 if (FoldPackArgument)
2879 Info.setStrictPackMatch();
2880 }
2881 // Deduce template arguments from the pattern.
2883 S, TemplateParams, Pattern, As[ArgIdx], Info, PartialOrdering,
2884 Deduced, HasDeducedAnyParam);
2886 return Result;
2887
2888 PackScope.nextPackElement();
2889 }
2890
2891 // Build argument packs for each of the parameter packs expanded by this
2892 // pack expansion.
2893 return PackScope.finish();
2894 }
2895}
2896
2901 bool NumberOfArgumentsMustMatch) {
2902 return ::DeduceTemplateArguments(
2903 *this, TemplateParams, Ps, As, Info, Deduced, NumberOfArgumentsMustMatch,
2904 /*PartialOrdering=*/false, PackFold::ParameterToArgument,
2905 /*HasDeducedAnyParam=*/nullptr);
2906}
2907
2910 QualType NTTPType, SourceLocation Loc) {
2911 switch (Arg.getKind()) {
2913 llvm_unreachable("Can't get a NULL template argument here");
2914
2916 return TemplateArgumentLoc(
2917 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2918
2920 if (NTTPType.isNull())
2921 NTTPType = Arg.getParamTypeForDecl();
2922 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2923 .getAs<Expr>();
2924 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
2925 }
2926
2928 if (NTTPType.isNull())
2929 NTTPType = Arg.getNullPtrType();
2930 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2931 .getAs<Expr>();
2932 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2933 E);
2934 }
2935
2939 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
2940 }
2941
2946 Builder.MakeTrivial(Context, Template.getQualifier(), Loc);
2947 return TemplateArgumentLoc(
2948 Context, Arg, Loc, Builder.getWithLocInContext(Context), Loc,
2949 /*EllipsisLoc=*/Arg.getKind() == TemplateArgument::TemplateExpansion
2950 ? Loc
2951 : SourceLocation());
2952 }
2953
2955 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2956
2959 }
2960
2961 llvm_unreachable("Invalid TemplateArgument Kind!");
2962}
2963
2966 SourceLocation Location) {
2968 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2969}
2970
2971/// Convert the given deduced template argument and add it to the set of
2972/// fully-converted template arguments.
2973static bool
2976 TemplateDeductionInfo &Info, bool IsDeduced,
2978 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2979 unsigned ArgumentPackIndex) {
2980 // Convert the deduced template argument into a template
2981 // argument that we can check, almost as if the user had written
2982 // the template argument explicitly.
2983 TemplateArgumentLoc ArgLoc =
2985
2986 SaveAndRestore _1(CTAI.MatchingTTP, false);
2987 SaveAndRestore _2(CTAI.StrictPackMatch, false);
2988 // Check the template argument, converting it as necessary.
2989 auto Res = S.CheckTemplateArgument(
2990 Param, ArgLoc, Template, Template->getLocation(),
2991 Template->getSourceRange().getEnd(), ArgumentPackIndex, CTAI,
2992 IsDeduced
2996 if (CTAI.StrictPackMatch)
2997 Info.setStrictPackMatch();
2998 return Res;
2999 };
3000
3001 if (Arg.getKind() == TemplateArgument::Pack) {
3002 // This is a template argument pack, so check each of its arguments against
3003 // the template parameter.
3004 SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
3005 CanonicalPackedArgsBuilder;
3006 for (const auto &P : Arg.pack_elements()) {
3007 // When converting the deduced template argument, append it to the
3008 // general output list. We need to do this so that the template argument
3009 // checking logic has all of the prior template arguments available.
3010 DeducedTemplateArgument InnerArg(P);
3012 assert(InnerArg.getKind() != TemplateArgument::Pack &&
3013 "deduced nested pack");
3014 if (P.isNull()) {
3015 // We deduced arguments for some elements of this pack, but not for
3016 // all of them. This happens if we get a conditionally-non-deduced
3017 // context in a pack expansion (such as an overload set in one of the
3018 // arguments).
3019 S.Diag(Param->getLocation(),
3020 diag::err_template_arg_deduced_incomplete_pack)
3021 << Arg << Param;
3022 return true;
3023 }
3024 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
3025 return true;
3026
3027 // Move the converted template argument into our argument pack.
3028 SugaredPackedArgsBuilder.push_back(CTAI.SugaredConverted.pop_back_val());
3029 CanonicalPackedArgsBuilder.push_back(
3030 CTAI.CanonicalConverted.pop_back_val());
3031 }
3032
3033 // If the pack is empty, we still need to substitute into the parameter
3034 // itself, in case that substitution fails.
3035 if (SugaredPackedArgsBuilder.empty()) {
3038 /*Final=*/true);
3039 Sema::ArgPackSubstIndexRAII OnlySubstNonPackExpansion(S, std::nullopt);
3040
3041 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3042 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
3043 NTTP, CTAI.SugaredConverted,
3044 Template->getSourceRange());
3045 if (Inst.isInvalid() ||
3046 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
3047 NTTP->getDeclName()).isNull())
3048 return true;
3049 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3050 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
3051 TTP, CTAI.SugaredConverted,
3052 Template->getSourceRange());
3053 if (Inst.isInvalid() ||
3054 !S.SubstTemplateParams(TTP->getTemplateParameters(), S.CurContext,
3055 Args))
3056 return true;
3057 }
3058 // For type parameters, no substitution is ever required.
3059 }
3060
3061 // Create the resulting argument pack.
3062 CTAI.SugaredConverted.push_back(
3063 TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
3065 S.Context, CanonicalPackedArgsBuilder));
3066 return false;
3067 }
3068
3069 return ConvertArg(Arg, 0);
3070}
3071
3072/// \param IsIncomplete When used, we only consider template parameters that
3073/// were deduced, disregarding any default arguments. After the function
3074/// finishes, the object pointed at will contain a value indicating if the
3075/// conversion was actually incomplete.
3077 Sema &S, NamedDecl *Template, TemplateParameterList *TemplateParams,
3080 LocalInstantiationScope *CurrentInstantiationScope,
3081 unsigned NumAlreadyConverted, bool *IsIncomplete) {
3082 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3083 NamedDecl *Param = TemplateParams->getParam(I);
3084
3085 // C++0x [temp.arg.explicit]p3:
3086 // A trailing template parameter pack (14.5.3) not otherwise deduced will
3087 // be deduced to an empty sequence of template arguments.
3088 // FIXME: Where did the word "trailing" come from?
3089 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
3090 if (auto Result =
3091 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish();
3093 return Result;
3094 }
3095
3096 if (!Deduced[I].isNull()) {
3097 if (I < NumAlreadyConverted) {
3098 // We may have had explicitly-specified template arguments for a
3099 // template parameter pack (that may or may not have been extended
3100 // via additional deduced arguments).
3101 if (Param->isParameterPack() && CurrentInstantiationScope &&
3102 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
3103 // Forget the partially-substituted pack; its substitution is now
3104 // complete.
3105 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
3106 // We still need to check the argument in case it was extended by
3107 // deduction.
3108 } else {
3109 // We have already fully type-checked and converted this
3110 // argument, because it was explicitly-specified. Just record the
3111 // presence of this argument.
3112 CTAI.SugaredConverted.push_back(Deduced[I]);
3113 CTAI.CanonicalConverted.push_back(
3115 continue;
3116 }
3117 }
3118
3119 // We may have deduced this argument, so it still needs to be
3120 // checked and converted.
3121 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
3122 IsDeduced, CTAI)) {
3123 Info.Param = makeTemplateParameter(Param);
3124 // FIXME: These template arguments are temporary. Free them!
3125 Info.reset(
3128 CTAI.CanonicalConverted));
3130 }
3131
3132 continue;
3133 }
3134
3135 // [C++26][temp.deduct.partial]p12 - When partial ordering, it's ok for
3136 // template parameters to remain not deduced. As a provisional fix for a
3137 // core issue that does not exist yet, which may be related to CWG2160, only
3138 // consider template parameters that were deduced, disregarding any default
3139 // arguments.
3140 if (IsIncomplete) {
3141 *IsIncomplete = true;
3142 CTAI.SugaredConverted.push_back({});
3143 CTAI.CanonicalConverted.push_back({});
3144 continue;
3145 }
3146
3147 // Substitute into the default template argument, if available.
3148 bool HasDefaultArg = false;
3149 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
3150 if (!TD) {
3154 }
3155
3156 TemplateArgumentLoc DefArg;
3157 {
3158 Qualifiers ThisTypeQuals;
3159 CXXRecordDecl *ThisContext = nullptr;
3160 if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
3161 if (Rec->isLambda())
3162 if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
3163 ThisContext = Method->getParent();
3164 ThisTypeQuals = Method->getMethodQualifiers();
3165 }
3166
3167 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
3168 S.getLangOpts().CPlusPlus17);
3169
3171 TD, /*TemplateKWLoc=*/SourceLocation(), TD->getLocation(),
3172 TD->getSourceRange().getEnd(), Param, CTAI.SugaredConverted,
3173 CTAI.CanonicalConverted, HasDefaultArg);
3174 }
3175
3176 // If there was no default argument, deduction is incomplete.
3177 if (DefArg.getArgument().isNull()) {
3178 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3179 Info.reset(
3182
3185 }
3186
3187 SaveAndRestore _1(CTAI.PartialOrdering, false);
3188 SaveAndRestore _2(CTAI.MatchingTTP, false);
3189 SaveAndRestore _3(CTAI.StrictPackMatch, false);
3190 // Check whether we can actually use the default argument.
3192 Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
3193 /*ArgumentPackIndex=*/0, CTAI, Sema::CTAK_Specified)) {
3194 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3195 // FIXME: These template arguments are temporary. Free them!
3196 Info.reset(
3200 }
3201
3202 // If we get here, we successfully used the default template argument.
3203 }
3204
3206}
3207
3209 if (auto *DC = dyn_cast<DeclContext>(D))
3210 return DC;
3211 return D->getDeclContext();
3212}
3213
3214template<typename T> struct IsPartialSpecialization {
3215 static constexpr bool value = false;
3216};
3217template<>
3221template<>
3223 static constexpr bool value = true;
3224};
3225
3228 ArrayRef<TemplateArgument> SugaredDeducedArgs,
3229 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
3230 TemplateDeductionInfo &Info) {
3231 llvm::SmallVector<AssociatedConstraint, 3> AssociatedConstraints;
3232 bool DeducedArgsNeedReplacement = false;
3233 if (auto *TD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Template)) {
3234 TD->getAssociatedConstraints(AssociatedConstraints);
3235 DeducedArgsNeedReplacement = !TD->isClassScopeExplicitSpecialization();
3236 } else if (auto *TD =
3237 dyn_cast<VarTemplatePartialSpecializationDecl>(Template)) {
3238 TD->getAssociatedConstraints(AssociatedConstraints);
3239 DeducedArgsNeedReplacement = !TD->isClassScopeExplicitSpecialization();
3240 } else {
3241 cast<TemplateDecl>(Template)->getAssociatedConstraints(
3242 AssociatedConstraints);
3243 }
3244
3245 std::optional<ArrayRef<TemplateArgument>> Innermost;
3246 // If we don't need to replace the deduced template arguments,
3247 // we can add them immediately as the inner-most argument list.
3248 if (!DeducedArgsNeedReplacement)
3249 Innermost = SugaredDeducedArgs;
3250
3252 Template, Template->getDeclContext(), /*Final=*/false, Innermost,
3253 /*RelativeToPrimary=*/true, /*Pattern=*/
3254 nullptr, /*ForConstraintInstantiation=*/true);
3255
3256 // getTemplateInstantiationArgs picks up the non-deduced version of the
3257 // template args when this is a variable template partial specialization and
3258 // not class-scope explicit specialization, so replace with Deduced Args
3259 // instead of adding to inner-most.
3260 if (!Innermost)
3261 MLTAL.replaceInnermostTemplateArguments(Template, SugaredDeducedArgs);
3262
3263 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
3264 Info.getLocation(),
3267 Info.reset(
3268 TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
3269 TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
3271 }
3273}
3274
3278 TemplateDeductionInfo &Info) {
3279 TemplateParameterList *TPL = Template->getTemplateParameters();
3280 TemplateArgumentListInfo InstArgs(TPL->getLAngleLoc(), TPL->getRAngleLoc());
3281 if (S.SubstTemplateArguments(Ps, MLTAL, InstArgs)) {
3282 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
3283 if (ParamIdx >= TPL->size())
3284 ParamIdx = TPL->size() - 1;
3285
3286 Decl *Param = TPL->getParam(ParamIdx);
3287 Info.Param = makeTemplateParameter(Param);
3288 Info.FirstArg = Ps[ArgIdx].getArgument();
3290 }
3291
3294 if (S.CheckTemplateArgumentList(Template, Template->getLocation(), InstArgs,
3295 /*DefaultArgs=*/{}, false, InstCTAI,
3296 /*UpdateArgsWithConversions=*/true,
3301
3302 // Check that we produced the correct argument list.
3304 AsStack{As};
3305 for (;;) {
3306 auto take = [](SmallVectorImpl<ArrayRef<TemplateArgument>> &Stack)
3308 while (!Stack.empty()) {
3309 auto &Xs = Stack.back();
3310 if (Xs.empty()) {
3311 Stack.pop_back();
3312 continue;
3313 }
3314 auto &X = Xs.front();
3315 if (X.getKind() == TemplateArgument::Pack) {
3316 Stack.emplace_back(X.getPackAsArray());
3317 Xs = Xs.drop_front();
3318 continue;
3319 }
3320 assert(!X.isNull());
3321 return {Xs, X};
3322 }
3323 static constexpr ArrayRef<TemplateArgument> None;
3324 return {const_cast<ArrayRef<TemplateArgument> &>(None),
3326 };
3327 auto [Ps, P] = take(PsStack);
3328 auto [As, A] = take(AsStack);
3329 if (P.isNull() && A.isNull())
3330 break;
3331 TemplateArgument PP = P.isPackExpansion() ? P.getPackExpansionPattern() : P,
3332 PA = A.isPackExpansion() ? A.getPackExpansionPattern() : A;
3333 if (!S.Context.isSameTemplateArgument(PP, PA)) {
3334 if (!P.isPackExpansion() && !A.isPackExpansion()) {
3336 (AsStack.empty() ? As.end() : AsStack.back().begin()) -
3337 As.begin()));
3338 Info.FirstArg = P;
3339 Info.SecondArg = A;
3341 }
3342 if (P.isPackExpansion()) {
3343 Ps = Ps.drop_front();
3344 continue;
3345 }
3346 if (A.isPackExpansion()) {
3347 As = As.drop_front();
3348 continue;
3349 }
3350 }
3351 Ps = Ps.drop_front(P.isPackExpansion() ? 0 : 1);
3352 As = As.drop_front(A.isPackExpansion() && !P.isPackExpansion() ? 0 : 1);
3353 }
3354 assert(PsStack.empty());
3355 assert(AsStack.empty());
3357}
3358
3359/// Complete template argument deduction.
3361 Sema &S, NamedDecl *Entity, TemplateParameterList *EntityTPL,
3365 TemplateDeductionInfo &Info, bool CopyDeducedArgs) {
3366 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Entity));
3367
3368 // C++ [temp.deduct.type]p2:
3369 // [...] or if any template argument remains neither deduced nor
3370 // explicitly specified, template argument deduction fails.
3373 S, Entity, EntityTPL, /*IsDeduced=*/PartialOrdering, Deduced, Info,
3374 CTAI,
3375 /*CurrentInstantiationScope=*/nullptr,
3376 /*NumAlreadyConverted=*/0U, /*IsIncomplete=*/nullptr);
3378 return Result;
3379
3380 if (CopyDeducedArgs) {
3381 // Form the template argument list from the deduced template arguments.
3382 TemplateArgumentList *SugaredDeducedArgumentList =
3384 TemplateArgumentList *CanonicalDeducedArgumentList =
3386 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3387 }
3388
3390 /*Final=*/true);
3391 MLTAL.addOuterRetainedLevels(Template->getTemplateParameters()->getDepth());
3392 if (auto Result =
3393 CheckDeducedTemplateArgumentList(S, Template, Ps, As, MLTAL, Info);
3395 return Result;
3396
3397 if (!PartialOrdering) {
3399 S, Entity, CTAI.SugaredConverted, CTAI.CanonicalConverted, Info);
3401 return Result;
3402 }
3403
3405}
3407 Sema &S, NamedDecl *Entity, TemplateParameterList *EntityTPL,
3411 TemplateDeductionInfo &Info, bool CopyDeducedArgs) {
3412 TemplateParameterList *TPL = Template->getTemplateParameters();
3413 SmallVector<TemplateArgumentLoc, 8> PsLoc(Ps.size());
3414 for (unsigned I = 0, N = Ps.size(); I != N; ++I)
3415 PsLoc[I] = S.getTrivialTemplateArgumentLoc(Ps[I], QualType(),
3416 TPL->getParam(I)->getLocation());
3417 return FinishTemplateArgumentDeduction(S, Entity, EntityTPL, Template,
3418 PartialOrdering, PsLoc, As, Deduced,
3419 Info, CopyDeducedArgs);
3420}
3421
3422/// Complete template argument deduction for DeduceTemplateArgumentsFromType.
3423/// FIXME: this is mostly duplicated with the above two versions. Deduplicate
3424/// the three implementations.
3426 Sema &S, TemplateDecl *TD,
3428 TemplateDeductionInfo &Info) {
3430
3431 // C++ [temp.deduct.type]p2:
3432 // [...] or if any template argument remains neither deduced nor
3433 // explicitly specified, template argument deduction fails.
3436 S, TD, TD->getTemplateParameters(), /*IsDeduced=*/false, Deduced,
3437 Info, CTAI,
3438 /*CurrentInstantiationScope=*/nullptr, /*NumAlreadyConverted=*/0,
3439 /*IsIncomplete=*/nullptr);
3441 return Result;
3442
3443 return ::CheckDeducedArgumentConstraints(S, TD, CTAI.SugaredConverted,
3444 CTAI.CanonicalConverted, Info);
3445}
3446
3447/// Perform template argument deduction to determine whether the given template
3448/// arguments match the given class or variable template partial specialization
3449/// per C++ [temp.class.spec.match].
3450template <typename T>
3451static std::enable_if_t<IsPartialSpecialization<T>::value,
3454 ArrayRef<TemplateArgument> TemplateArgs,
3455 TemplateDeductionInfo &Info) {
3456 if (Partial->isInvalidDecl())
3458
3459 // C++ [temp.class.spec.match]p2:
3460 // A partial specialization matches a given actual template
3461 // argument list if the template arguments of the partial
3462 // specialization can be deduced from the actual template argument
3463 // list (14.8.2).
3464
3465 // Unevaluated SFINAE context.
3468 Sema::SFINAETrap Trap(S, Info);
3469
3470 // This deduction has no relation to any outer instantiation we might be
3471 // performing.
3472 LocalInstantiationScope InstantiationScope(S);
3473
3475 Deduced.resize(Partial->getTemplateParameters()->size());
3477 S, Partial->getTemplateParameters(),
3478 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3479 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/false,
3481 /*HasDeducedAnyParam=*/nullptr);
3483 return Result;
3484
3485 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3486 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs);
3487 if (Inst.isInvalid())
3489
3492 Result = ::FinishTemplateArgumentDeduction(
3493 S, Partial, Partial->getTemplateParameters(),
3494 Partial->getSpecializedTemplate(),
3495 /*IsPartialOrdering=*/false,
3496 Partial->getTemplateArgsAsWritten()->arguments(), TemplateArgs, Deduced,
3497 Info, /*CopyDeducedArgs=*/true);
3498 });
3499
3501 return Result;
3502
3503 if (Trap.hasErrorOccurred())
3505
3507}
3508
3511 ArrayRef<TemplateArgument> TemplateArgs,
3512 TemplateDeductionInfo &Info) {
3513 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3514}
3517 ArrayRef<TemplateArgument> TemplateArgs,
3518 TemplateDeductionInfo &Info) {
3519 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3520}
3521
3525 if (TD->isInvalidDecl())
3527
3528 QualType PType;
3529 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
3530 // Use the InjectedClassNameType.
3531 PType = Context.getCanonicalTagType(CTD->getTemplatedDecl());
3532 } else if (const auto *AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(TD)) {
3533 PType = AliasTemplate->getTemplatedDecl()->getUnderlyingType();
3534 } else {
3535 assert(false && "Expected a class or alias template");
3536 }
3537
3538 // Unevaluated SFINAE context.
3541 SFINAETrap Trap(*this, Info);
3542
3543 // This deduction has no relation to any outer instantiation we might be
3544 // performing.
3545 LocalInstantiationScope InstantiationScope(*this);
3546
3548 TD->getTemplateParameters()->size());
3551 if (auto DeducedResult = DeduceTemplateArguments(
3552 TD->getTemplateParameters(), PArgs, AArgs, Info, Deduced, false);
3553 DeducedResult != TemplateDeductionResult::Success) {
3554 return DeducedResult;
3555 }
3556
3557 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3558 InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs);
3559 if (Inst.isInvalid())
3561
3564 Result = ::FinishTemplateArgumentDeduction(*this, TD, Deduced, Info);
3565 });
3566
3568 return Result;
3569
3570 if (Trap.hasErrorOccurred())
3572
3574}
3575
3576/// Determine whether the given type T is a simple-template-id type.
3578 if (const TemplateSpecializationType *Spec
3579 = T->getAs<TemplateSpecializationType>())
3580 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
3581
3582 // C++17 [temp.local]p2:
3583 // the injected-class-name [...] is equivalent to the template-name followed
3584 // by the template-arguments of the class template specialization or partial
3585 // specialization enclosed in <>
3586 // ... which means it's equivalent to a simple-template-id.
3587 //
3588 // This only arises during class template argument deduction for a copy
3589 // deduction candidate, where it permits slicing.
3590 if (isa<InjectedClassNameType>(T.getCanonicalType()))
3591 return true;
3592
3593 return false;
3594}
3595
3598 TemplateArgumentListInfo &ExplicitTemplateArgs,
3601 TemplateDeductionInfo &Info) {
3602 assert(isSFINAEContext());
3603 assert(isUnevaluatedContext());
3604
3605 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3606 TemplateParameterList *TemplateParams
3607 = FunctionTemplate->getTemplateParameters();
3608
3609 if (ExplicitTemplateArgs.size() == 0) {
3610 // No arguments to substitute; just copy over the parameter types and
3611 // fill in the function type.
3612 for (auto *P : Function->parameters())
3613 ParamTypes.push_back(P->getType());
3614
3615 if (FunctionType)
3616 *FunctionType = Function->getType();
3618 }
3619
3620 // C++ [temp.arg.explicit]p3:
3621 // Template arguments that are present shall be specified in the
3622 // declaration order of their corresponding template-parameters. The
3623 // template argument list shall not specify more template-arguments than
3624 // there are corresponding template-parameters.
3625
3626 // Enter a new template instantiation context where we check the
3627 // explicitly-specified template arguments against this function template,
3628 // and then substitute them into the function parameter types.
3631 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3633 if (Inst.isInvalid())
3635
3638 ExplicitTemplateArgs, /*DefaultArgs=*/{},
3639 /*PartialTemplateArgs=*/true, CTAI,
3640 /*UpdateArgsWithConversions=*/false)) {
3641 unsigned Index = CTAI.SugaredConverted.size();
3642 if (Index >= TemplateParams->size())
3644 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3646 }
3647
3648 // Form the template argument list from the explicitly-specified
3649 // template arguments.
3650 TemplateArgumentList *SugaredExplicitArgumentList =
3652 TemplateArgumentList *CanonicalExplicitArgumentList =
3654 Info.setExplicitArgs(SugaredExplicitArgumentList,
3655 CanonicalExplicitArgumentList);
3656
3657 // Template argument deduction and the final substitution should be
3658 // done in the context of the templated declaration. Explicit
3659 // argument substitution, on the other hand, needs to happen in the
3660 // calling context.
3661 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3662
3663 // If we deduced template arguments for a template parameter pack,
3664 // note that the template argument pack is partially substituted and record
3665 // the explicit template arguments. They'll be used as part of deduction
3666 // for this template parameter pack.
3667 unsigned PartiallySubstitutedPackIndex = -1u;
3668 if (!CTAI.SugaredConverted.empty()) {
3669 const TemplateArgument &Arg = CTAI.SugaredConverted.back();
3670 if (Arg.getKind() == TemplateArgument::Pack) {
3671 auto *Param = TemplateParams->getParam(CTAI.SugaredConverted.size() - 1);
3672 // If this is a fully-saturated fixed-size pack, it should be
3673 // fully-substituted, not partially-substituted.
3674 UnsignedOrNone Expansions = getExpandedPackSize(Param);
3675 if (!Expansions || Arg.pack_size() < *Expansions) {
3676 PartiallySubstitutedPackIndex = CTAI.SugaredConverted.size() - 1;
3677 CurrentInstantiationScope->SetPartiallySubstitutedPack(
3678 Param, Arg.pack_begin(), Arg.pack_size());
3679 }
3680 }
3681 }
3682
3683 const FunctionProtoType *Proto
3684 = Function->getType()->getAs<FunctionProtoType>();
3685 assert(Proto && "Function template does not have a prototype?");
3686
3687 // Isolate our substituted parameters from our caller.
3688 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3689
3690 ExtParameterInfoBuilder ExtParamInfos;
3691
3693 SugaredExplicitArgumentList->asArray(),
3694 /*Final=*/true);
3695
3696 // Instantiate the types of each of the function parameters given the
3697 // explicitly-specified template arguments. If the function has a trailing
3698 // return type, substitute it after the arguments to ensure we substitute
3699 // in lexical order.
3700 if (Proto->hasTrailingReturn()) {
3701 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3702 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3703 /*params=*/nullptr, ExtParamInfos))
3705 }
3706
3707 // Instantiate the return type.
3708 QualType ResultType;
3709 {
3710 // C++11 [expr.prim.general]p3:
3711 // If a declaration declares a member function or member function
3712 // template of a class X, the expression this is a prvalue of type
3713 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3714 // and the end of the function-definition, member-declarator, or
3715 // declarator.
3716 Qualifiers ThisTypeQuals;
3717 CXXRecordDecl *ThisContext = nullptr;
3718 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3719 ThisContext = Method->getParent();
3720 ThisTypeQuals = Method->getMethodQualifiers();
3721 }
3722
3723 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3725
3726 ResultType =
3727 SubstType(Proto->getReturnType(), MLTAL,
3728 Function->getTypeSpecStartLoc(), Function->getDeclName());
3729 if (ResultType.isNull())
3731 // CUDA: Kernel function must have 'void' return type.
3732 if (getLangOpts().CUDA)
3733 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3734 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3735 << Function->getType() << Function->getSourceRange();
3737 }
3738 }
3739
3740 // Instantiate the types of each of the function parameters given the
3741 // explicitly-specified template arguments if we didn't do so earlier.
3742 if (!Proto->hasTrailingReturn() &&
3743 SubstParmTypes(Function->getLocation(), Function->parameters(),
3744 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3745 /*params*/ nullptr, ExtParamInfos))
3747
3748 if (FunctionType) {
3749 auto EPI = Proto->getExtProtoInfo();
3750 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3751 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3752 Function->getLocation(),
3753 Function->getDeclName(),
3754 EPI);
3755 if (FunctionType->isNull())
3757 }
3758
3759 // C++ [temp.arg.explicit]p2:
3760 // Trailing template arguments that can be deduced (14.8.2) may be
3761 // omitted from the list of explicit template-arguments. If all of the
3762 // template arguments can be deduced, they may all be omitted; in this
3763 // case, the empty template argument list <> itself may also be omitted.
3764 //
3765 // Take all of the explicitly-specified arguments and put them into
3766 // the set of deduced template arguments. The partially-substituted
3767 // parameter pack, however, will be set to NULL since the deduction
3768 // mechanism handles the partially-substituted argument pack directly.
3769 Deduced.reserve(TemplateParams->size());
3770 for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3771 const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
3772 if (I == PartiallySubstitutedPackIndex)
3773 Deduced.push_back(DeducedTemplateArgument());
3774 else
3775 Deduced.push_back(Arg);
3776 }
3777
3779}
3780
3781/// Check whether the deduced argument type for a call to a function
3782/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3785 Sema::OriginalCallArg OriginalArg,
3786 QualType DeducedA) {
3787 ASTContext &Context = S.Context;
3788
3789 auto Failed = [&]() -> TemplateDeductionResult {
3790 Info.FirstArg = TemplateArgument(DeducedA);
3791 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3792 Info.CallArgIndex = OriginalArg.ArgIdx;
3793 return OriginalArg.DecomposedParam
3796 };
3797
3798 QualType A = OriginalArg.OriginalArgType;
3799 QualType OriginalParamType = OriginalArg.OriginalParamType;
3800
3801 // Check for type equality (top-level cv-qualifiers and _Atomic are ignored,
3802 // since _Atomic is treated as a qualifier).
3803 if (Context.hasSameType(A.getAtomicUnqualifiedType(),
3804 DeducedA.getAtomicUnqualifiedType()))
3806
3807 // Strip off references on the argument types; they aren't needed for
3808 // the following checks.
3809 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3810 DeducedA = DeducedARef->getPointeeType();
3811 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3812 A = ARef->getPointeeType();
3813
3814 // C++ [temp.deduct.call]p4:
3815 // [...] However, there are three cases that allow a difference:
3816 // - If the original P is a reference type, the deduced A (i.e., the
3817 // type referred to by the reference) can be more cv-qualified than
3818 // the transformed A.
3819 if (const ReferenceType *OriginalParamRef
3820 = OriginalParamType->getAs<ReferenceType>()) {
3821 // We don't want to keep the reference around any more.
3822 OriginalParamType = OriginalParamRef->getPointeeType();
3823
3824 // FIXME: Resolve core issue (no number yet): if the original P is a
3825 // reference type and the transformed A is function type "noexcept F",
3826 // the deduced A can be F.
3827 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA))
3829
3830 Qualifiers AQuals = A.getQualifiers();
3831 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3832
3833 // Under Objective-C++ ARC, the deduced type may have implicitly
3834 // been given strong or (when dealing with a const reference)
3835 // unsafe_unretained lifetime. If so, update the original
3836 // qualifiers to include this lifetime.
3837 if (S.getLangOpts().ObjCAutoRefCount &&
3838 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3840 (DeducedAQuals.hasConst() &&
3841 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3842 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3843 }
3844
3845 if (AQuals == DeducedAQuals) {
3846 // Qualifiers match; there's nothing to do.
3847 } else if (!DeducedAQuals.compatiblyIncludes(AQuals, S.getASTContext())) {
3848 return Failed();
3849 } else {
3850 // Qualifiers are compatible, so have the argument type adopt the
3851 // deduced argument type's qualifiers as if we had performed the
3852 // qualification conversion.
3853 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3854 }
3855 }
3856
3857 // - The transformed A can be another pointer or pointer to member
3858 // type that can be converted to the deduced A via a function pointer
3859 // conversion and/or a qualification conversion.
3860 //
3861 // Also allow conversions which merely strip __attribute__((noreturn)) from
3862 // function types (recursively).
3863 bool ObjCLifetimeConversion = false;
3864 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3865 (S.IsQualificationConversion(A, DeducedA, false,
3866 ObjCLifetimeConversion) ||
3867 S.IsFunctionConversion(A, DeducedA)))
3869
3870 // - If P is a class and P has the form simple-template-id, then the
3871 // transformed A can be a derived class of the deduced A. [...]
3872 // [...] Likewise, if P is a pointer to a class of the form
3873 // simple-template-id, the transformed A can be a pointer to a
3874 // derived class pointed to by the deduced A.
3875 if (const PointerType *OriginalParamPtr
3876 = OriginalParamType->getAs<PointerType>()) {
3877 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3878 if (const PointerType *APtr = A->getAs<PointerType>()) {
3879 if (A->getPointeeType()->isRecordType()) {
3880 OriginalParamType = OriginalParamPtr->getPointeeType();
3881 DeducedA = DeducedAPtr->getPointeeType();
3882 A = APtr->getPointeeType();
3883 }
3884 }
3885 }
3886 }
3887
3888 if (Context.hasSameUnqualifiedType(A, DeducedA))
3890
3891 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3892 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3894
3895 return Failed();
3896}
3897
3898/// Find the pack index for a particular parameter index in an instantiation of
3899/// a function template with specific arguments.
3900///
3901/// \return The pack index for whichever pack produced this parameter, or -1
3902/// if this was not produced by a parameter. Intended to be used as the
3903/// ArgumentPackSubstitutionIndex for further substitutions.
3904// FIXME: We should track this in OriginalCallArgs so we don't need to
3905// reconstruct it here.
3906static UnsignedOrNone
3909 unsigned ParamIdx) {
3910 unsigned Idx = 0;
3911 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3912 if (PD->isParameterPack()) {
3913 UnsignedOrNone NumArgs =
3914 S.getNumArgumentsInExpansion(PD->getType(), Args);
3915 unsigned NumExpansions = NumArgs ? *NumArgs : 1;
3916 if (Idx + NumExpansions > ParamIdx)
3917 return ParamIdx - Idx;
3918 Idx += NumExpansions;
3919 } else {
3920 if (Idx == ParamIdx)
3921 return std::nullopt; // Not a pack expansion
3922 ++Idx;
3923 }
3924 }
3925
3926 llvm_unreachable("parameter index would not be produced from template");
3927}
3928
3929// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`,
3930// we'll try to instantiate and update its explicit specifier after constraint
3931// checking.
3934 const MultiLevelTemplateArgumentList &SubstArgs,
3936 ArrayRef<TemplateArgument> DeducedArgs) {
3937 auto GetExplicitSpecifier = [](FunctionDecl *D) {
3938 return isa<CXXConstructorDecl>(D)
3939 ? cast<CXXConstructorDecl>(D)->getExplicitSpecifier()
3940 : cast<CXXConversionDecl>(D)->getExplicitSpecifier();
3941 };
3942 auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) {
3944 ? cast<CXXConstructorDecl>(D)->setExplicitSpecifier(ES)
3945 : cast<CXXConversionDecl>(D)->setExplicitSpecifier(ES);
3946 };
3947
3948 ExplicitSpecifier ES = GetExplicitSpecifier(Specialization);
3949 Expr *ExplicitExpr = ES.getExpr();
3950 if (!ExplicitExpr)
3952 if (!ExplicitExpr->isValueDependent())
3954
3955 // By this point, FinishTemplateArgumentDeduction will have been reverted back
3956 // to a regular non-SFINAE template instantiation context, so setup a new
3957 // SFINAE context.
3959 S, Info.getLocation(), FunctionTemplate, DeducedArgs,
3961 if (Inst.isInvalid())
3963 Sema::SFINAETrap Trap(S, Info);
3964 const ExplicitSpecifier InstantiatedES =
3965 S.instantiateExplicitSpecifier(SubstArgs, ES);
3966 if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) {
3967 Specialization->setInvalidDecl(true);
3969 }
3970 SetExplicitSpecifier(Specialization, InstantiatedES);
3972}
3973
3977 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3979 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3980 bool PartialOverloading, bool PartialOrdering,
3981 bool ForOverloadSetAddressResolution,
3982 llvm::function_ref<bool(bool)> CheckNonDependent) {
3983 // Enter a new template instantiation context while we instantiate the
3984 // actual function declaration.
3985 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3987 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3989 if (Inst.isInvalid())
3991
3992 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3993
3994 // C++ [temp.deduct.type]p2:
3995 // [...] or if any template argument remains neither deduced nor
3996 // explicitly specified, template argument deduction fails.
3997 bool IsIncomplete = false;
4000 *this, FunctionTemplate, FunctionTemplate->getTemplateParameters(),
4001 /*IsDeduced=*/true, Deduced, Info, CTAI, CurrentInstantiationScope,
4002 NumExplicitlySpecified, PartialOverloading ? &IsIncomplete : nullptr);
4004 return Result;
4005
4006 // Form the template argument list from the deduced template arguments.
4007 TemplateArgumentList *SugaredDeducedArgumentList =
4009 TemplateArgumentList *CanonicalDeducedArgumentList =
4011 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
4012
4013 // Substitute the deduced template arguments into the function template
4014 // declaration to produce the function template specialization.
4015 DeclContext *Owner = FunctionTemplate->getDeclContext();
4016 if (FunctionTemplate->getFriendObjectKind())
4017 Owner = FunctionTemplate->getLexicalDeclContext();
4018 FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
4019
4020 if (CheckNonDependent(/*OnlyInitializeNonUserDefinedConversions=*/true))
4022
4023 // C++20 [temp.deduct.general]p5: [CWG2369]
4024 // If the function template has associated constraints, those constraints
4025 // are checked for satisfaction. If the constraints are not satisfied, type
4026 // deduction fails.
4027 //
4028 // FIXME: We haven't implemented CWG2369 for lambdas yet, because we need
4029 // to figure out how to instantiate lambda captures to the scope without
4030 // first instantiating the lambda.
4031 bool IsLambda = isLambdaCallOperator(FD) || isLambdaConversionOperator(FD);
4032 if (!IsLambda && !IsIncomplete) {
4034 Info.getLocation(),
4035 FunctionTemplate->getCanonicalDecl()->getTemplatedDecl(),
4041 }
4042 }
4043 // C++ [temp.deduct.call]p10: [CWG1391]
4044 // If deduction succeeds for all parameters that contain
4045 // template-parameters that participate in template argument deduction,
4046 // and all template arguments are explicitly specified, deduced, or
4047 // obtained from default template arguments, remaining parameters are then
4048 // compared with the corresponding arguments. For each remaining parameter
4049 // P with a type that was non-dependent before substitution of any
4050 // explicitly-specified template arguments, if the corresponding argument
4051 // A cannot be implicitly converted to P, deduction fails.
4052 if (CheckNonDependent(/*OnlyInitializeNonUserDefinedConversions=*/false))
4054
4056 FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
4057 /*Final=*/false);
4058 Specialization = cast_or_null<FunctionDecl>(
4059 SubstDecl(FD, Owner, SubstArgs));
4060 if (!Specialization || Specialization->isInvalidDecl())
4062
4063 assert(isSameDeclaration(Specialization->getPrimaryTemplate(),
4065
4066 // If the template argument list is owned by the function template
4067 // specialization, release it.
4068 if (Specialization->getTemplateSpecializationArgs() ==
4069 CanonicalDeducedArgumentList)
4070 Info.takeCanonical();
4071
4072 // C++2a [temp.deduct]p5
4073 // [...] When all template arguments have been deduced [...] all uses of
4074 // template parameters [...] are replaced with the corresponding deduced
4075 // or default argument values.
4076 // [...] If the function template has associated constraints
4077 // ([temp.constr.decl]), those constraints are checked for satisfaction
4078 // ([temp.constr.constr]). If the constraints are not satisfied, type
4079 // deduction fails.
4080 if (IsLambda && !IsIncomplete) {
4088 }
4089 }
4090
4091 // We skipped the instantiation of the explicit-specifier during the
4092 // substitution of `FD` before. So, we try to instantiate it back if
4093 // `Specialization` is either a constructor or a conversion function.
4097 Info, FunctionTemplate,
4098 DeducedArgs)) {
4100 }
4101 }
4102
4103 if (OriginalCallArgs) {
4104 // C++ [temp.deduct.call]p4:
4105 // In general, the deduction process attempts to find template argument
4106 // values that will make the deduced A identical to A (after the type A
4107 // is transformed as described above). [...]
4108 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
4109 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
4110 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
4111
4112 auto ParamIdx = OriginalArg.ArgIdx;
4113 unsigned ExplicitOffset =
4114 (Specialization->hasCXXExplicitFunctionObjectParameter() &&
4115 !ForOverloadSetAddressResolution)
4116 ? 1
4117 : 0;
4118 if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset)
4119 // FIXME: This presumably means a pack ended up smaller than we
4120 // expected while deducing. Should this not result in deduction
4121 // failure? Can it even happen?
4122 continue;
4123
4124 QualType DeducedA;
4125 if (!OriginalArg.DecomposedParam) {
4126 // P is one of the function parameters, just look up its substituted
4127 // type.
4128 DeducedA =
4129 Specialization->getParamDecl(ParamIdx + ExplicitOffset)->getType();
4130 } else {
4131 // P is a decomposed element of a parameter corresponding to a
4132 // braced-init-list argument. Substitute back into P to find the
4133 // deduced A.
4134 QualType &CacheEntry =
4135 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
4136 if (CacheEntry.isNull()) {
4138 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
4139 ParamIdx));
4140 CacheEntry =
4141 SubstType(OriginalArg.OriginalParamType, SubstArgs,
4142 Specialization->getTypeSpecStartLoc(),
4143 Specialization->getDeclName());
4144 }
4145 DeducedA = CacheEntry;
4146 }
4147
4148 if (auto TDK =
4149 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
4151 return TDK;
4152 }
4153 }
4154
4155 // If we suppressed any diagnostics while performing template argument
4156 // deduction, and if we haven't already instantiated this declaration,
4157 // keep track of these diagnostics. They'll be emitted if this specialization
4158 // is actually used.
4159 if (Info.diag_begin() != Info.diag_end()) {
4160 auto [Pos, Inserted] =
4161 SuppressedDiagnostics.try_emplace(Specialization->getCanonicalDecl());
4162 if (Inserted)
4163 Pos->second.append(Info.diag_begin(), Info.diag_end());
4164 }
4165
4167}
4168
4172 if (!FailedTSC)
4173 return;
4174
4175 Decl *TemplatedDecl = TD->getTemplatedDecl();
4176 for (TemplateSpecCandidate &Candidate : *FailedTSC) {
4177 if (Candidate.Specialization &&
4178 declaresSameEntity(Candidate.Specialization, TemplatedDecl))
4179 return;
4180 }
4181
4182 FailedTSC->addCandidate().set(
4183 DeclAccessPair::make(TD, AS_public), TemplatedDecl,
4185}
4186
4188 FriendTemplateDecl *FTD, ClassTemplateDecl *PatternCTD,
4190 ArrayRef<TemplateArgument> PatternArgs,
4191 ArrayRef<TemplateArgument> CandidateArgs, SourceLocation Loc,
4192 TemplateSpecCandidateSet *FailedTSC,
4193 MultiLevelTemplateArgumentList &DeducedArgs) {
4196 ContextRAII SavedContext(*this, FTD->getDeclContext());
4197 LocalInstantiationScope InstantiationScope(*this);
4198 InstantiatingTemplate Inst(*this, Loc, FTD);
4199 if (Inst.isInvalid()) {
4200 TemplateDeductionInfo Info(Loc);
4202 *this, PatternCTD, Info, TemplateDeductionResult::InstantiationDepth,
4203 FailedTSC);
4204 return false;
4205 }
4206
4208 DeducedArgLists.reserve(TPLs.size());
4209 for (TemplateParameterList *Params : TPLs) {
4210 TemplateDeductionInfo Info(Loc, Params->getDepth());
4211 SFINAETrap Trap(*this, Info);
4214 Params, PatternArgs, CandidateArgs, Info, Deduced,
4215 /*NumberOfArgumentsMustMatch=*/false);
4216
4218 bool IsIncomplete = false;
4221 *this, PatternCTD, Params, /*IsDeduced=*/false, Deduced, Info, CTAI,
4222 &InstantiationScope, /*NumAlreadyConverted=*/0, &IsIncomplete);
4223 if (Result == TemplateDeductionResult::Success && IsIncomplete) {
4224 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
4225 if (!Deduced[I].isNull())
4226 continue;
4227 Info.Param = makeTemplateParameter(Params->getParam(I));
4228 break;
4229 }
4230 Info.reset(
4234 }
4238 AddFriendTemplateDeductionCandidate(*this, PatternCTD, Info, Result,
4239 FailedTSC);
4240 return false;
4241 }
4242
4243 DeducedArgLists.push_back(
4245 }
4246
4247 for (TemplateArgumentList *Args : llvm::reverse(DeducedArgLists))
4248 DeducedArgs.addOuterTemplateArguments(FTD, Args->asArray(),
4249 /*Final=*/true);
4250 if (!TPLs.empty())
4251 DeducedArgs.addOuterRetainedLevels(TPLs.front()->getDepth());
4252
4253 if (DeducedArgs.isAnyArgInstantiationDependent() &&
4254 llvm::any_of(TPLs, [](TemplateParameterList *Params) {
4255 return Params->hasAssociatedConstraints();
4256 }))
4257 return false;
4258
4260 PatternArgLocs.reserve(PatternArgs.size());
4261 for (const TemplateArgument &Arg : PatternArgs)
4262 PatternArgLocs.push_back(
4264
4265 {
4266 TemplateDeductionInfo Info(Loc);
4267 SFINAETrap Trap(*this, Info);
4269 *this, CandidateCTD, PatternArgLocs, CandidateArgs, DeducedArgs, Info);
4273 AddFriendTemplateDeductionCandidate(*this, PatternCTD, Info, Result,
4274 FailedTSC);
4275 return false;
4276 }
4277 }
4278
4279 for (TemplateParameterList *Params : TPLs) {
4281 Params->getAssociatedConstraints(Constraints);
4282 if (Constraints.empty())
4283 continue;
4284
4285 TemplateDeductionInfo Info(Loc, Params->getDepth());
4286 SFINAETrap Trap(*this, Info);
4287 if (CheckConstraintSatisfaction(PatternCTD, Constraints, DeducedArgs,
4288 SourceRange(Loc),
4291 Trap.hasErrorOccurred()) {
4292 SmallVector<TemplateArgument, 4> CanonicalCandidateArgs;
4293 CanonicalCandidateArgs.reserve(CandidateArgs.size());
4294 for (const TemplateArgument &Arg : CandidateArgs)
4295 CanonicalCandidateArgs.push_back(
4296 Context.getCanonicalTemplateArgument(Arg));
4297 Info.reset(
4299 TemplateArgumentList::CreateCopy(Context, CanonicalCandidateArgs));
4301 *this, PatternCTD, Info,
4303 return false;
4304 }
4305 }
4306
4307 return true;
4308}
4309
4310/// Gets the type of a function for template-argument-deducton
4311/// purposes when it's considered as part of an overload set.
4313 FunctionDecl *Fn) {
4314 // We may need to deduce the return type of the function now.
4315 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
4316 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
4317 return {};
4318
4319 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
4320 if (Method->isImplicitObjectMemberFunction()) {
4321 // An instance method that's referenced in a form that doesn't
4322 // look like a member pointer is just invalid.
4323 if (!R.HasFormOfMemberPointer)
4324 return {};
4325
4327 Fn->getType(), /*Qualifier=*/std::nullopt, Method->getParent());
4328 }
4329
4330 if (!R.IsAddressOfOperand) return Fn->getType();
4331 return S.Context.getPointerType(Fn->getType());
4332}
4333
4334/// Apply the deduction rules for overload sets.
4335///
4336/// \return the null type if this argument should be treated as an
4337/// undeduced context
4338static QualType
4340 Expr *Arg, QualType ParamType,
4341 bool ParamWasReference,
4342 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4343
4345
4346 OverloadExpr *Ovl = R.Expression;
4347
4348 // C++0x [temp.deduct.call]p4
4349 unsigned TDF = 0;
4350 if (ParamWasReference)
4352 if (R.IsAddressOfOperand)
4353 TDF |= TDF_IgnoreQualifiers;
4354
4355 // C++0x [temp.deduct.call]p6:
4356 // When P is a function type, pointer to function type, or pointer
4357 // to member function type:
4358
4359 if (!ParamType->isFunctionType() &&
4360 !ParamType->isFunctionPointerType() &&
4361 !ParamType->isMemberFunctionPointerType()) {
4362 if (Ovl->hasExplicitTemplateArgs()) {
4363 // But we can still look for an explicit specialization.
4364 if (FunctionDecl *ExplicitSpec =
4366 Ovl, /*Complain=*/false,
4367 /*Found=*/nullptr, FailedTSC,
4368 /*ForTypeDeduction=*/true))
4369 return GetTypeOfFunction(S, R, ExplicitSpec);
4370 }
4371
4372 DeclAccessPair DAP;
4373 if (FunctionDecl *Viable =
4375 return GetTypeOfFunction(S, R, Viable);
4376
4377 return {};
4378 }
4379
4380 // Gather the explicit template arguments, if any.
4381 TemplateArgumentListInfo ExplicitTemplateArgs;
4382 if (Ovl->hasExplicitTemplateArgs())
4383 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4385 for (UnresolvedSetIterator I = Ovl->decls_begin(),
4386 E = Ovl->decls_end(); I != E; ++I) {
4387 NamedDecl *D = (*I)->getUnderlyingDecl();
4388
4389 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
4390 // - If the argument is an overload set containing one or more
4391 // function templates, the parameter is treated as a
4392 // non-deduced context.
4393 if (!Ovl->hasExplicitTemplateArgs())
4394 return {};
4395
4396 // Otherwise, see if we can resolve a function type
4397 FunctionDecl *Specialization = nullptr;
4398 TemplateDeductionInfo Info(Ovl->getNameLoc());
4399 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
4402 continue;
4403
4404 D = Specialization;
4405 }
4406
4408 QualType ArgType = GetTypeOfFunction(S, R, Fn);
4409 if (ArgType.isNull()) continue;
4410
4411 // Function-to-pointer conversion.
4412 if (!ParamWasReference && ParamType->isPointerType() &&
4413 ArgType->isFunctionType())
4414 ArgType = S.Context.getPointerType(ArgType);
4415
4416 // - If the argument is an overload set (not containing function
4417 // templates), trial argument deduction is attempted using each
4418 // of the members of the set. If deduction succeeds for only one
4419 // of the overload set members, that member is used as the
4420 // argument value for the deduction. If deduction succeeds for
4421 // more than one member of the overload set the parameter is
4422 // treated as a non-deduced context.
4423
4424 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
4425 // Type deduction is done independently for each P/A pair, and
4426 // the deduced template argument values are then combined.
4427 // So we do not reject deductions which were made elsewhere.
4429 Deduced(TemplateParams->size());
4430 TemplateDeductionInfo Info(Ovl->getNameLoc());
4432 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4433 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4434 /*HasDeducedAnyParam=*/nullptr);
4436 continue;
4437 // C++ [temp.deduct.call]p6:
4438 // [...] If all successful deductions yield the same deduced A, that
4439 // deduced A is the result of deduction; otherwise, the parameter is
4440 // treated as a non-deduced context. [...]
4441 if (!Match.isNull() && !S.isSameOrCompatibleFunctionType(Match, ArgType))
4442 return {};
4443 Match = ArgType;
4444 }
4445
4446 return Match;
4447}
4448
4449/// Perform the adjustments to the parameter and argument types
4450/// described in C++ [temp.deduct.call].
4451///
4452/// \returns true if the caller should not attempt to perform any template
4453/// argument deduction based on this P/A pair because the argument is an
4454/// overloaded function set that could not be resolved.
4456 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4457 QualType &ParamType, QualType &ArgType,
4458 Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
4459 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4460 // C++0x [temp.deduct.call]p3:
4461 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
4462 // are ignored for type deduction.
4463 if (ParamType.hasQualifiers())
4464 ParamType = ParamType.getUnqualifiedType();
4465
4466 // [...] If P is a reference type, the type referred to by P is
4467 // used for type deduction.
4468 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
4469 if (ParamRefType)
4470 ParamType = ParamRefType->getPointeeType();
4471
4472 // Overload sets usually make this parameter an undeduced context,
4473 // but there are sometimes special circumstances. Typically
4474 // involving a template-id-expr.
4475 if (ArgType == S.Context.OverloadTy) {
4476 assert(Arg && "expected a non-null arg expression");
4477 ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType,
4478 ParamRefType != nullptr, FailedTSC);
4479 if (ArgType.isNull())
4480 return true;
4481 }
4482
4483 if (ParamRefType) {
4484 // If the argument has incomplete array type, try to complete its type.
4485 if (ArgType->isIncompleteArrayType()) {
4486 assert(Arg && "expected a non-null arg expression");
4487 ArgType = S.getCompletedType(Arg);
4488 }
4489
4490 // C++1z [temp.deduct.call]p3:
4491 // If P is a forwarding reference and the argument is an lvalue, the type
4492 // "lvalue reference to A" is used in place of A for type deduction.
4493 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
4494 ArgClassification.isLValue()) {
4495 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
4496 ArgType = S.Context.getAddrSpaceQualType(
4498 ArgType = S.Context.getLValueReferenceType(ArgType);
4499 }
4500 } else {
4501 // C++ [temp.deduct.call]p2:
4502 // If P is not a reference type:
4503 // - If A is an array type, the pointer type produced by the
4504 // array-to-pointer standard conversion (4.2) is used in place of
4505 // A for type deduction; otherwise,
4506 // - If A is a function type, the pointer type produced by the
4507 // function-to-pointer standard conversion (4.3) is used in place
4508 // of A for type deduction; otherwise,
4509 if (ArgType->canDecayToPointerType())
4510 ArgType = S.Context.getDecayedType(ArgType);
4511 else {
4512 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
4513 // type are ignored for type deduction.
4514 ArgType = ArgType.getUnqualifiedType();
4515 }
4516 }
4517
4518 // C++0x [temp.deduct.call]p4:
4519 // In general, the deduction process attempts to find template argument
4520 // values that will make the deduced A identical to A (after the type A
4521 // is transformed as described above). [...]
4523
4524 // - If the original P is a reference type, the deduced A (i.e., the
4525 // type referred to by the reference) can be more cv-qualified than
4526 // the transformed A.
4527 if (ParamRefType)
4529 // - The transformed A can be another pointer or pointer to member
4530 // type that can be converted to the deduced A via a qualification
4531 // conversion (4.4).
4532 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
4533 ArgType->isObjCObjectPointerType())
4534 TDF |= TDF_IgnoreQualifiers;
4535 // - If P is a class and P has the form simple-template-id, then the
4536 // transformed A can be a derived class of the deduced A. Likewise,
4537 // if P is a pointer to a class of the form simple-template-id, the
4538 // transformed A can be a pointer to a derived class pointed to by
4539 // the deduced A.
4540 if (isSimpleTemplateIdType(ParamType) ||
4541 (ParamType->getAs<PointerType>() &&
4543 ParamType->castAs<PointerType>()->getPointeeType())))
4544 TDF |= TDF_DerivedClass;
4545
4546 return false;
4547}
4548
4549static bool
4551 QualType T);
4552
4554 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4555 QualType ParamType, QualType ArgType,
4556 Expr::Classification ArgClassification, Expr *Arg,
4560 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4561 TemplateSpecCandidateSet *FailedTSC = nullptr);
4562
4563/// Attempt template argument deduction from an initializer list
4564/// deemed to be an argument in a function call.
4566 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
4569 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
4570 unsigned TDF) {
4571 // C++ [temp.deduct.call]p1: (CWG 1591)
4572 // If removing references and cv-qualifiers from P gives
4573 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
4574 // a non-empty initializer list, then deduction is performed instead for
4575 // each element of the initializer list, taking P0 as a function template
4576 // parameter type and the initializer element as its argument
4577 //
4578 // We've already removed references and cv-qualifiers here.
4579 if (!ILE->getNumInits())
4581
4582 QualType ElTy;
4583 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
4584 if (ArrTy)
4585 ElTy = ArrTy->getElementType();
4586 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
4587 // Otherwise, an initializer list argument causes the parameter to be
4588 // considered a non-deduced context
4590 }
4591
4592 // Resolving a core issue: a braced-init-list containing any designators is
4593 // a non-deduced context.
4594 for (Expr *E : ILE->inits())
4597
4598 // Deduction only needs to be done for dependent types.
4599 if (ElTy->isDependentType()) {
4600 for (Expr *E : ILE->inits()) {
4602 S, TemplateParams, 0, ElTy, E->getType(),
4603 E->Classify(S.getASTContext()), E, Info, Deduced,
4604 OriginalCallArgs, true, ArgIdx, TDF);
4606 return Result;
4607 }
4608 }
4609
4610 // in the P0[N] case, if N is a non-type template parameter, N is deduced
4611 // from the length of the initializer list.
4612 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
4613 // Determine the array bound is something we can deduce.
4615 getNTTParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
4616 // We can perform template argument deduction for the given non-type
4617 // template parameter.
4618 // C++ [temp.deduct.type]p13:
4619 // The type of N in the type T[N] is std::size_t.
4621 llvm::APInt Size(S.Context.getIntWidth(T),
4624 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
4625 /*ArrayBound=*/true, Info, /*PartialOrdering=*/false, Deduced,
4626 /*HasDeducedAnyParam=*/nullptr);
4628 return Result;
4629 }
4630 }
4631
4633}
4634
4635/// Perform template argument deduction per [temp.deduct.call] for a
4636/// single parameter / argument pair.
4638 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4639 QualType ParamType, QualType ArgType,
4640 Expr::Classification ArgClassification, Expr *Arg,
4644 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4645 TemplateSpecCandidateSet *FailedTSC) {
4646
4647 QualType OrigParamType = ParamType;
4648
4649 // If P is a reference type [...]
4650 // If P is a cv-qualified type [...]
4652 S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
4653 ArgClassification, Arg, TDF, FailedTSC))
4655
4656 // If [...] the argument is a non-empty initializer list [...]
4657 if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
4658 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
4659 Deduced, OriginalCallArgs, ArgIdx, TDF);
4660
4661 // [...] the deduction process attempts to find template argument values
4662 // that will make the deduced A identical to A
4663 //
4664 // Keep track of the argument type and corresponding parameter index,
4665 // so we can check for compatibility between the deduced A and A.
4666 if (Arg)
4667 OriginalCallArgs.push_back(
4668 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
4670 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4671 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4672 /*HasDeducedAnyParam=*/nullptr);
4673}
4674
4677 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4679 bool PartialOverloading, bool AggregateDeductionCandidate,
4680 bool PartialOrdering, QualType ObjectType,
4681 Expr::Classification ObjectClassification,
4682 bool ForOverloadSetAddressResolution,
4683 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent) {
4684 if (FunctionTemplate->isInvalidDecl())
4686
4687 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4688 unsigned NumParams = Function->getNumParams();
4689 bool HasExplicitObject = false;
4690 int ExplicitObjectOffset = 0;
4691
4692 // [C++26] [over.call.func]p3
4693 // If the primary-expression is the address of an overload set,
4694 // the argument list is the same as the expression-list in the call.
4695 // Otherwise, the argument list is the expression-list in the call augmented
4696 // by the addition of an implied object argument as in a qualified function
4697 // call.
4698 if (!ForOverloadSetAddressResolution &&
4699 Function->hasCXXExplicitFunctionObjectParameter()) {
4700 HasExplicitObject = true;
4701 ExplicitObjectOffset = 1;
4702 }
4703
4704 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
4705
4706 // C++ [temp.deduct.call]p1:
4707 // Template argument deduction is done by comparing each function template
4708 // parameter type (call it P) with the type of the corresponding argument
4709 // of the call (call it A) as described below.
4710 if (Args.size() < Function->getMinRequiredExplicitArguments() &&
4711 !PartialOverloading)
4713 else if (TooManyArguments(NumParams, Args.size() + ExplicitObjectOffset,
4714 PartialOverloading)) {
4715 const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
4716 if (Proto->isTemplateVariadic())
4717 /* Do nothing */;
4718 else if (!Proto->isVariadic())
4720 }
4721
4724 Sema::SFINAETrap Trap(*this, Info);
4725
4726 // The types of the parameters from which we will perform template argument
4727 // deduction.
4728 LocalInstantiationScope InstScope(*this);
4729 TemplateParameterList *TemplateParams
4730 = FunctionTemplate->getTemplateParameters();
4732 SmallVector<QualType, 8> ParamTypes;
4733 unsigned NumExplicitlySpecified = 0;
4734 if (ExplicitTemplateArgs) {
4737 Result = SubstituteExplicitTemplateArguments(
4738 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4739 Info);
4740 });
4742 return Result;
4743 if (Trap.hasErrorOccurred())
4745
4746 NumExplicitlySpecified = Deduced.size();
4747 } else {
4748 // Just fill in the parameter types from the function declaration.
4749 for (unsigned I = 0; I != NumParams; ++I)
4750 ParamTypes.push_back(Function->getParamDecl(I)->getType());
4751 }
4752
4753 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
4754
4755 // Deduce an argument of type ParamType from an expression with index ArgIdx.
4756 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx,
4757 bool ExplicitObjectArgument) {
4758 // C++ [demp.deduct.call]p1: (DR1391)
4759 // Template argument deduction is done by comparing each function template
4760 // parameter that contains template-parameters that participate in
4761 // template argument deduction ...
4762 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4764
4765 if (ExplicitObjectArgument) {
4766 // ... with the type of the corresponding argument
4768 *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
4769 ObjectClassification,
4770 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4771 /*Decomposed*/ false, ArgIdx, /*TDF*/ 0);
4772 }
4773
4774 // ... with the type of the corresponding argument
4776 *this, TemplateParams, FirstInnerIndex, ParamType,
4777 Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()),
4778 Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false,
4779 ArgIdx, /*TDF*/ 0);
4780 };
4781
4782 // Deduce template arguments from the function parameters.
4783 Deduced.resize(TemplateParams->size());
4784 SmallVector<QualType, 8> ParamTypesForArgChecking;
4785 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4786 ParamIdx != NumParamTypes; ++ParamIdx) {
4787 QualType ParamType = ParamTypes[ParamIdx];
4788
4789 const PackExpansionType *ParamExpansion =
4790 dyn_cast<PackExpansionType>(ParamType);
4791 if (!ParamExpansion) {
4792 // Simple case: matching a function parameter to a function argument.
4793 if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0))
4794 break;
4795
4796 ParamTypesForArgChecking.push_back(ParamType);
4797
4798 if (ParamIdx == 0 && HasExplicitObject) {
4799 if (ObjectType.isNull())
4801
4802 if (auto Result = DeduceCallArgument(ParamType, 0,
4803 /*ExplicitObjectArgument=*/true);
4805 return Result;
4806 continue;
4807 }
4808
4809 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4810 /*ExplicitObjectArgument=*/false);
4812 return Result;
4813
4814 continue;
4815 }
4816
4817 bool IsTrailingPack = ParamIdx + 1 == NumParamTypes;
4818
4819 QualType ParamPattern = ParamExpansion->getPattern();
4820 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
4821 ParamPattern,
4822 AggregateDeductionCandidate && IsTrailingPack);
4823
4824 // C++0x [temp.deduct.call]p1:
4825 // For a function parameter pack that occurs at the end of the
4826 // parameter-declaration-list, the type A of each remaining argument of
4827 // the call is compared with the type P of the declarator-id of the
4828 // function parameter pack. Each comparison deduces template arguments
4829 // for subsequent positions in the template parameter packs expanded by
4830 // the function parameter pack. When a function parameter pack appears
4831 // in a non-deduced context [not at the end of the list], the type of
4832 // that parameter pack is never deduced.
4833 //
4834 // FIXME: The above rule allows the size of the parameter pack to change
4835 // after we skip it (in the non-deduced case). That makes no sense, so
4836 // we instead notionally deduce the pack against N arguments, where N is
4837 // the length of the explicitly-specified pack if it's expanded by the
4838 // parameter pack and 0 otherwise, and we treat each deduction as a
4839 // non-deduced context.
4840 if (IsTrailingPack || PackScope.hasFixedArity()) {
4841 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4842 PackScope.nextPackElement(), ++ArgIdx) {
4843 ParamTypesForArgChecking.push_back(ParamPattern);
4844 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4845 /*ExplicitObjectArgument=*/false);
4847 return Result;
4848 }
4849 } else {
4850 // If the parameter type contains an explicitly-specified pack that we
4851 // could not expand, skip the number of parameters notionally created
4852 // by the expansion.
4853 UnsignedOrNone NumExpansions = ParamExpansion->getNumExpansions();
4854 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4855 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4856 ++I, ++ArgIdx) {
4857 ParamTypesForArgChecking.push_back(ParamPattern);
4858 // FIXME: Should we add OriginalCallArgs for these? What if the
4859 // corresponding argument is a list?
4860 PackScope.nextPackElement();
4861 }
4862 } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4863 PackScope.isDeducedFromEarlierParameter()) {
4864 // [temp.deduct.general#3]
4865 // When all template arguments have been deduced
4866 // or obtained from default template arguments, all uses of template
4867 // parameters in the template parameter list of the template are
4868 // replaced with the corresponding deduced or default argument values
4869 //
4870 // If we have a trailing parameter pack, that has been deduced
4871 // previously we substitute the pack here in a similar fashion as
4872 // above with the trailing parameter packs. The main difference here is
4873 // that, in this case we are not processing all of the remaining
4874 // arguments. We are only process as many arguments as we have in
4875 // the already deduced parameter.
4876 UnsignedOrNone ArgPosAfterSubstitution =
4877 PackScope.getSavedPackSizeIfAllEqual();
4878 if (!ArgPosAfterSubstitution)
4879 continue;
4880
4881 unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4882 for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4883 ParamTypesForArgChecking.push_back(ParamPattern);
4884 if (auto Result =
4885 DeduceCallArgument(ParamPattern, ArgIdx,
4886 /*ExplicitObjectArgument=*/false);
4888 return Result;
4889
4890 PackScope.nextPackElement();
4891 }
4892 }
4893 }
4894
4895 // Build argument packs for each of the parameter packs expanded by this
4896 // pack expansion.
4897 if (auto Result = PackScope.finish();
4899 return Result;
4900 }
4901
4902 // Capture the context in which the function call is made. This is the context
4903 // that is needed when the accessibility of template arguments is checked.
4904 DeclContext *CallingCtx = CurContext;
4905
4908 Result = FinishTemplateArgumentDeduction(
4909 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4910 &OriginalCallArgs, PartialOverloading, PartialOrdering,
4911 ForOverloadSetAddressResolution,
4912 [&, CallingCtx](bool OnlyInitializeNonUserDefinedConversions) {
4913 ContextRAII SavedContext(*this, CallingCtx);
4914 return CheckNonDependent(ParamTypesForArgChecking,
4915 OnlyInitializeNonUserDefinedConversions);
4916 });
4917 });
4918 if (Trap.hasErrorOccurred()) {
4919 if (Specialization)
4920 Specialization->setInvalidDecl(true);
4922 }
4923 return Result;
4924}
4925
4928 bool AdjustExceptionSpec) {
4929 if (ArgFunctionType.isNull())
4930 return ArgFunctionType;
4931
4932 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4933 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4934 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4935 bool Rebuild = false;
4936
4937 CallingConv CC = FunctionTypeP->getCallConv();
4938 if (EPI.ExtInfo.getCC() != CC) {
4939 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4940 Rebuild = true;
4941 }
4942
4943 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4944 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4945 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4946 Rebuild = true;
4947 }
4948
4949 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4950 ArgFunctionTypeP->hasExceptionSpec())) {
4951 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4952 Rebuild = true;
4953 }
4954
4955 if (!Rebuild)
4956 return ArgFunctionType;
4957
4958 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4959 ArgFunctionTypeP->getParamTypes(), EPI);
4960}
4961
4964 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4966 bool IsAddressOfFunction) {
4967 if (FunctionTemplate->isInvalidDecl())
4969
4970 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4971 TemplateParameterList *TemplateParams
4972 = FunctionTemplate->getTemplateParameters();
4973 QualType FunctionType = Function->getType();
4974
4977
4978 // Unevaluated SFINAE context.
4981 SFINAETrap Trap(*this, Info);
4982
4983 // Substitute any explicit template arguments.
4984 LocalInstantiationScope InstScope(*this);
4986 unsigned NumExplicitlySpecified = 0;
4987 SmallVector<QualType, 4> ParamTypes;
4988 if (ExplicitTemplateArgs) {
4991 Result = SubstituteExplicitTemplateArguments(
4992 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4993 &FunctionType, Info);
4994 });
4996 return Result;
4997 if (Trap.hasErrorOccurred())
4999
5000 NumExplicitlySpecified = Deduced.size();
5001 }
5002
5003 // When taking the address of a function, we require convertibility of
5004 // the resulting function type. Otherwise, we allow arbitrary mismatches
5005 // of calling convention and noreturn.
5006 if (!IsAddressOfFunction)
5007 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
5008 /*AdjustExceptionSpec*/false);
5009
5010 Deduced.resize(TemplateParams->size());
5011
5012 // If the function has a deduced return type, substitute it for a dependent
5013 // type so that we treat it as a non-deduced context in what follows.
5014 bool HasDeducedReturnType = false;
5015 if (getLangOpts().CPlusPlus14 &&
5016 Function->getReturnType()->getContainedAutoType()) {
5018 HasDeducedReturnType = true;
5019 }
5020
5021 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
5022 unsigned TDF =
5024 // Deduce template arguments from the function type.
5026 *this, TemplateParams, FunctionType, ArgFunctionType, Info, Deduced,
5027 TDF, PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
5028 /*HasDeducedAnyParam=*/nullptr);
5030 return Result;
5031 // Substituting the function type can instantiate the trailing return type,
5032 // so handle the same immediate-context substitution failure here.
5033 if (Trap.hasErrorOccurred())
5035 }
5036
5039 Result = FinishTemplateArgumentDeduction(
5040 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
5041 /*OriginalCallArgs=*/nullptr, /*PartialOverloading=*/false,
5042 /*PartialOrdering=*/true, IsAddressOfFunction);
5043 });
5044 // Taking the address of a function template forms its function type, and
5045 // substituting into that type can require instantiating a trailing return
5046 // type whose expression selects a deleted function. That is a deduction
5047 // failure, not a hard error:
5048 //
5049 // C++ [temp.deduct.funcaddr]p1:
5050 // [...] If there is a target, the function template's function type and
5051 // the target type are used as the types of P and A, and the deduction is
5052 // done as described in [temp.deduct.type].
5053 //
5054 // C++ [temp.deduct.general]p7:
5055 // [...] The substitution occurs in all types and expressions that are
5056 // used in the deduction substitution loci. The expressions include [...]
5057 // general expressions (i.e., non-constant expressions) inside sizeof,
5058 // decltype, and other contexts that allow non-constant expressions. [...]
5059 //
5060 // C++ [dcl.fct.def.delete]p2:
5061 // A construct that designates a deleted function implicitly or
5062 // explicitly, other than to declare it [...], is ill-formed.
5063 // [Note: [...] It applies even for references in expressions that are not
5064 // potentially evaluated. - end note]
5065 //
5066 // C++ [temp.deduct.general]p8:
5067 // If a substitution results in an invalid type or expression, type
5068 // deduction fails. [...] Invalid types and expressions can result in a
5069 // deduction failure only in the immediate context of the deduction
5070 // substitution loci. [...]
5071 //
5072 // This substitution is in that immediate context, so treat diagnostics
5073 // recorded by the SFINAE trap as deduction failure instead of replaying
5074 // them as hard errors.
5075 if (Trap.hasErrorOccurred()) {
5076 if (Specialization)
5077 Specialization->setInvalidDecl(true);
5079 }
5081 return Result;
5082
5083 // If the function has a deduced return type, deduce it now, so we can check
5084 // that the deduced function type matches the requested type.
5085 if (HasDeducedReturnType && IsAddressOfFunction &&
5086 Specialization->getReturnType()->isUndeducedType() &&
5089
5090 // [C++26][expr.const]/p17
5091 // An expression or conversion is immediate-escalating if it is not initially
5092 // in an immediate function context and it is [...]
5093 // a potentially-evaluated id-expression that denotes an immediate function.
5094 if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
5095 Specialization->isImmediateEscalating() && PotentiallyEvaluated &&
5097 Info.getLocation()))
5099
5100 // Adjust the exception specification of the argument to match the
5101 // substituted and resolved type we just formed. (Calling convention and
5102 // noreturn can't be dependent, so we don't actually need this for them
5103 // right now.)
5104 QualType SpecializationType = Specialization->getType();
5105 if (!IsAddressOfFunction) {
5106 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
5107 /*AdjustExceptionSpec*/true);
5108
5109 // Revert placeholder types in the return type back to undeduced types so
5110 // that the comparison below compares the declared return types.
5111 if (HasDeducedReturnType) {
5112 SpecializationType = SubstAutoType(SpecializationType, QualType());
5113 ArgFunctionType = SubstAutoType(ArgFunctionType, QualType());
5114 }
5115 }
5116
5117 // If the requested function type does not match the actual type of the
5118 // specialization with respect to arguments of compatible pointer to function
5119 // types, template argument deduction fails.
5120 if (!ArgFunctionType.isNull()) {
5121 if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
5122 SpecializationType, ArgFunctionType)
5123 : !Context.hasSameFunctionTypeIgnoringExceptionSpec(
5124 SpecializationType, ArgFunctionType)) {
5125 Info.FirstArg = TemplateArgument(SpecializationType);
5126 Info.SecondArg = TemplateArgument(ArgFunctionType);
5128 }
5129 }
5130
5132}
5133
5135 FunctionTemplateDecl *ConversionTemplate, QualType ObjectType,
5136 Expr::Classification ObjectClassification, QualType A,
5138 if (ConversionTemplate->isInvalidDecl())
5140
5141 CXXConversionDecl *ConversionGeneric
5142 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
5143
5144 QualType P = ConversionGeneric->getConversionType();
5145 bool IsReferenceP = P->isReferenceType();
5146 bool IsReferenceA = A->isReferenceType();
5147
5148 // C++0x [temp.deduct.conv]p2:
5149 // If P is a reference type, the type referred to by P is used for
5150 // type deduction.
5151 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
5152 P = PRef->getPointeeType();
5153
5154 // C++0x [temp.deduct.conv]p4:
5155 // [...] If A is a reference type, the type referred to by A is used
5156 // for type deduction.
5157 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
5158 A = ARef->getPointeeType();
5159 // We work around a defect in the standard here: cv-qualifiers are also
5160 // removed from P and A in this case, unless P was a reference type. This
5161 // seems to mostly match what other compilers are doing.
5162 if (!IsReferenceP) {
5163 A = A.getUnqualifiedType();
5164 P = P.getUnqualifiedType();
5165 }
5166
5167 // C++ [temp.deduct.conv]p3:
5168 //
5169 // If A is not a reference type:
5170 } else {
5171 assert(!A->isReferenceType() && "Reference types were handled above");
5172
5173 // - If P is an array type, the pointer type produced by the
5174 // array-to-pointer standard conversion (4.2) is used in place
5175 // of P for type deduction; otherwise,
5176 if (P->isArrayType())
5177 P = Context.getArrayDecayedType(P);
5178 // - If P is a function type, the pointer type produced by the
5179 // function-to-pointer standard conversion (4.3) is used in
5180 // place of P for type deduction; otherwise,
5181 else if (P->isFunctionType())
5182 P = Context.getPointerType(P);
5183 // - If P is a cv-qualified type, the top level cv-qualifiers of
5184 // P's type are ignored for type deduction.
5185 else
5186 P = P.getUnqualifiedType();
5187
5188 // C++0x [temp.deduct.conv]p4:
5189 // If A is a cv-qualified type, the top level cv-qualifiers of A's
5190 // type are ignored for type deduction. If A is a reference type, the type
5191 // referred to by A is used for type deduction.
5192 A = A.getUnqualifiedType();
5193 }
5194
5195 // Unevaluated SFINAE context.
5198 SFINAETrap Trap(*this, Info);
5199
5200 // C++ [temp.deduct.conv]p1:
5201 // Template argument deduction is done by comparing the return
5202 // type of the template conversion function (call it P) with the
5203 // type that is required as the result of the conversion (call it
5204 // A) as described in 14.8.2.4.
5205 TemplateParameterList *TemplateParams
5206 = ConversionTemplate->getTemplateParameters();
5208 Deduced.resize(TemplateParams->size());
5209
5210 // C++0x [temp.deduct.conv]p4:
5211 // In general, the deduction process attempts to find template
5212 // argument values that will make the deduced A identical to
5213 // A. However, there are two cases that allow a difference:
5214 unsigned TDF = 0;
5215 // - If the original A is a reference type, A can be more
5216 // cv-qualified than the deduced A (i.e., the type referred to
5217 // by the reference)
5218 if (IsReferenceA)
5220 // - The deduced A can be another pointer or pointer to member
5221 // type that can be converted to A via a qualification
5222 // conversion.
5223 //
5224 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
5225 // both P and A are pointers or member pointers. In this case, we
5226 // just ignore cv-qualifiers completely).
5227 if ((P->isPointerType() && A->isPointerType()) ||
5229 TDF |= TDF_IgnoreQualifiers;
5230
5232 if (ConversionGeneric->isExplicitObjectMemberFunction()) {
5233 QualType ParamType = ConversionGeneric->getParamDecl(0)->getType();
5236 *this, TemplateParams, getFirstInnerIndex(ConversionTemplate),
5237 ParamType, ObjectType, ObjectClassification,
5238 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
5239 /*Decomposed*/ false, 0, /*TDF*/ 0);
5241 return Result;
5242 }
5243
5245 *this, TemplateParams, P, A, Info, Deduced, TDF,
5246 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
5247 /*HasDeducedAnyParam=*/nullptr);
5249 return Result;
5250
5251 // Create an Instantiation Scope for finalizing the operator.
5252 LocalInstantiationScope InstScope(*this);
5253 // Finish template argument deduction.
5254 FunctionDecl *ConversionSpecialized = nullptr;
5257 Result = FinishTemplateArgumentDeduction(
5258 ConversionTemplate, Deduced, 0, ConversionSpecialized, Info,
5259 &OriginalCallArgs, /*PartialOverloading=*/false,
5260 /*PartialOrdering=*/false, /*ForOverloadSetAddressResolution*/ false);
5261 });
5262 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
5263 return Result;
5264}
5265
5268 TemplateArgumentListInfo *ExplicitTemplateArgs,
5271 bool IsAddressOfFunction) {
5272 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
5273 QualType(), Specialization, Info,
5274 IsAddressOfFunction);
5275}
5276
5277namespace {
5278 struct DependentAuto { bool IsPack; };
5279
5280 /// Substitute the 'auto' specifier or deduced template specialization type
5281 /// specifier within a type for a given replacement type.
5282 class SubstituteDeducedTypeTransform :
5283 public TreeTransform<SubstituteDeducedTypeTransform> {
5284 DeducedKind DK;
5285 QualType Replacement;
5286 bool UseTypeSugar;
5288
5289 public:
5290 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
5291 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5292 DK(DA.IsPack ? DeducedKind::DeducedAsPack
5294 UseTypeSugar(true) {}
5295
5296 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
5297 bool UseTypeSugar = true)
5298 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5299 DK(Replacement.isNull() ? DeducedKind::Undeduced
5300 : DeducedKind::Deduced),
5301 Replacement(Replacement), UseTypeSugar(UseTypeSugar) {
5302 assert((!Replacement.isNull() || UseTypeSugar) &&
5303 "An undeduced auto type is never type sugar");
5304 }
5305
5306 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
5307 assert(isa<TemplateTypeParmType>(Replacement) &&
5308 "unexpected unsugared replacement kind");
5309 QualType Result = Replacement;
5310 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
5311 NewTL.setNameLoc(TL.getNameLoc());
5312 return Result;
5313 }
5314
5315 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
5316 // If we're building the type pattern to deduce against, don't wrap the
5317 // substituted type in an AutoType. Certain template deduction rules
5318 // apply only when a template type parameter appears directly (and not if
5319 // the parameter is found through desugaring). For instance:
5320 // auto &&lref = lvalue;
5321 // must transform into "rvalue reference to T" not "rvalue reference to
5322 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
5323 //
5324 // FIXME: Is this still necessary?
5325 if (!UseTypeSugar)
5326 return TransformDesugared(TLB, TL);
5327
5328 QualType Result = SemaRef.Context.getAutoType(
5329 DK, Replacement, TL.getTypePtr()->getKeyword(),
5330 TL.getTypePtr()->getTypeConstraintConcept(),
5331 TL.getTypePtr()->getTypeConstraintArguments());
5332 auto NewTL = TLB.push<AutoTypeLoc>(Result);
5333 NewTL.copy(TL);
5334 return Result;
5335 }
5336
5337 QualType TransformDeducedTemplateSpecializationType(
5338 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
5339 if (!UseTypeSugar)
5340 return TransformDesugared(TLB, TL);
5341
5343 DK, Replacement, TL.getTypePtr()->getKeyword(),
5344 TL.getTypePtr()->getTemplateName());
5345 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5346 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5347 NewTL.setNameLoc(TL.getNameLoc());
5348 NewTL.setQualifierLoc(TL.getQualifierLoc());
5349 return Result;
5350 }
5351
5352 QualType TransformAtomicType(TypeLocBuilder &TLB, AtomicTypeLoc TL) {
5353 // When building the function parameter for placeholder type deduction
5354 // (Replacement is the invented template parameter), dig through _Atomic
5355 // around an auto placeholder so deduction matches the non-atomic
5356 // argument. The _Atomic wrapper is re-applied by the final substitution
5357 // pass, which uses a concrete Replacement and falls through to the
5358 // default transform.
5359 //
5360 // This handles only the simple case where _Atomic wraps auto directly
5361 // (e.g. _Atomic(auto)), which is what the C standard currently permits.
5362 // If more complex forms such as _Atomic(auto*) are ever allowed, the
5363 // correct fix would be to treat _Atomic as a qualifier inside
5364 // DeduceTemplateArgumentsByTypeMatch instead.
5365 if (isa_and_nonnull<TemplateTypeParmType>(Replacement) &&
5367 return getDerived().TransformType(TLB, TL.getValueLoc());
5368 return inherited::TransformAtomicType(TLB, TL);
5369 }
5370
5371 ExprResult TransformLambdaExpr(LambdaExpr *E) {
5372 // Lambdas never need to be transformed.
5373 return E;
5374 }
5375 bool TransformExceptionSpec(SourceLocation Loc,
5376 FunctionProtoType::ExceptionSpecInfo &ESI,
5377 SmallVectorImpl<QualType> &Exceptions,
5378 bool &Changed) {
5379 if (ESI.Type == EST_Uninstantiated) {
5380 ESI.instantiate();
5381 Changed = true;
5382 }
5383 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
5384 }
5385
5386 QualType Apply(TypeLoc TL) {
5387 // Create some scratch storage for the transformed type locations.
5388 // FIXME: We're just going to throw this information away. Don't build it.
5389 TypeLocBuilder TLB;
5390 TLB.reserve(TL.getFullDataSize());
5391 return TransformType(TLB, TL);
5392 }
5393 };
5394
5395} // namespace
5396
5397static bool CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type,
5399 QualType Deduced) {
5400 ConstraintSatisfaction Satisfaction;
5402 cast<ConceptDecl>(Type.getTypeConstraintConcept().getAsTemplateDecl());
5403 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
5404 TypeLoc.getRAngleLoc());
5405 TemplateArgs.addArgument(
5408 Deduced, TypeLoc.getNameLoc())));
5409 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
5410 TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
5411
5413 if (S.CheckTemplateArgumentList(Concept, TypeLoc.getNameLoc(), TemplateArgs,
5414 /*DefaultArgs=*/{},
5415 /*PartialTemplateArgs=*/false, CTAI))
5416 return true;
5418 /*Final=*/true);
5420 Concept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
5421 TypeLoc.getLocalSourceRange(), Satisfaction))
5422 return true;
5423 if (!Satisfaction.IsSatisfied) {
5424 std::string Buf;
5425 llvm::raw_string_ostream OS(Buf);
5426 OS << "'" << Concept->getName();
5427 if (TypeLoc.hasExplicitTemplateArgs()) {
5428 printTemplateArgumentList(OS, Type.getTypeConstraintArguments(),
5430 Type.getTypeConstraintConcept()
5431 .getAsTemplateDecl()
5432 ->getTemplateParameters());
5433 }
5434 OS << "'";
5435 S.Diag(TypeLoc.getConceptNameLoc(),
5436 diag::err_placeholder_constraints_not_satisfied)
5437 << Deduced << Buf << TypeLoc.getLocalSourceRange();
5438 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
5439 return true;
5440 }
5441 return false;
5442}
5443
5446 TemplateDeductionInfo &Info, bool DependentDeduction,
5447 bool IgnoreConstraints,
5448 TemplateSpecCandidateSet *FailedTSC) {
5449 assert(DependentDeduction || Info.getDeducedDepth() == 0);
5450 if (Init->containsErrors())
5452
5453 const AutoType *AT = Type.getType()->getContainedAutoType();
5454 assert(AT);
5455
5456 if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
5457 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
5458 if (NonPlaceholder.isInvalid())
5460 Init = NonPlaceholder.get();
5461 }
5462
5463 DependentAuto DependentResult = {
5464 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
5465
5466 if (!DependentDeduction &&
5467 (Type.getType()->isDependentType() || Init->isTypeDependent() ||
5468 Init->containsUnexpandedParameterPack())) {
5469 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5470 assert(!Result.isNull() && "substituting DependentTy can't fail");
5472 }
5473
5474 auto *InitList = dyn_cast<InitListExpr>(Init);
5475 bool IsArrayType = Type.getType()->isArrayType();
5476 if (!getLangOpts().CPlusPlus && (InitList || IsArrayType)) {
5477 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c)
5478 << (int)AT->getKeyword() << IsArrayType;
5480 }
5481
5482 // Emit a warning if 'auto*' is used in pedantic and in C23 mode.
5483 if (getLangOpts().C23 && Type.getType()->isPointerType()) {
5484 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5485 }
5486
5487 // Deduce type of TemplParam in Func(Init)
5489 Deduced.resize(1);
5490
5491 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
5492
5493 QualType DeducedType;
5494 // If this is a 'decltype(auto)' specifier, do the decltype dance.
5495 if (AT->isDecltypeAuto()) {
5496 if (InitList) {
5497 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
5499 }
5500
5501 DeducedType = getDecltypeForExpr(Init);
5502 assert(!DeducedType.isNull());
5503 } else {
5504 LocalInstantiationScope InstScope(*this);
5505
5506 // Build template<class TemplParam> void Func(FuncParam);
5507 SourceLocation Loc = Init->getExprLoc();
5509 Context, nullptr, SourceLocation(), Loc, Info.getDeducedDepth(), 0,
5510 nullptr, false, false, false);
5511 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
5512 NamedDecl *TemplParamPtr = TemplParam;
5514 Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
5515
5516 if (InitList) {
5517 // Notionally, we substitute std::initializer_list<T> for 'auto' and
5518 // deduce against that. Such deduction only succeeds if removing
5519 // cv-qualifiers and references results in std::initializer_list<T>.
5520 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
5522
5523 SourceRange DeducedFromInitRange;
5524 for (Expr *Init : InitList->inits()) {
5525 // Resolving a core issue: a braced-init-list containing any designators
5526 // is a non-deduced context.
5530 *this, TemplateParamsSt.get(), 0, TemplArg, Init->getType(),
5531 Init->Classify(getASTContext()), Init, Info, Deduced,
5532 OriginalCallArgs,
5533 /*Decomposed=*/true,
5534 /*ArgIdx=*/0, /*TDF=*/0);
5537 Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction)
5538 << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
5539 << Init->getSourceRange();
5541 }
5542 return TDK;
5543 }
5544
5545 if (DeducedFromInitRange.isInvalid() &&
5546 Deduced[0].getKind() != TemplateArgument::Null)
5547 DeducedFromInitRange = Init->getSourceRange();
5548 }
5549 } else {
5550 if (!getLangOpts().CPlusPlus && Init->refersToBitField() &&
5551 AT->getKeyword() == AutoTypeKeyword::GNUAutoType) {
5552 Diag(Loc, diag::err_auto_bitfield);
5554 }
5555 QualType FuncParam =
5556 SubstituteDeducedTypeTransform(*this, TemplArg).Apply(Type);
5557 assert(!FuncParam.isNull() &&
5558 "substituting template parameter for 'auto' failed");
5560 *this, TemplateParamsSt.get(), 0, FuncParam, Init->getType(),
5561 Init->Classify(getASTContext()), Init, Info, Deduced,
5562 OriginalCallArgs,
5563 /*Decomposed=*/false, /*ArgIdx=*/0, /*TDF=*/0, FailedTSC);
5565 return TDK;
5566 }
5567
5568 // Could be null if somehow 'auto' appears in a non-deduced context.
5571 DeducedType = Deduced[0].getAsType();
5572
5573 if (InitList) {
5574 DeducedType = BuildStdInitializerList(DeducedType, Loc);
5575 if (DeducedType.isNull())
5577 }
5578 }
5579
5580 if (!Result.isNull()) {
5581 if (!Context.hasSameType(DeducedType, Result)) {
5582 Info.FirstArg = Result;
5583 Info.SecondArg = DeducedType;
5585 }
5586 DeducedType = Context.getCommonSugaredType(Result, DeducedType);
5587 }
5588
5589 if (AT->isConstrained() && !IgnoreConstraints &&
5591 *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType))
5593
5594 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
5595 if (Result.isNull())
5597
5598 // Check that the deduced argument type is compatible with the original
5599 // argument type per C++ [temp.deduct.call]p4.
5600 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
5601 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
5602 assert((bool)InitList == OriginalArg.DecomposedParam &&
5603 "decomposed non-init-list in auto deduction?");
5604 if (auto TDK =
5605 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
5607 Result = QualType();
5608 return TDK;
5609 }
5610 }
5611
5613}
5614
5616 QualType TypeToReplaceAuto) {
5617 assert(TypeToReplaceAuto != Context.DependentTy);
5618 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5619 .TransformType(TypeWithAuto);
5620}
5621
5623 QualType TypeToReplaceAuto) {
5624 assert(TypeToReplaceAuto != Context.DependentTy);
5625 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5626 .TransformType(TypeWithAuto);
5627}
5628
5630 return SubstituteDeducedTypeTransform(
5631 *this,
5632 DependentAuto{/*IsPack=*/isa<PackExpansionType>(TypeWithAuto)})
5633 .TransformType(TypeWithAuto);
5634}
5635
5638 return SubstituteDeducedTypeTransform(
5639 *this, DependentAuto{/*IsPack=*/isa<PackExpansionType>(
5640 TypeWithAuto->getType())})
5641 .TransformType(TypeWithAuto);
5642}
5643
5645 QualType TypeToReplaceAuto) {
5646 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5647 /*UseTypeSugar*/ false)
5648 .TransformType(TypeWithAuto);
5649}
5650
5652 QualType TypeToReplaceAuto) {
5653 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5654 /*UseTypeSugar*/ false)
5655 .TransformType(TypeWithAuto);
5656}
5657
5659 const Expr *Init) {
5661 Diag(VDecl->getLocation(),
5662 VDecl->isInitCapture()
5663 ? diag::err_init_capture_deduction_failure_from_init_list
5664 : diag::err_auto_var_deduction_failure_from_init_list)
5665 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
5666 else
5667 Diag(VDecl->getLocation(),
5668 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
5669 : diag::err_auto_var_deduction_failure)
5670 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5671 << Init->getSourceRange();
5672}
5673
5675 bool Diagnose) {
5676 assert(FD->getReturnType()->isUndeducedType());
5677
5678 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
5679 // within the return type from the call operator's type.
5681 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5682 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5683
5684 // For a generic lambda, instantiate the call operator if needed.
5685 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5687 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5688 if (!CallOp || CallOp->isInvalidDecl())
5689 return true;
5690
5691 // We might need to deduce the return type by instantiating the definition
5692 // of the operator() function.
5693 if (CallOp->getReturnType()->isUndeducedType()) {
5695 InstantiateFunctionDefinition(Loc, CallOp);
5696 });
5697 }
5698 }
5699
5700 if (CallOp->isInvalidDecl())
5701 return true;
5702 assert(!CallOp->getReturnType()->isUndeducedType() &&
5703 "failed to deduce lambda return type");
5704
5705 // Build the new return type from scratch.
5706 CallingConv RetTyCC = FD->getReturnType()
5707 ->getPointeeType()
5708 ->castAs<FunctionType>()
5709 ->getCallConv();
5711 CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
5712 if (FD->getReturnType()->getAs<PointerType>())
5713 RetType = Context.getPointerType(RetType);
5714 else {
5715 assert(FD->getReturnType()->getAs<BlockPointerType>());
5716 RetType = Context.getBlockPointerType(RetType);
5717 }
5718 Context.adjustDeducedFunctionResultType(FD, RetType);
5719 return false;
5720 }
5721
5725 });
5726 }
5727
5728 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
5729 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
5730 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
5731 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
5732 }
5733
5734 return StillUndeduced;
5735}
5736
5738 SourceLocation Loc) {
5739 assert(FD->isImmediateEscalating());
5740
5742 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5743 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5744
5745 // For a generic lambda, instantiate the call operator if needed.
5746 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5748 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5749 if (!CallOp || CallOp->isInvalidDecl())
5750 return true;
5752 Loc, [&] { InstantiateFunctionDefinition(Loc, CallOp); });
5753 }
5754 return CallOp->isInvalidDecl();
5755 }
5756
5759 Loc, [&] { InstantiateFunctionDefinition(Loc, FD); });
5760 }
5761 return false;
5762}
5763
5765 const CXXMethodDecl *Method,
5766 QualType RawType,
5767 bool IsOtherRvr) {
5768 // C++20 [temp.func.order]p3.1, p3.2:
5769 // - The type X(M) is "rvalue reference to cv A" if the optional
5770 // ref-qualifier of M is && or if M has no ref-qualifier and the
5771 // positionally-corresponding parameter of the other transformed template
5772 // has rvalue reference type; if this determination depends recursively
5773 // upon whether X(M) is an rvalue reference type, it is not considered to
5774 // have rvalue reference type.
5775 //
5776 // - Otherwise, X(M) is "lvalue reference to cv A".
5777 assert(Method && !Method->isExplicitObjectMemberFunction() &&
5778 "expected a member function with no explicit object parameter");
5779
5780 RawType = Context.getQualifiedType(RawType, Method->getMethodQualifiers());
5781 if (Method->getRefQualifier() == RQ_RValue ||
5782 (IsOtherRvr && Method->getRefQualifier() == RQ_None))
5783 return Context.getRValueReferenceType(RawType);
5784 return Context.getLValueReferenceType(RawType);
5785}
5786
5789 QualType A, ArrayRef<TemplateArgument> DeducedArgs, bool CheckConsistency) {
5790 MultiLevelTemplateArgumentList MLTAL(FTD, DeducedArgs,
5791 /*Final=*/true);
5793 S,
5794 ArgIdx ? ::getPackIndexForParam(S, FTD, MLTAL, *ArgIdx) : std::nullopt);
5795 bool IsIncompleteSubstitution = false;
5796 // FIXME: A substitution can be incomplete on a non-structural part of the
5797 // type. Use the canonical type for now, until the TemplateInstantiator can
5798 // deal with that.
5799
5800 // Workaround: Implicit deduction guides use InjectedClassNameTypes, whereas
5801 // the explicit guides don't. The substitution doesn't transform these types,
5802 // so let it transform their specializations instead.
5803 bool IsDeductionGuide = isa<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
5804 if (IsDeductionGuide) {
5805 if (auto *Injected = P->getAsCanonical<InjectedClassNameType>())
5806 P = Injected->getDecl()->getCanonicalTemplateSpecializationType(
5807 S.Context);
5808 }
5809 QualType InstP = S.SubstType(P.getCanonicalType(), MLTAL, FTD->getLocation(),
5810 FTD->getDeclName(), &IsIncompleteSubstitution);
5811 if (InstP.isNull() && !IsIncompleteSubstitution)
5813 if (!CheckConsistency)
5815 if (IsIncompleteSubstitution)
5817
5818 // [temp.deduct.call]/4 - Check we produced a consistent deduction.
5819 // This handles just the cases that can appear when partial ordering.
5820 if (auto *PA = dyn_cast<PackExpansionType>(A);
5821 PA && !isa<PackExpansionType>(InstP))
5822 A = PA->getPattern();
5825 if (IsDeductionGuide) {
5826 if (auto *Injected = T1->getAsCanonical<InjectedClassNameType>())
5827 T1 = Injected->getDecl()->getCanonicalTemplateSpecializationType(
5828 S.Context);
5829 if (auto *Injected = T2->getAsCanonical<InjectedClassNameType>())
5830 T2 = Injected->getDecl()->getCanonicalTemplateSpecializationType(
5831 S.Context);
5832 }
5833 if (!S.Context.hasSameType(T1, T2))
5836}
5837
5838template <class T>
5840 Sema &S, FunctionTemplateDecl *FTD,
5843 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(FTD));
5844
5845 // C++26 [temp.deduct.type]p2:
5846 // [...] or if any template argument remains neither deduced nor
5847 // explicitly specified, template argument deduction fails.
5848 bool IsIncomplete = false;
5849 Sema::CheckTemplateArgumentInfo CTAI(/*PartialOrdering=*/true);
5851 S, FTD, FTD->getTemplateParameters(), /*IsDeduced=*/true, Deduced,
5852 Info, CTAI,
5853 /*CurrentInstantiationScope=*/nullptr,
5854 /*NumAlreadyConverted=*/0, &IsIncomplete);
5856 return Result;
5857
5858 // Form the template argument list from the deduced template arguments.
5859 TemplateArgumentList *SugaredDeducedArgumentList =
5861 TemplateArgumentList *CanonicalDeducedArgumentList =
5863
5864 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
5865
5866 // Substitute the deduced template arguments into the argument
5867 // and verify that the instantiated argument is both valid
5868 // and equivalent to the parameter.
5869 LocalInstantiationScope InstScope(S);
5870 return CheckDeductionConsistency(S, FTD, CTAI.SugaredConverted);
5871}
5872
5873/// Determine whether the function template \p FT1 is at least as
5874/// specialized as \p FT2.
5878 ArrayRef<QualType> Args1, ArrayRef<QualType> Args2, bool Args1Offset) {
5879 FunctionDecl *FD1 = FT1->getTemplatedDecl();
5880 FunctionDecl *FD2 = FT2->getTemplatedDecl();
5881 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
5882 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
5883 assert(Proto1 && Proto2 && "Function templates must have prototypes");
5884
5885 // C++26 [temp.deduct.partial]p3:
5886 // The types used to determine the ordering depend on the context in which
5887 // the partial ordering is done:
5888 // - In the context of a function call, the types used are those function
5889 // parameter types for which the function call has arguments.
5890 // - In the context of a call to a conversion operator, the return types
5891 // of the conversion function templates are used.
5892 // - In other contexts (14.6.6.2) the function template's function type
5893 // is used.
5894
5895 if (TPOC == TPOC_Other) {
5896 // We wouldn't be partial ordering these candidates if these didn't match.
5897 assert(Proto1->getMethodQuals() == Proto2->getMethodQuals() &&
5898 Proto1->getRefQualifier() == Proto2->getRefQualifier() &&
5899 Proto1->isVariadic() == Proto2->isVariadic() &&
5900 "shouldn't partial order functions with different qualifiers in a "
5901 "context where the function type is used");
5902
5903 assert(Args1.empty() && Args2.empty() &&
5904 "Only call context should have arguments");
5905 Args1 = Proto1->getParamTypes();
5906 Args2 = Proto2->getParamTypes();
5907 }
5908
5909 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
5911 TemplateDeductionInfo Info(Loc);
5912
5913 bool HasDeducedAnyParamFromReturnType = false;
5914 if (TPOC != TPOC_Call) {
5916 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
5918 /*DeducedFromArrayBound=*/false,
5919 &HasDeducedAnyParamFromReturnType) !=
5921 return false;
5922 }
5923
5924 llvm::SmallBitVector HasDeducedParam;
5925 if (TPOC != TPOC_Conversion) {
5926 HasDeducedParam.resize(Args2.size());
5927 if (DeduceTemplateArguments(S, TemplateParams, Args2, Args1, Info, Deduced,
5929 /*HasDeducedAnyParam=*/nullptr,
5930 &HasDeducedParam) !=
5932 return false;
5933 }
5934
5935 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
5938 Sema::SFINAETrap Trap(S, Info);
5940 S, Info.getLocation(), FT2, DeducedArgs,
5942 if (Inst.isInvalid())
5943 return false;
5944
5945 bool AtLeastAsSpecialized;
5947 AtLeastAsSpecialized =
5948 ::FinishTemplateArgumentDeduction(
5949 S, FT2, Deduced, Info,
5950 [&](Sema &S, FunctionTemplateDecl *FTD,
5951 ArrayRef<TemplateArgument> DeducedArgs) {
5952 // As a provisional fix for a core issue that does not
5953 // exist yet, which may be related to CWG2160, only check the
5954 // consistency of parameters and return types which participated
5955 // in deduction. We will still try to substitute them though.
5956 if (TPOC != TPOC_Call) {
5957 if (auto TDR = ::CheckDeductionConsistency(
5958 S, FTD, /*ArgIdx=*/std::nullopt,
5959 Proto2->getReturnType(), Proto1->getReturnType(),
5960 DeducedArgs,
5961 /*CheckConsistency=*/HasDeducedAnyParamFromReturnType);
5962 TDR != TemplateDeductionResult::Success)
5963 return TDR;
5964 }
5965
5966 if (TPOC == TPOC_Conversion)
5967 return TemplateDeductionResult::Success;
5968
5969 return ::DeduceForEachType(
5970 S, TemplateParams, Args2, Args1, Info, Deduced,
5971 PartialOrderingKind::Call, /*FinishingDeduction=*/true,
5972 [&](Sema &S, TemplateParameterList *, int ParamIdx,
5973 UnsignedOrNone ArgIdx, QualType P, QualType A,
5974 TemplateDeductionInfo &Info,
5975 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5976 PartialOrderingKind) {
5977 if (ArgIdx && *ArgIdx >= static_cast<unsigned>(Args1Offset))
5978 ArgIdx = *ArgIdx - Args1Offset;
5979 else
5980 ArgIdx = std::nullopt;
5981 return ::CheckDeductionConsistency(
5982 S, FTD, ArgIdx, P, A, DeducedArgs,
5983 /*CheckConsistency=*/HasDeducedParam[ParamIdx]);
5984 });
5986 });
5987 if (!AtLeastAsSpecialized || Trap.hasErrorOccurred())
5988 return false;
5989
5990 // C++0x [temp.deduct.partial]p11:
5991 // In most cases, all template parameters must have values in order for
5992 // deduction to succeed, but for partial ordering purposes a template
5993 // parameter may remain without a value provided it is not used in the
5994 // types being used for partial ordering. [ Note: a template parameter used
5995 // in a non-deduced context is considered used. -end note]
5996 unsigned ArgIdx = 0, NumArgs = Deduced.size();
5997 for (; ArgIdx != NumArgs; ++ArgIdx)
5998 if (Deduced[ArgIdx].isNull())
5999 break;
6000
6001 if (ArgIdx == NumArgs) {
6002 // All template arguments were deduced. FT1 is at least as specialized
6003 // as FT2.
6004 return true;
6005 }
6006
6007 // Figure out which template parameters were used.
6008 llvm::SmallBitVector UsedParameters(TemplateParams->size());
6009 switch (TPOC) {
6010 case TPOC_Call:
6011 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
6012 ::MarkUsedTemplateParameters(S.Context, Args2[I], /*OnlyDeduced=*/false,
6013 TemplateParams->getDepth(), UsedParameters);
6014 break;
6015
6016 case TPOC_Conversion:
6017 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(),
6018 /*OnlyDeduced=*/false,
6019 TemplateParams->getDepth(), UsedParameters);
6020 break;
6021
6022 case TPOC_Other:
6023 // We do not deduce template arguments from the exception specification
6024 // when determining the primary template of a function template
6025 // specialization or when taking the address of a function template.
6026 // Therefore, we do not mark template parameters in the exception
6027 // specification as used during partial ordering to prevent the following
6028 // from being ambiguous:
6029 //
6030 // template<typename T, typename U>
6031 // void f(U) noexcept(noexcept(T())); // #1
6032 //
6033 // template<typename T>
6034 // void f(T*) noexcept; // #2
6035 //
6036 // template<>
6037 // void f<int>(int*) noexcept; // explicit specialization of #2
6038 //
6039 // Although there is no corresponding wording in the standard, this seems
6040 // to be the intended behavior given the definition of
6041 // 'deduction substitution loci' in [temp.deduct].
6043 S.Context,
6044 S.Context.getFunctionTypeWithExceptionSpec(FD2->getType(), EST_None),
6045 /*OnlyDeduced=*/false, TemplateParams->getDepth(), UsedParameters);
6046 break;
6047 }
6048
6049 for (; ArgIdx != NumArgs; ++ArgIdx)
6050 // If this argument had no value deduced but was used in one of the types
6051 // used for partial ordering, then deduction fails.
6052 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
6053 return false;
6054
6055 return true;
6056}
6057
6059
6060// This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
6061// there is no wording or even resolution for this issue.
6064 const TemplateSpecializationType *TST1,
6065 const TemplateSpecializationType *TST2) {
6066 ArrayRef<TemplateArgument> As1 = TST1->template_arguments(),
6067 As2 = TST2->template_arguments();
6068 const TemplateArgument &TA1 = As1.back(), &TA2 = As2.back();
6069 // C++26 [temp.deduct.partial]p11:
6070 // If, after considering the above, function template F is at least as
6071 // specialized as function template G and vice-versa, and if G has a
6072 // trailing function parameter pack for which F does not have a
6073 // corresponding parameter, and if F does not have a trailing function
6074 // parameter pack, then F is more specialized than G.
6075 bool IsPack1 = TA1.getKind() == TemplateArgument::Pack;
6076 bool IsPack2 = TA2.getKind() == TemplateArgument::Pack;
6077 if (IsPack1 != IsPack2)
6080 if (!IsPack1 || As1.size() != As2.size())
6082
6083 unsigned PackSize1 = TA1.pack_size(), PackSize2 = TA2.pack_size();
6084 bool IsPackExpansion1 =
6085 PackSize1 && TA1.pack_elements().back().isPackExpansion();
6086 bool IsPackExpansion2 =
6087 PackSize2 && TA2.pack_elements().back().isPackExpansion();
6088 if (PackSize1 == PackSize2 && IsPackExpansion1 == IsPackExpansion2)
6090 if (PackSize1 > PackSize2 && IsPackExpansion1)
6092 if (PackSize1 < PackSize2 && IsPackExpansion2)
6095}
6096
6099 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
6100 QualType RawObj1Ty, QualType RawObj2Ty, bool Reversed,
6101 bool PartialOverloading) {
6104 const FunctionDecl *FD1 = FT1->getTemplatedDecl();
6105 const FunctionDecl *FD2 = FT2->getTemplatedDecl();
6106 bool ShouldConvert1 = false;
6107 bool ShouldConvert2 = false;
6108 bool Args1Offset = false;
6109 bool Args2Offset = false;
6110 QualType Obj1Ty;
6111 QualType Obj2Ty;
6112 if (TPOC == TPOC_Call) {
6113 const FunctionProtoType *Proto1 =
6114 FD1->getType()->castAs<FunctionProtoType>();
6115 const FunctionProtoType *Proto2 =
6116 FD2->getType()->castAs<FunctionProtoType>();
6117
6118 // - In the context of a function call, the function parameter types are
6119 // used.
6120 const CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
6121 const CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
6122 // C++20 [temp.func.order]p3
6123 // [...] Each function template M that is a member function is
6124 // considered to have a new first parameter of type
6125 // X(M), described below, inserted in its function parameter list.
6126 //
6127 // Note that we interpret "that is a member function" as
6128 // "that is a member function with no expicit object argument".
6129 // Otherwise the ordering rules for methods with expicit objet arguments
6130 // against anything else make no sense.
6131
6132 bool NonStaticMethod1 = Method1 && !Method1->isStatic(),
6133 NonStaticMethod2 = Method2 && !Method2->isStatic();
6134
6135 auto Params1Begin = Proto1->param_type_begin(),
6136 Params2Begin = Proto2->param_type_begin();
6137
6138 size_t NumComparedArguments = NumCallArguments1;
6139
6140 if (auto OO = FD1->getOverloadedOperator();
6141 (NonStaticMethod1 && NonStaticMethod2) ||
6142 (OO != OO_None && OO != OO_Call && OO != OO_Subscript)) {
6143 ShouldConvert1 =
6144 NonStaticMethod1 && !Method1->hasCXXExplicitFunctionObjectParameter();
6145 ShouldConvert2 =
6146 NonStaticMethod2 && !Method2->hasCXXExplicitFunctionObjectParameter();
6147 NumComparedArguments += 1;
6148
6149 if (ShouldConvert1) {
6150 bool IsRValRef2 =
6151 ShouldConvert2
6152 ? Method2->getRefQualifier() == RQ_RValue
6153 : Proto2->param_type_begin()[0]->isRValueReferenceType();
6154 // Compare 'this' from Method1 against first parameter from Method2.
6155 Obj1Ty = GetImplicitObjectParameterType(this->Context, Method1,
6156 RawObj1Ty, IsRValRef2);
6157 Args1.push_back(Obj1Ty);
6158 Args1Offset = true;
6159 }
6160 if (ShouldConvert2) {
6161 bool IsRValRef1 =
6162 ShouldConvert1
6163 ? Method1->getRefQualifier() == RQ_RValue
6164 : Proto1->param_type_begin()[0]->isRValueReferenceType();
6165 // Compare 'this' from Method2 against first parameter from Method1.
6166 Obj2Ty = GetImplicitObjectParameterType(this->Context, Method2,
6167 RawObj2Ty, IsRValRef1);
6168 Args2.push_back(Obj2Ty);
6169 Args2Offset = true;
6170 }
6171 } else {
6172 if (NonStaticMethod1 && Method1->hasCXXExplicitFunctionObjectParameter())
6173 Params1Begin += 1;
6174 if (NonStaticMethod2 && Method2->hasCXXExplicitFunctionObjectParameter())
6175 Params2Begin += 1;
6176 }
6177 Args1.insert(Args1.end(), Params1Begin, Proto1->param_type_end());
6178 Args2.insert(Args2.end(), Params2Begin, Proto2->param_type_end());
6179
6180 // C++ [temp.func.order]p5:
6181 // The presence of unused ellipsis and default arguments has no effect on
6182 // the partial ordering of function templates.
6183 Args1.resize(std::min(Args1.size(), NumComparedArguments));
6184 Args2.resize(std::min(Args2.size(), NumComparedArguments));
6185
6186 if (Reversed)
6187 std::reverse(Args2.begin(), Args2.end());
6188 } else {
6189 assert(!Reversed && "Only call context could have reversed arguments");
6190 }
6191 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, Args1,
6192 Args2, Args2Offset);
6193 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, Args2,
6194 Args1, Args1Offset);
6195 // C++ [temp.deduct.partial]p10:
6196 // F is more specialized than G if F is at least as specialized as G and G
6197 // is not at least as specialized as F.
6198 if (Better1 != Better2) // We have a clear winner
6199 return Better1 ? FT1 : FT2;
6200
6201 if (!Better1 && !Better2) // Neither is better than the other
6202 return nullptr;
6203
6204 // C++ [temp.deduct.partial]p11:
6205 // ... and if G has a trailing function parameter pack for which F does not
6206 // have a corresponding parameter, and if F does not have a trailing
6207 // function parameter pack, then F is more specialized than G.
6208
6209 SmallVector<QualType> Param1;
6210 Param1.reserve(FD1->param_size() + ShouldConvert1);
6211 if (ShouldConvert1)
6212 Param1.push_back(Obj1Ty);
6213 for (const auto &P : FD1->parameters())
6214 Param1.push_back(P->getType());
6215
6216 SmallVector<QualType> Param2;
6217 Param2.reserve(FD2->param_size() + ShouldConvert2);
6218 if (ShouldConvert2)
6219 Param2.push_back(Obj2Ty);
6220 for (const auto &P : FD2->parameters())
6221 Param2.push_back(P->getType());
6222
6223 unsigned NumParams1 = Param1.size();
6224 unsigned NumParams2 = Param2.size();
6225
6226 bool Variadic1 =
6227 FD1->param_size() && FD1->parameters().back()->isParameterPack();
6228 bool Variadic2 =
6229 FD2->param_size() && FD2->parameters().back()->isParameterPack();
6230 if (Variadic1 != Variadic2) {
6231 if (Variadic1 && NumParams1 > NumParams2)
6232 return FT2;
6233 if (Variadic2 && NumParams2 > NumParams1)
6234 return FT1;
6235 }
6236
6237 // Skip this tie breaker if we are performing overload resolution with partial
6238 // arguments, as this breaks some assumptions about how closely related the
6239 // candidates are.
6240 for (int i = 0, e = std::min(NumParams1, NumParams2);
6241 !PartialOverloading && i < e; ++i) {
6242 QualType T1 = Param1[i].getCanonicalType();
6243 QualType T2 = Param2[i].getCanonicalType();
6244 auto *TST1 = dyn_cast<TemplateSpecializationType>(T1);
6245 auto *TST2 = dyn_cast<TemplateSpecializationType>(T2);
6246 if (!TST1 || !TST2)
6247 continue;
6248 switch (getMoreSpecializedTrailingPackTieBreaker(TST1, TST2)) {
6250 return FT1;
6252 return FT2;
6254 continue;
6255 }
6256 llvm_unreachable(
6257 "unknown MoreSpecializedTrailingPackTieBreakerResult value");
6258 }
6259
6260 if (!Context.getLangOpts().CPlusPlus20)
6261 return nullptr;
6262
6263 // Match GCC on not implementing [temp.func.order]p6.2.1.
6264
6265 // C++20 [temp.func.order]p6:
6266 // If deduction against the other template succeeds for both transformed
6267 // templates, constraints can be considered as follows:
6268
6269 // C++20 [temp.func.order]p6.1:
6270 // If their template-parameter-lists (possibly including template-parameters
6271 // invented for an abbreviated function template ([dcl.fct])) or function
6272 // parameter lists differ in length, neither template is more specialized
6273 // than the other.
6276 if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
6277 return nullptr;
6278
6279 // C++20 [temp.func.order]p6.2.2:
6280 // Otherwise, if the corresponding template-parameters of the
6281 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6282 // function parameters that positionally correspond between the two
6283 // templates are not of the same type, neither template is more specialized
6284 // than the other.
6285 if (!TemplateParameterListsAreEqual(TPL1, TPL2, false,
6287 return nullptr;
6288
6289 // [dcl.fct]p5:
6290 // Any top-level cv-qualifiers modifying a parameter type are deleted when
6291 // forming the function type.
6292 for (unsigned i = 0; i < NumParams1; ++i)
6293 if (!Context.hasSameUnqualifiedType(Param1[i], Param2[i]))
6294 return nullptr;
6295
6296 // C++20 [temp.func.order]p6.3:
6297 // Otherwise, if the context in which the partial ordering is done is
6298 // that of a call to a conversion function and the return types of the
6299 // templates are not the same, then neither template is more specialized
6300 // than the other.
6301 if (TPOC == TPOC_Conversion &&
6302 !Context.hasSameType(FD1->getReturnType(), FD2->getReturnType()))
6303 return nullptr;
6304
6306 FT1->getAssociatedConstraints(AC1);
6307 FT2->getAssociatedConstraints(AC2);
6308 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6309 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
6310 return nullptr;
6311 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
6312 return nullptr;
6313 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6314 return nullptr;
6315 return AtLeastAsConstrained1 ? FT1 : FT2;
6316}
6317
6320 TemplateSpecCandidateSet &FailedCandidates,
6321 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
6322 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
6323 bool Complain, QualType TargetType) {
6324 if (SpecBegin == SpecEnd) {
6325 if (Complain) {
6326 Diag(Loc, NoneDiag);
6327 FailedCandidates.NoteCandidates(*this, Loc);
6328 }
6329 return SpecEnd;
6330 }
6331
6332 if (SpecBegin + 1 == SpecEnd)
6333 return SpecBegin;
6334
6335 // Find the function template that is better than all of the templates it
6336 // has been compared to.
6337 UnresolvedSetIterator Best = SpecBegin;
6338 FunctionTemplateDecl *BestTemplate
6339 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
6340 assert(BestTemplate && "Not a function template specialization?");
6341 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
6342 FunctionTemplateDecl *Challenger
6343 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6344 assert(Challenger && "Not a function template specialization?");
6345 if (declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6346 Loc, TPOC_Other, 0),
6347 Challenger)) {
6348 Best = I;
6349 BestTemplate = Challenger;
6350 }
6351 }
6352
6353 // Make sure that the "best" function template is more specialized than all
6354 // of the others.
6355 bool Ambiguous = false;
6356 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6357 FunctionTemplateDecl *Challenger
6358 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6359 if (I != Best &&
6360 !declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6361 Loc, TPOC_Other, 0),
6362 BestTemplate)) {
6363 Ambiguous = true;
6364 break;
6365 }
6366 }
6367
6368 if (!Ambiguous) {
6369 // We found an answer. Return it.
6370 return Best;
6371 }
6372
6373 // Diagnose the ambiguity.
6374 if (Complain) {
6375 Diag(Loc, AmbigDiag);
6376
6377 // FIXME: Can we order the candidates in some sane way?
6378 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6379 PartialDiagnostic PD = CandidateDiag;
6380 const auto *FD = cast<FunctionDecl>(*I);
6382 FD->getPrimaryTemplate()->getTemplateParameters(),
6383 *FD->getTemplateSpecializationArgs());
6384 if (!TargetType.isNull())
6385 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
6386 Diag((*I)->getLocation(), PD);
6387 }
6388 }
6389
6390 return SpecEnd;
6391}
6392
6394 FunctionDecl *FD2) {
6395 assert(!FD1->getDescribedTemplate() && !FD2->getDescribedTemplate() &&
6396 "not for function templates");
6397 assert(!FD1->isFunctionTemplateSpecialization() ||
6399 assert(!FD2->isFunctionTemplateSpecialization() ||
6401
6402 FunctionDecl *F1 = FD1;
6403 if (FunctionDecl *P = FD1->getTemplateInstantiationPattern(false))
6404 F1 = P;
6405
6406 FunctionDecl *F2 = FD2;
6407 if (FunctionDecl *P = FD2->getTemplateInstantiationPattern(false))
6408 F2 = P;
6409
6411 F1->getAssociatedConstraints(AC1);
6412 F2->getAssociatedConstraints(AC2);
6413 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6414 if (IsAtLeastAsConstrained(F1, AC1, F2, AC2, AtLeastAsConstrained1))
6415 return nullptr;
6416 if (IsAtLeastAsConstrained(F2, AC2, F1, AC1, AtLeastAsConstrained2))
6417 return nullptr;
6418 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6419 return nullptr;
6420 return AtLeastAsConstrained1 ? FD1 : FD2;
6421}
6422
6423/// Determine whether one template specialization, P1, is at least as
6424/// specialized than another, P2.
6425///
6426/// \tparam TemplateLikeDecl The kind of P2, which must be a
6427/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
6428/// \param T1 The injected-class-name of P1 (faked for a variable template).
6429/// \param T2 The injected-class-name of P2 (faked for a variable template).
6430/// \param Template The primary template of P2, in case it is a partial
6431/// specialization, the same as P2 otherwise.
6432template <typename TemplateLikeDecl>
6434 TemplateLikeDecl *P2,
6436 TemplateDeductionInfo &Info) {
6437 // C++ [temp.class.order]p1:
6438 // For two class template partial specializations, the first is at least as
6439 // specialized as the second if, given the following rewrite to two
6440 // function templates, the first function template is at least as
6441 // specialized as the second according to the ordering rules for function
6442 // templates (14.6.6.2):
6443 // - the first function template has the same template parameters as the
6444 // first partial specialization and has a single function parameter
6445 // whose type is a class template specialization with the template
6446 // arguments of the first partial specialization, and
6447 // - the second function template has the same template parameters as the
6448 // second partial specialization and has a single function parameter
6449 // whose type is a class template specialization with the template
6450 // arguments of the second partial specialization.
6451 //
6452 // Rather than synthesize function templates, we merely perform the
6453 // equivalent partial ordering by performing deduction directly on
6454 // the template arguments of the class template partial
6455 // specializations. This computation is slightly simpler than the
6456 // general problem of function template partial ordering, because
6457 // class template partial specializations are more constrained. We
6458 // know that every template parameter is deducible from the class
6459 // template partial specialization's template arguments, for
6460 // example.
6462
6463 // Determine whether P1 is at least as specialized as P2.
6464 Deduced.resize(P2->getTemplateParameters()->size());
6466 S, P2->getTemplateParameters(), T2, T1, Info, Deduced, TDF_None,
6467 PartialOrderingKind::Call, /*DeducedFromArrayBound=*/false,
6468 /*HasDeducedAnyParam=*/nullptr) != TemplateDeductionResult::Success)
6469 return false;
6470
6471 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
6474 Sema::SFINAETrap Trap(S, Info);
6475 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs);
6476 if (Inst.isInvalid())
6477 return false;
6478
6480 Ps = cast<TemplateSpecializationType>(T2)->template_arguments(),
6481 As = cast<TemplateSpecializationType>(T1)->template_arguments();
6482
6485 Result = ::FinishTemplateArgumentDeduction(
6486 S, P2, P2->getTemplateParameters(), Template,
6487 /*IsPartialOrdering=*/true, Ps, As, Deduced, Info,
6488 /*CopyDeducedArgs=*/false);
6489 });
6491}
6492
6493namespace {
6494// A dummy class to return nullptr instead of P2 when performing "more
6495// specialized than primary" check.
6496struct GetP2 {
6497 template <typename T1, typename T2,
6498 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6499 T2 *operator()(T1 *, T2 *P2) {
6500 return P2;
6501 }
6502 template <typename T1, typename T2,
6503 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6504 T1 *operator()(T1 *, T2 *) {
6505 return nullptr;
6506 }
6507};
6508
6509// The assumption is that two template argument lists have the same size.
6510struct TemplateArgumentListAreEqual {
6511 ASTContext &Ctx;
6512 TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
6513
6514 template <typename T1, typename T2,
6515 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6516 bool operator()(T1 *PS1, T2 *PS2) {
6517 ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
6518 Args2 = PS2->getTemplateArgs().asArray();
6519
6520 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6521 // We use profile, instead of structural comparison of the arguments,
6522 // because canonicalization can't do the right thing for dependent
6523 // expressions.
6524 llvm::FoldingSetNodeID IDA, IDB;
6525 Args1[I].Profile(IDA, Ctx);
6526 Args2[I].Profile(IDB, Ctx);
6527 if (IDA != IDB)
6528 return false;
6529 }
6530 return true;
6531 }
6532
6533 template <typename T1, typename T2,
6534 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6535 bool operator()(T1 *Spec, T2 *Primary) {
6536 ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
6537 Args2 = Primary->getInjectedTemplateArgs(Ctx);
6538
6539 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6540 // We use profile, instead of structural comparison of the arguments,
6541 // because canonicalization can't do the right thing for dependent
6542 // expressions.
6543 llvm::FoldingSetNodeID IDA, IDB;
6544 Args1[I].Profile(IDA, Ctx);
6545 // Unlike the specialization arguments, the injected arguments are not
6546 // always canonical.
6547 Ctx.getCanonicalTemplateArgument(Args2[I]).Profile(IDB, Ctx);
6548 if (IDA != IDB)
6549 return false;
6550 }
6551 return true;
6552 }
6553};
6554} // namespace
6555
6556/// Returns the more specialized template specialization between T1/P1 and
6557/// T2/P2.
6558/// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
6559/// specialization and T2/P2 is the primary template.
6560/// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
6561///
6562/// \param T1 the type of the first template partial specialization
6563///
6564/// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
6565/// template partial specialization; otherwise, the type of the
6566/// primary template.
6567///
6568/// \param P1 the first template partial specialization
6569///
6570/// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
6571/// partial specialization; otherwise, the primary template.
6572///
6573/// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
6574/// more specialized, returns nullptr if P1 is not more specialized.
6575/// - otherwise, returns the more specialized template partial
6576/// specialization. If neither partial specialization is more
6577/// specialized, returns NULL.
6578template <typename TemplateLikeDecl, typename PrimaryDel>
6579static TemplateLikeDecl *
6580getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
6581 PrimaryDel *P2, TemplateDeductionInfo &Info) {
6582 constexpr bool IsMoreSpecialThanPrimaryCheck =
6583 !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
6584
6585 TemplateDecl *P2T;
6586 if constexpr (IsMoreSpecialThanPrimaryCheck)
6587 P2T = P2;
6588 else
6589 P2T = P2->getSpecializedTemplate();
6590
6591 bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, P2T, Info);
6592 if (IsMoreSpecialThanPrimaryCheck && !Better1)
6593 return nullptr;
6594
6595 bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1,
6596 P1->getSpecializedTemplate(), Info);
6597 if (IsMoreSpecialThanPrimaryCheck && !Better2)
6598 return P1;
6599
6600 // C++ [temp.deduct.partial]p10:
6601 // F is more specialized than G if F is at least as specialized as G and G
6602 // is not at least as specialized as F.
6603 if (Better1 != Better2) // We have a clear winner
6604 return Better1 ? P1 : GetP2()(P1, P2);
6605
6606 if (!Better1 && !Better2)
6607 return nullptr;
6608
6613 return P1;
6615 return GetP2()(P1, P2);
6617 break;
6618 }
6619
6620 if (!S.Context.getLangOpts().CPlusPlus20)
6621 return nullptr;
6622
6623 // Match GCC on not implementing [temp.func.order]p6.2.1.
6624
6625 // C++20 [temp.func.order]p6:
6626 // If deduction against the other template succeeds for both transformed
6627 // templates, constraints can be considered as follows:
6628
6629 TemplateParameterList *TPL1 = P1->getTemplateParameters();
6630 TemplateParameterList *TPL2 = P2->getTemplateParameters();
6631 if (TPL1->size() != TPL2->size())
6632 return nullptr;
6633
6634 // C++20 [temp.func.order]p6.2.2:
6635 // Otherwise, if the corresponding template-parameters of the
6636 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6637 // function parameters that positionally correspond between the two
6638 // templates are not of the same type, neither template is more specialized
6639 // than the other.
6640 if (!S.TemplateParameterListsAreEqual(TPL1, TPL2, false,
6642 return nullptr;
6643
6644 if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
6645 return nullptr;
6646
6648 P1->getAssociatedConstraints(AC1);
6649 P2->getAssociatedConstraints(AC2);
6650 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6651 if (S.IsAtLeastAsConstrained(P1, AC1, P2, AC2, AtLeastAsConstrained1) ||
6652 (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
6653 return nullptr;
6654 if (S.IsAtLeastAsConstrained(P2, AC2, P1, AC1, AtLeastAsConstrained2))
6655 return nullptr;
6656 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6657 return nullptr;
6658 return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
6659}
6660
6672
6675 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
6678
6680 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6681 if (MaybeSpec)
6682 Info.clearSFINAEDiagnostic();
6683 return MaybeSpec;
6684}
6685
6690 // Pretend the variable template specializations are class template
6691 // specializations and form a fake injected class name type for comparison.
6692 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
6693 "the partial specializations being compared should specialize"
6694 " the same template.");
6696 QualType PT1 = Context.getCanonicalTemplateSpecializationType(
6698 QualType PT2 = Context.getCanonicalTemplateSpecializationType(
6700
6701 TemplateDeductionInfo Info(Loc);
6702 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6703}
6704
6707 VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
6708 TemplateName Name(Primary->getCanonicalDecl());
6709
6710 SmallVector<TemplateArgument, 8> PrimaryCanonArgs(
6712 Context.canonicalizeTemplateArguments(PrimaryCanonArgs);
6713
6714 QualType PrimaryT = Context.getCanonicalTemplateSpecializationType(
6715 ElaboratedTypeKeyword::None, Name, PrimaryCanonArgs);
6716 QualType PartialT = Context.getCanonicalTemplateSpecializationType(
6718
6720 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6721 if (MaybeSpec)
6722 Info.clearSFINAEDiagnostic();
6723 return MaybeSpec;
6724}
6725
6728 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
6729 bool PartialOrdering, bool *StrictPackMatch) {
6730 // C++1z [temp.arg.template]p4: (DR 150)
6731 // A template template-parameter P is at least as specialized as a
6732 // template template-argument A if, given the following rewrite to two
6733 // function templates...
6734
6735 // Rather than synthesize function templates, we merely perform the
6736 // equivalent partial ordering by performing deduction directly on
6737 // the template parameter lists of the template template parameters.
6738 //
6740
6744 if (Inst.isInvalid())
6745 return false;
6746
6748
6749 // Given an invented class template X with the template parameter list of
6750 // A (including default arguments):
6751 // - Each function template has a single function parameter whose type is
6752 // a specialization of X with template arguments corresponding to the
6753 // template parameters from the respective function template
6755
6756 // Check P's arguments against A's parameter list. This will fill in default
6757 // template arguments as needed. AArgs are already correct by construction.
6758 // We can't just use CheckTemplateIdType because that will expand alias
6759 // templates.
6761 {
6763 P->getRAngleLoc());
6764 for (unsigned I = 0, N = P->size(); I != N; ++I) {
6765 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
6766 // expansions, to form an "as written" argument list.
6767 TemplateArgument Arg = PArgs[I];
6768 if (Arg.getKind() == TemplateArgument::Pack) {
6769 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
6770 Arg = *Arg.pack_begin();
6771 }
6773 Arg, QualType(), P->getParam(I)->getLocation()));
6774 }
6775 PArgs.clear();
6776
6777 // C++1z [temp.arg.template]p3:
6778 // If the rewrite produces an invalid type, then P is not at least as
6779 // specialized as A.
6781 /*PartialOrdering=*/false, /*MatchingTTP=*/true);
6782 CTAI.SugaredConverted = std::move(PArgs);
6783 if (CheckTemplateArgumentList(AArg, ArgLoc, PArgList, DefaultArgs,
6784 /*PartialTemplateArgs=*/false, CTAI,
6785 /*UpdateArgsWithConversions=*/true,
6786 /*ConstraintsNotSatisfied=*/nullptr))
6787 return false;
6788 PArgs = std::move(CTAI.SugaredConverted);
6789 if (StrictPackMatch)
6790 *StrictPackMatch |= CTAI.StrictPackMatch;
6791 }
6792
6793 // Determine whether P1 is at least as specialized as P2.
6794 TemplateDeductionInfo Info(ArgLoc, A->getDepth());
6796 Deduced.resize(A->size());
6797
6798 // ... the function template corresponding to P is at least as specialized
6799 // as the function template corresponding to A according to the partial
6800 // ordering rules for function templates.
6801
6802 // Provisional resolution for CWG2398: Regarding temp.arg.template]p4, when
6803 // applying the partial ordering rules for function templates on
6804 // the rewritten template template parameters:
6805 // - In a deduced context, the matching of packs versus fixed-size needs to
6806 // be inverted between Ps and As. On non-deduced context, matching needs to
6807 // happen both ways, according to [temp.arg.template]p3, but this is
6808 // currently implemented as a special case elsewhere.
6810 *this, A, AArgs, PArgs, Info, Deduced,
6811 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/true,
6813 /*HasDeducedAnyParam=*/nullptr)) {
6815 if (StrictPackMatch && Info.hasStrictPackMatch())
6816 *StrictPackMatch = true;
6817 break;
6818
6820 Diag(AArg->getLocation(), diag::err_template_param_list_different_arity)
6821 << (A->size() > P->size()) << /*isTemplateTemplateParameter=*/true
6823 return false;
6825 Diag(AArg->getLocation(), diag::err_non_deduced_mismatch)
6826 << Info.FirstArg << Info.SecondArg;
6827 return false;
6830 diag::err_inconsistent_deduction)
6831 << Info.FirstArg << Info.SecondArg;
6832 return false;
6834 return false;
6835
6836 // None of these should happen for a plain deduction.
6851 llvm_unreachable("Unexpected Result");
6852 }
6853
6856 TDK = ::FinishTemplateArgumentDeduction(
6857 *this, AArg, AArg->getTemplateParameters(), AArg, PartialOrdering,
6858 AArgs, PArgs, Deduced, Info, /*CopyDeducedArgs=*/false);
6859 });
6860 switch (TDK) {
6862 return true;
6863
6864 // It doesn't seem possible to get a non-deduced mismatch when partial
6865 // ordering TTPs, except with an invalid template parameter list which has
6866 // a parameter after a pack.
6868 assert(PArg->isInvalidDecl() && "Unexpected NonDeducedMismatch");
6869 return false;
6870
6871 // Substitution failures should have already been diagnosed.
6875 return false;
6876
6877 // None of these should happen when just converting deduced arguments.
6892 llvm_unreachable("Unexpected Result");
6893 }
6894 llvm_unreachable("Unexpected TDK");
6895}
6896
6897namespace {
6898struct MarkUsedTemplateParameterVisitor : DynamicRecursiveASTVisitor {
6899 llvm::SmallBitVector &Used;
6900 unsigned Depth;
6901 bool VisitDeclRefTypes = true;
6902
6903 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used, unsigned Depth,
6904 bool VisitDeclRefTypes = true)
6905 : Used(Used), Depth(Depth), VisitDeclRefTypes(VisitDeclRefTypes) {}
6906
6907 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
6908 if (T->getDepth() == Depth)
6909 Used[T->getIndex()] = true;
6910 return true;
6911 }
6912
6913 bool TraverseTemplateName(TemplateName Template,
6914 bool TraverseQualifier) override {
6915 if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
6916 Template.getAsTemplateDecl()))
6917 if (TTP->getDepth() == Depth)
6918 Used[TTP->getIndex()] = true;
6920 TraverseQualifier);
6921 return true;
6922 }
6923
6924 bool VisitDeclRefExpr(DeclRefExpr *E) override {
6925 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
6926 if (NTTP->getDepth() == Depth)
6927 Used[NTTP->getIndex()] = true;
6928 if (VisitDeclRefTypes)
6930 return true;
6931 }
6932
6933 bool VisitDependentTemplateIdExpr(DependentTemplateIdExpr *E) override {
6934 TemplateTemplateParmDecl *TTP = E->getParameter();
6935 if (TTP->getDepth() == Depth)
6936 Used[TTP->getIndex()] = true;
6937 return true;
6938 }
6939
6940 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *NTTP) override {
6941 if (NTTP->getDepth() == Depth)
6942 Used[NTTP->getIndex()] = true;
6943 return true;
6944 }
6945
6946 bool TraverseSizeOfPackExpr(SizeOfPackExpr *SOPE) override {
6947 return TraverseDecl(SOPE->getPack());
6948 }
6949};
6950}
6951
6952/// Mark the template parameters that are used by the given
6953/// expression.
6954static void
6956 const Expr *E,
6957 bool OnlyDeduced,
6958 unsigned Depth,
6959 llvm::SmallBitVector &Used) {
6960 if (!OnlyDeduced) {
6961 MarkUsedTemplateParameterVisitor(Used, Depth)
6962 .TraverseStmt(const_cast<Expr *>(E));
6963 return;
6964 }
6965
6966 // We can deduce from a pack expansion.
6967 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
6968 E = Expansion->getPattern();
6969
6971
6972 if (const auto *DTI = dyn_cast<DependentTemplateIdExpr>(E)) {
6973 Used[DTI->getParameter()->getIndex()] = true;
6974 for (const auto &TLoc : DTI->template_arguments())
6975 MarkUsedTemplateParameters(Ctx, TLoc.getArgument(), OnlyDeduced, Depth,
6976 Used);
6977 return;
6978 }
6979
6981 if (!NTTP)
6982 return;
6983 if (NTTP.getDepth() == Depth)
6984 Used[NTTP.getIndex()] = true;
6985
6986 // In C++17 mode, additional arguments may be deduced from the type of a
6987 // non-type argument.
6988 if (Ctx.getLangOpts().CPlusPlus17)
6989 MarkUsedTemplateParameters(Ctx, NTTP.getType(), OnlyDeduced, Depth, Used);
6990}
6991
6992/// Mark the template parameters that are used by the given
6993/// nested name specifier.
6995 bool OnlyDeduced, unsigned Depth,
6996 llvm::SmallBitVector &Used) {
6998 return;
6999 MarkUsedTemplateParameters(Ctx, QualType(NNS.getAsType(), 0), OnlyDeduced,
7000 Depth, Used);
7001}
7002
7003/// Mark the template parameters that are used by the given
7004/// template name.
7005static void
7007 TemplateName Name,
7008 bool OnlyDeduced,
7009 unsigned Depth,
7010 llvm::SmallBitVector &Used) {
7011 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
7013 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
7014 if (TTP->getDepth() == Depth)
7015 Used[TTP->getIndex()] = true;
7016 }
7017 return;
7018 }
7019
7021 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
7022 Depth, Used);
7024 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
7025 Depth, Used);
7026}
7027
7028/// Mark the template parameters that are used by the given
7029/// type.
7030static void
7032 bool OnlyDeduced,
7033 unsigned Depth,
7034 llvm::SmallBitVector &Used) {
7035 if (T.isNull())
7036 return;
7037
7038 // Non-dependent types have nothing deducible
7039 if (!T->isDependentType())
7040 return;
7041
7042 T = Ctx.getCanonicalType(T);
7043 switch (T->getTypeClass()) {
7044 case Type::Pointer:
7047 OnlyDeduced,
7048 Depth,
7049 Used);
7050 break;
7051
7052 case Type::BlockPointer:
7055 OnlyDeduced,
7056 Depth,
7057 Used);
7058 break;
7059
7060 case Type::LValueReference:
7061 case Type::RValueReference:
7064 OnlyDeduced,
7065 Depth,
7066 Used);
7067 break;
7068
7069 case Type::MemberPointer: {
7070 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
7071 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
7072 Depth, Used);
7074 QualType(MemPtr->getQualifier().getAsType(), 0),
7075 OnlyDeduced, Depth, Used);
7076 break;
7077 }
7078
7079 case Type::DependentSizedArray:
7081 cast<DependentSizedArrayType>(T)->getSizeExpr(),
7082 OnlyDeduced, Depth, Used);
7083 // Fall through to check the element type
7084 [[fallthrough]];
7085
7086 case Type::ConstantArray:
7087 case Type::IncompleteArray:
7088 case Type::ArrayParameter:
7090 cast<ArrayType>(T)->getElementType(),
7091 OnlyDeduced, Depth, Used);
7092 break;
7093 case Type::Vector:
7094 case Type::ExtVector:
7096 cast<VectorType>(T)->getElementType(),
7097 OnlyDeduced, Depth, Used);
7098 break;
7099
7100 case Type::DependentVector: {
7101 const auto *VecType = cast<DependentVectorType>(T);
7102 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
7103 Depth, Used);
7104 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
7105 Used);
7106 break;
7107 }
7108 case Type::DependentSizedExtVector: {
7109 const DependentSizedExtVectorType *VecType
7111 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
7112 Depth, Used);
7113 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
7114 Depth, Used);
7115 break;
7116 }
7117
7118 case Type::DependentAddressSpace: {
7119 const DependentAddressSpaceType *DependentASType =
7121 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
7122 OnlyDeduced, Depth, Used);
7124 DependentASType->getAddrSpaceExpr(),
7125 OnlyDeduced, Depth, Used);
7126 break;
7127 }
7128
7129 case Type::ConstantMatrix: {
7130 const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T);
7131 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
7132 Depth, Used);
7133 break;
7134 }
7135
7136 case Type::CooperativeMatrix: {
7138 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
7139 Depth, Used);
7140 break;
7141 }
7142
7143 case Type::DependentSizedMatrix: {
7145 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
7146 Depth, Used);
7147 MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
7148 Used);
7149 MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
7150 Depth, Used);
7151 break;
7152 }
7153
7154 case Type::FunctionProto: {
7156 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
7157 Used);
7158 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
7159 // C++17 [temp.deduct.type]p5:
7160 // The non-deduced contexts are: [...]
7161 // -- A function parameter pack that does not occur at the end of the
7162 // parameter-declaration-list.
7163 if (!OnlyDeduced || I + 1 == N ||
7164 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
7165 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
7166 Depth, Used);
7167 } else {
7168 // FIXME: C++17 [temp.deduct.call]p1:
7169 // When a function parameter pack appears in a non-deduced context,
7170 // the type of that pack is never deduced.
7171 //
7172 // We should also track a set of "never deduced" parameters, and
7173 // subtract that from the list of deduced parameters after marking.
7174 }
7175 }
7176 if (auto *E = Proto->getNoexceptExpr())
7177 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
7178 break;
7179 }
7180
7181 case Type::TemplateTypeParm: {
7182 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
7183 if (TTP->getDepth() == Depth)
7184 Used[TTP->getIndex()] = true;
7185 break;
7186 }
7187
7188 case Type::SubstTemplateTypeParmPack: {
7189 const SubstTemplateTypeParmPackType *Subst
7191 if (Subst->getReplacedParameter()->getDepth() == Depth)
7192 Used[Subst->getIndex()] = true;
7193 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(), OnlyDeduced,
7194 Depth, Used);
7195 break;
7196 }
7197 case Type::SubstBuiltinTemplatePack: {
7198 MarkUsedTemplateParameters(Ctx, cast<SubstPackType>(T)->getArgumentPack(),
7199 OnlyDeduced, Depth, Used);
7200 break;
7201 }
7202
7203 case Type::InjectedClassName:
7205 ->getDecl()
7206 ->getCanonicalTemplateSpecializationType(Ctx);
7207 [[fallthrough]];
7208
7209 case Type::TemplateSpecialization: {
7210 const TemplateSpecializationType *Spec
7212
7213 TemplateName Name = Spec->getTemplateName();
7214 if (OnlyDeduced && Name.getAsDependentTemplateName())
7215 break;
7216
7217 MarkUsedTemplateParameters(Ctx, Name, OnlyDeduced, Depth, Used);
7218
7219 // C++0x [temp.deduct.type]p9:
7220 // If the template argument list of P contains a pack expansion that is
7221 // not the last template argument, the entire template argument list is a
7222 // non-deduced context.
7223 if (OnlyDeduced &&
7224 hasPackExpansionBeforeEnd(Spec->template_arguments()))
7225 break;
7226
7227 for (const auto &Arg : Spec->template_arguments())
7228 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
7229 break;
7230 }
7231
7232 case Type::Complex:
7233 if (!OnlyDeduced)
7235 cast<ComplexType>(T)->getElementType(),
7236 OnlyDeduced, Depth, Used);
7237 break;
7238
7239 case Type::Atomic:
7240 if (!OnlyDeduced)
7242 cast<AtomicType>(T)->getValueType(),
7243 OnlyDeduced, Depth, Used);
7244 break;
7245
7246 case Type::DependentName:
7247 if (!OnlyDeduced)
7249 cast<DependentNameType>(T)->getQualifier(),
7250 OnlyDeduced, Depth, Used);
7251 break;
7252
7253 case Type::TypeOf:
7254 if (!OnlyDeduced)
7255 MarkUsedTemplateParameters(Ctx, cast<TypeOfType>(T)->getUnmodifiedType(),
7256 OnlyDeduced, Depth, Used);
7257 break;
7258
7259 case Type::TypeOfExpr:
7260 if (!OnlyDeduced)
7262 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
7263 OnlyDeduced, Depth, Used);
7264 break;
7265
7266 case Type::Decltype:
7267 if (!OnlyDeduced)
7269 cast<DecltypeType>(T)->getUnderlyingExpr(),
7270 OnlyDeduced, Depth, Used);
7271 break;
7272
7273 case Type::PackIndexing:
7274 if (!OnlyDeduced) {
7276 OnlyDeduced, Depth, Used);
7277 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getIndexExpr(),
7278 OnlyDeduced, Depth, Used);
7279 }
7280 break;
7281
7282 case Type::UnaryTransform:
7283 if (!OnlyDeduced) {
7284 auto *UTT = cast<UnaryTransformType>(T);
7285 auto Next = UTT->getUnderlyingType();
7286 if (Next.isNull())
7287 Next = UTT->getBaseType();
7288 MarkUsedTemplateParameters(Ctx, Next, OnlyDeduced, Depth, Used);
7289 }
7290 break;
7291
7292 case Type::PackExpansion:
7294 cast<PackExpansionType>(T)->getPattern(),
7295 OnlyDeduced, Depth, Used);
7296 break;
7297
7298 case Type::Auto:
7299 case Type::DeducedTemplateSpecialization:
7301 cast<DeducedType>(T)->getDeducedType(),
7302 OnlyDeduced, Depth, Used);
7303 break;
7304 case Type::DependentBitInt:
7306 cast<DependentBitIntType>(T)->getNumBitsExpr(),
7307 OnlyDeduced, Depth, Used);
7308 break;
7309
7310 case Type::HLSLAttributedResource:
7312 Ctx, cast<HLSLAttributedResourceType>(T)->getWrappedType(), OnlyDeduced,
7313 Depth, Used);
7314 if (cast<HLSLAttributedResourceType>(T)->hasContainedType())
7316 Ctx, cast<HLSLAttributedResourceType>(T)->getContainedType(),
7317 OnlyDeduced, Depth, Used);
7318 break;
7319
7320 // None of these types have any template parameters in them.
7321 case Type::Builtin:
7322 case Type::VariableArray:
7323 case Type::FunctionNoProto:
7324 case Type::Record:
7325 case Type::Enum:
7326 case Type::ObjCInterface:
7327 case Type::ObjCObject:
7328 case Type::ObjCObjectPointer:
7329 case Type::UnresolvedUsing:
7330 case Type::Pipe:
7331 case Type::BitInt:
7332 case Type::HLSLInlineSpirv:
7333 case Type::OverflowBehavior:
7334#define TYPE(Class, Base)
7335#define ABSTRACT_TYPE(Class, Base)
7336#define DEPENDENT_TYPE(Class, Base)
7337#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7338#include "clang/AST/TypeNodes.inc"
7339 break;
7340 }
7341}
7342
7343/// Mark the template parameters that are used by this
7344/// template argument.
7345static void
7348 bool OnlyDeduced,
7349 unsigned Depth,
7350 llvm::SmallBitVector &Used) {
7351 switch (TemplateArg.getKind()) {
7357 break;
7358
7360 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
7361 Depth, Used);
7362 break;
7363
7367 TemplateArg.getAsTemplateOrTemplatePattern(),
7368 OnlyDeduced, Depth, Used);
7369 break;
7370
7372 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
7373 Depth, Used);
7374 break;
7375
7377 for (const auto &P : TemplateArg.pack_elements())
7378 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
7379 break;
7380 }
7381}
7382
7383void
7384Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
7385 unsigned Depth,
7386 llvm::SmallBitVector &Used) {
7387 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
7388}
7389
7391 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used) {
7392 MarkUsedTemplateParameterVisitor(Used, Depth, /*VisitDeclRefTypes=*/false)
7393 .TraverseStmt(const_cast<Expr *>(E));
7394}
7395
7396void
7398 bool OnlyDeduced, unsigned Depth,
7399 llvm::SmallBitVector &Used) {
7400 // C++0x [temp.deduct.type]p9:
7401 // If the template argument list of P contains a pack expansion that is not
7402 // the last template argument, the entire template argument list is a
7403 // non-deduced context.
7404 if (OnlyDeduced &&
7405 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
7406 return;
7407
7408 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7409 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
7410 Depth, Used);
7411}
7412
7414 bool OnlyDeduced, unsigned Depth,
7415 llvm::SmallBitVector &Used) {
7416 if (OnlyDeduced && hasPackExpansionBeforeEnd(TemplateArgs))
7417 return;
7418
7419 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7420 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced, Depth,
7421 Used);
7422}
7423
7425 ArrayRef<TemplateArgumentLoc> TemplateArgs, unsigned Depth,
7426 llvm::SmallBitVector &Used) {
7427 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7429 /*OnlyDeduced=*/false, Depth, Used);
7430}
7431
7434 llvm::SmallBitVector &Deduced) {
7435 TemplateParameterList *TemplateParams
7436 = FunctionTemplate->getTemplateParameters();
7437 Deduced.clear();
7438 Deduced.resize(TemplateParams->size());
7439
7440 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
7441 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
7442 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
7443 true, TemplateParams->getDepth(), Deduced);
7444}
7445
7448 QualType T) {
7449 if (!T->isDependentType())
7450 return false;
7451
7452 TemplateParameterList *TemplateParams
7453 = FunctionTemplate->getTemplateParameters();
7454 llvm::SmallBitVector Deduced(TemplateParams->size());
7455 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
7456 Deduced);
7457
7458 return Deduced.any();
7459}
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
Provides definitions for the various language-specific address spaces.
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Next
The next token in the unwrapped line.
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static AccessResult DeduceTemplateArguments(Sema &S, FriendTemplateDecl *FTD, DeclContext *DC, const TemplateSpecializationType *TST, ArrayRef< TemplateParameterList * > TPLs, TemplateSpecCandidateSet *FailedTSC, MultiLevelTemplateArgumentList &DeducedArgs)
static TemplateDeductionResult DeduceNullPtrTemplateArgument(Sema &S, TemplateParameterList *TemplateParams, NonTypeOrVarTemplateParmDecl NTTP, QualType NullPtrType, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
Deduce the value of the given non-type template parameter from the given null pointer template argume...
static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template, TemplateDeductionInfo &Info, bool IsDeduced, Sema::CheckTemplateArgumentInfo &CTAI)
Convert the given deduced template argument and add it to the set of fully-converted template argumen...
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
static TemplateDeductionResult DeduceTemplateSpecArguments(Sema &S, TemplateParameterList *TemplateParams, const QualType P, QualType A, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
static TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch(Sema &S, TemplateParameterList *TemplateParams, QualType Param, QualType Arg, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned TDF, PartialOrderingKind POK, bool DeducedFromArrayBound, bool *HasDeducedAnyParam)
Deduce the template arguments by comparing the parameter type and the argument type (C++ [temp....
static TemplateDeductionResult CheckDeductionConsistency(Sema &S, FunctionTemplateDecl *FTD, UnsignedOrNone ArgIdx, QualType P, QualType A, ArrayRef< TemplateArgument > DeducedArgs, bool CheckConsistency)
static PartialOrderingKind degradeCallPartialOrderingKind(PartialOrderingKind POK)
When propagating a partial ordering kind into a NonCall context, this is used to downgrade a 'Call' i...
static MoreSpecializedTrailingPackTieBreakerResult getMoreSpecializedTrailingPackTieBreaker(const TemplateSpecializationType *TST1, const TemplateSpecializationType *TST2)
static TemplateLikeDecl * getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1, PrimaryDel *P2, TemplateDeductionInfo &Info)
Returns the more specialized template specialization between T1/P1 and T2/P2.
static DeducedTemplateArgument checkDeducedTemplateArguments(ASTContext &Context, const DeducedTemplateArgument &X, const DeducedTemplateArgument &Y, bool AggregateCandidateDeduction=false)
Verify that the given, deduced template arguments are compatible.
static const Expr * unwrapExpressionForDeduction(const Expr *E)
static bool isSameDeclaration(Decl *X, Decl *Y)
Determine whether two declaration pointers refer to the same declaration.
static TemplateDeductionResult DeduceForEachType(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< QualType > Params, ArrayRef< QualType > Args, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, PartialOrderingKind POK, bool FinishingDeduction, T &&DeductFunc)
static void AddFriendTemplateDeductionCandidate(Sema &S, TemplateDecl *TD, TemplateDeductionInfo &Info, TemplateDeductionResult Result, TemplateSpecCandidateSet *FailedTSC)
static TemplateDeductionResult DeduceTemplateBases(Sema &S, const CXXRecordDecl *RD, TemplateParameterList *TemplateParams, QualType P, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
Attempt to deduce the template arguments by checking the base types according to (C++20 [temp....
static bool hasTemplateArgumentForDeduction(ArrayRef< TemplateArgument > &Args, unsigned &ArgIdx)
Determine whether there is a template argument to be used for deduction.
static DeclContext * getAsDeclContextOrEnclosing(Decl *D)
static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType, QualType ArgType)
Determine whether the parameter has qualifiers that the argument lacks.
static void MarkUsedTemplateParameters(ASTContext &Ctx, const TemplateArgument &TemplateArg, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark the template parameters that are used by this template argument.
static UnsignedOrNone getPackIndexForParam(Sema &S, FunctionTemplateDecl *FunctionTemplate, const MultiLevelTemplateArgumentList &Args, unsigned ParamIdx)
Find the pack index for a particular parameter index in an instantiation of a function template with ...
static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R, FunctionDecl *Fn)
Gets the type of a function for template-argument-deducton purposes when it's considered as part of a...
static bool hasPackExpansionBeforeEnd(ArrayRef< TemplateArgument > Args)
Determine whether the given set of template arguments has a pack expansion that is not the last templ...
static bool isSimpleTemplateIdType(QualType T)
Determine whether the given type T is a simple-template-id type.
PartialOrderingKind
The kind of PartialOrdering we're performing template argument deduction for (C++11 [temp....
static NonTypeOrVarTemplateParmDecl getNTTParameterFromExpr(const Expr *E, UnsignedOrNone Depth)
If the given expression is of a form that names a non-type template parameter, return the declaration...
MoreSpecializedTrailingPackTieBreakerResult
static TemplateParameter makeTemplateParameter(Decl *D)
Helper function to build a TemplateParameter when we don't know its type statically.
static TemplateDeductionResult CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info, Sema::OriginalCallArg OriginalArg, QualType DeducedA)
Check whether the deduced argument type for a call to a function template matches the actual argument...
static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, QualType &ParamType, QualType &ArgType, Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF, TemplateSpecCandidateSet *FailedTSC=nullptr)
Perform the adjustments to the parameter and argument types described in C++ [temp....
static TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, QualType ParamType, QualType ArgType, Expr::Classification ArgClassification, Expr *Arg, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< Sema::OriginalCallArg > &OriginalCallArgs, bool DecomposedParam, unsigned ArgIdx, unsigned TDF, TemplateSpecCandidateSet *FailedTSC=nullptr)
Perform template argument deduction per [temp.deduct.call] for a single parameter / argument pair.
static bool isAtLeastAsSpecializedAs(Sema &S, SourceLocation Loc, FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, TemplatePartialOrderingContext TPOC, ArrayRef< QualType > Args1, ArrayRef< QualType > Args2, bool Args1Offset)
Determine whether the function template FT1 is at least as specialized as FT2.
static QualType GetImplicitObjectParameterType(ASTContext &Context, const CXXMethodDecl *Method, QualType RawType, bool IsOtherRvr)
static TemplateDeductionResult DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType, InitListExpr *ILE, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< Sema::OriginalCallArg > &OriginalCallArgs, unsigned ArgIdx, unsigned TDF)
Attempt template argument deduction from an initializer list deemed to be an argument in a function c...
static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD)
Get the index of the first template parameter that was originally from the innermost template-paramet...
static TemplateDeductionResult CheckDeducedTemplateArgumentList(Sema &S, TemplateDecl *Template, ArrayRef< TemplateArgumentLoc > Ps, ArrayRef< TemplateArgument > As, const MultiLevelTemplateArgumentList &MLTAL, TemplateDeductionInfo &Info)
PackFold
What directions packs are allowed to match non-packs.
static QualType getTypeOfTemplateArgumentValue(TemplateDeductionInfo &Info, const TemplateArgument &A)
C++26 [temp.deduct.type]p13: When the value of the argument corresponding to a constant template para...
static TemplateDeductionResult ConvertDeducedTemplateArguments(Sema &S, NamedDecl *Template, TemplateParameterList *TemplateParams, bool IsDeduced, SmallVectorImpl< DeducedTemplateArgument > &Deduced, TemplateDeductionInfo &Info, Sema::CheckTemplateArgumentInfo &CTAI, LocalInstantiationScope *CurrentInstantiationScope, unsigned NumAlreadyConverted, bool *IsIncomplete)
static QualType ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams, Expr *Arg, QualType ParamType, bool ParamWasReference, TemplateSpecCandidateSet *FailedTSC=nullptr)
Apply the deduction rules for overload sets.
static bool IsPossiblyOpaquelyQualifiedType(QualType T)
Determines whether the given type is an opaque type that might be more qualified when instantiated.
static TemplateDeductionResult CheckDeducedArgumentConstraints(Sema &S, NamedDecl *Template, ArrayRef< TemplateArgument > SugaredDeducedArgs, ArrayRef< TemplateArgument > CanonicalDeducedArgs, TemplateDeductionInfo &Info)
static const TemplateSpecializationType * getLastTemplateSpecType(QualType QT)
Deduce the template arguments by comparing the template parameter type (which is a template-id) with ...
static TemplateDeductionResult instantiateExplicitSpecifierDeferred(Sema &S, FunctionDecl *Specialization, const MultiLevelTemplateArgumentList &SubstArgs, TemplateDeductionInfo &Info, FunctionTemplateDecl *FunctionTemplate, ArrayRef< TemplateArgument > DeducedArgs)
static bool CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type, AutoTypeLoc TypeLoc, QualType Deduced)
static TemplateDeductionResult DeduceNonTypeTemplateArgument(Sema &S, TemplateParameterList *TemplateParams, const NonTypeOrVarTemplateParmDecl NTTP, const DeducedTemplateArgument &NewDeduced, QualType ValueType, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
Deduce the value of the given non-type template parameter as the given deduced template argument.
static bool IsPossiblyOpaquelyQualifiedTypeInternal(const Type *T)
static bool hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate, QualType T)
static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex)
Determine whether a type denotes a forwarding reference.
static TemplateDeductionResult FinishTemplateArgumentDeduction(Sema &S, NamedDecl *Entity, TemplateParameterList *EntityTPL, TemplateDecl *Template, bool PartialOrdering, ArrayRef< TemplateArgumentLoc > Ps, ArrayRef< TemplateArgument > As, SmallVectorImpl< DeducedTemplateArgument > &Deduced, TemplateDeductionInfo &Info, bool CopyDeducedArgs)
Complete template argument deduction.
static bool isParameterPack(Expr *PackExpression)
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TemplateNameKind enum.
Defines the clang::TypeLoc interface and its subclasses.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
const TemplateTemplateParmDecl * getTemplate() const
const NonTypeTemplateParmDecl * getNTTP() const
NonTypeOrVarTemplateParmDecl(const NamedDecl *Template)
TemplateParameter asTemplateParam() const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
unsigned getIntWidth(QualType T) const
QualType getAutoType(DeducedKind DK, QualType DeducedAsType, AutoTypeKeyword Keyword, TemplateName TypeConstraintConcept=TemplateName(), ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
CanQualType NullPtrTy
const LangOptions & getLangOpts() const
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
LangAS getDefaultOpenCLPointeeAddrSpace()
Returns default address space based on OpenCL version and enabled features.
CanQualType OverloadTy
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedIntTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y, bool IgnoreDeduced=false) const
Determine whether the given template names refer to the same template.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isSameTemplateArgument(const TemplateArgument &Arg1, const TemplateArgument &Arg2) const
Determine whether the given template arguments Arg1 and Arg2 are equivalent.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
TemplateName getDeducedTemplateName(TemplateName Underlying, DefaultArguments DefaultArgs) const
Represents a TemplateName which had some of its default arguments deduced.
QualType getDeducedTemplateSpecializationType(DeducedKind DK, QualType DeducedAsType, ElaboratedTypeKeyword Keyword, TemplateName Template) const
C++17 deduced class template specialization type.
const DependentSizedArrayType * getAsDependentSizedArrayType(QualType T) const
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
TypeLoc getValueLoc() const
Definition TypeLoc.h:2784
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8538
Pointer to a block type.
Definition TypeBase.h:3654
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2994
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3030
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2719
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition DeclCXX.h:2346
bool isStatic() const
Definition DeclCXX.cpp:2417
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:773
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
base_class_range bases()
Definition DeclCXX.h:609
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1744
Declaration of a class template.
CanQualType getCanonicalInjectedSpecializationType(const ASTContext &Ctx) const
Retrieve the canonical template specialization type of the injected-class-name for this class templat...
CanQualType getCanonicalInjectedSpecializationType(const ASTContext &Ctx) const
Retrieves the canonical injected specialization type for this partial specialization.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3363
Declaration of a C++20 concept.
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4623
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4645
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4642
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Represents an opaque OpenCL cooperative matrix type.
Definition TypeBase.h:4718
QualType getElementType() const
Returns the element type.
Definition TypeBase.h:4743
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2110
ValueDecl * getDecl()
Definition Expr.h:1383
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition DeclBase.cpp:285
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isInvalidDecl() const
Definition DeclBase.h:597
SourceLocation getLocation() const
Definition DeclBase.h:448
DeclContext * getDeclContext()
Definition DeclBase.h:457
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
Kind getKind() const
Definition DeclBase.h:451
Captures a template argument whose value has been deduced via c++ template argument deduction.
Definition Template.h:339
void setDeducedFromArrayBound(bool Deduced)
Specify whether the given non-type template argument was deduced from an array bound.
Definition Template.h:366
bool wasDeducedFromArrayBound() const
For a non-type template argument, determine whether the template argument was deduced from an array b...
Definition Template.h:362
SourceLocation getElaboratedKeywordLoc() const
Definition TypeLoc.h:2632
NestedNameSpecifierLoc getQualifierLoc() const
Definition TypeLoc.h:2644
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4160
QualType getPointeeType() const
Definition TypeBase.h:4172
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4200
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4816
TemplateTemplateParmDecl * getParameter() const
Definition ExprCXX.h:3510
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4458
virtual bool TraverseTemplateName(TemplateName Template, bool TraverseQualifier=true)
virtual bool TraverseType(QualType T, bool TraverseQualifier=true)
RAII object that enters a new expression evaluation context.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1949
bool isInvalid() const
Determine if the explicit specifier is invalid.
Definition DeclCXX.h:1978
const Expr * getExpr() const
Definition DeclCXX.h:1958
The return type of classify().
Definition Expr.h:341
bool isLValue() const
Definition Expr.h:392
This represents one expression.
Definition Expr.h:114
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition Expr.h:146
ExtVectorType - Extended vector type.
Definition TypeBase.h:4498
Stores a list of template parameters and the associated requires-clause (if any) for a TemplateDecl a...
Declaration of a friend template.
Represents a function declaration or definition.
Definition Decl.h:2082
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2974
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4283
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4271
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3946
QualType getReturnType() const
Definition Decl.h:3022
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2947
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition Decl.cpp:4342
void getAssociatedConstraints(SmallVectorImpl< AssociatedConstraint > &ACs) const
Get the associated-constraints of this function declaration.
Definition Decl.h:2925
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4407
bool isImmediateEscalating() const
Definition Decl.cpp:3387
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4208
size_t param_size() const
Definition Decl.h:2963
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5650
param_type_iterator param_type_begin() const
Definition TypeBase.h:6094
const ExtParameterInfo * getExtParameterInfosOrNull() const
Return a pointer to the beginning of the array of extra parameter information, if present,...
Definition TypeBase.h:6132
unsigned getNumParams() const
Definition TypeBase.h:5928
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition TypeBase.h:6070
Qualifiers getMethodQuals() const
Definition TypeBase.h:6076
QualType getParamType(unsigned i) const
Definition TypeBase.h:5930
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5963
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:6054
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5939
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition TypeBase.h:6015
param_type_iterator param_type_end() const
Definition TypeBase.h:6098
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5935
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition TypeBase.h:6084
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4846
QualType getReturnType() const
Definition TypeBase.h:5186
Describes an C or C++ initializer list.
Definition Expr.h:5377
unsigned getNumInits() const
Definition Expr.h:5410
unsigned getNumInitsWithEmbedExpanded() const
getNumInits but if the list has an EmbedExpr inside includes full length of embedded data.
Definition Expr.h:5414
ArrayRef< Expr * > inits() const
Definition Expr.h:5441
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3716
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:377
NamedDecl * getPartiallySubstitutedPack(const TemplateArgument **ExplicitArgs=nullptr, unsigned *NumExplicitArgs=nullptr) const
Retrieve the partially-substitued template parameter pack.
void ResetPartiallySubstitutedPack()
Reset the partially-substituted pack when it is no longer of interest.
Definition Template.h:566
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4568
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4587
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3752
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3784
QualType getPointeeType() const
Definition TypeBase.h:3770
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition Template.h:218
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:272
void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final=false)
Replaces the current 'innermost' level with the provided argument list.
Definition Template.h:245
This represents a decl that may have a name.
Definition Decl.h:276
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:489
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
Class that aids in the construction of nested-name-specifiers along with source-location information ...
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Represents a pointer to an Objective C object.
Definition TypeBase.h:8321
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition ExprCXX.h:3143
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3295
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3204
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3256
decls_iterator decls_begin() const
Definition ExprCXX.h:3236
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3325
decls_iterator decls_end() const
Definition ExprCXX.h:3239
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4417
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:280
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3404
QualType getPointeeType() const
Definition TypeBase.h:3414
A (possibly-)qualified type.
Definition TypeBase.h:938
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8769
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8680
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8806
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8720
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8865
QualType getCanonicalType() const
Definition TypeBase.h:8732
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8774
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1853
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8726
Represents a template name as written in source code.
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
unsigned getCVRQualifiers() const
Definition TypeBase.h:489
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:496
GC getObjCGCAttr() const
Definition TypeBase.h:520
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
void removeObjCLifetime()
Definition TypeBase.h:552
bool isStrictSupersetOf(Qualifiers Other) const
Determine whether this set of qualifiers is a strict superset of another set of qualifiers,...
Definition Type.cpp:57
bool hasConst() const
Definition TypeBase.h:458
bool hasNonTrivialObjCLifetime() const
True if the lifetime is neither None or ExplicitNone.
Definition TypeBase.h:560
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:728
bool hasAddressSpace() const
Definition TypeBase.h:571
void removeObjCGCAttr()
Definition TypeBase.h:524
void removeAddressSpace()
Definition TypeBase.h:597
bool hasObjCGCAttr() const
Definition TypeBase.h:519
void setCVRQualifiers(unsigned mask)
Definition TypeBase.h:492
bool hasObjCLifetime() const
Definition TypeBase.h:545
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
Qualifiers withoutObjCLifetime() const
Definition TypeBase.h:534
LangAS getAddressSpace() const
Definition TypeBase.h:572
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:549
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3734
ArrayRef< TemplateArgument > getInjectedTemplateArgs(const ASTContext &Context) const
Retrieve the "injected" template arguments that correspond to the template parameters of this templat...
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3679
QualType getPointeeType() const
Definition TypeBase.h:3701
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
RAII object used to change the argument pack substitution index within a Sema object.
Definition Sema.h:14013
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8720
A RAII object to temporarily push a declaration context.
Definition Sema.h:3683
A helper class for building up ExtParameterInfos.
Definition Sema.h:13382
const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams)
Return a pointer (suitable for setting in an ExtProtoInfo) to the ExtParameterInfo array we've built ...
Definition Sema.h:13401
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12797
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12831
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13411
TemplateDeductionResult DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType, sema::TemplateDeductionInfo &Info)
Deduce the template arguments of the given template from FromType.
QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement)
Completely replace the auto in TypeWithAuto by Replacement.
SemaCUDA & CUDA()
Definition Sema.h:1518
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:7159
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc)
Looks for the std::initializer_list template and instantiates it with Element, or emits an error if i...
TemplateDeductionResult FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl< OriginalCallArg > const *OriginalCallArgs, bool PartialOverloading, bool PartialOrdering, bool ForOverloadSetAddressResolution, llvm::function_ref< bool(bool)> CheckNonDependent=[](bool) { return false;})
Finish template argument deduction for a function template, checking the deduced template arguments f...
@ CTAK_DeducedFromArrayBound
The template argument was deduced from an array bound via template argument deduction.
Definition Sema.h:12319
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12311
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12315
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition Sema.h:1339
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
void MarkUsedTemplateParametersForSubsumptionParameterMapping(const Expr *E, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are named in a given expression.
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
ASTContext & getASTContext() const
Definition Sema.h:935
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:773
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg, const DefaultArguments &DefaultArgs, SourceLocation ArgLoc, bool PartialOrdering, bool *StrictPackMatch)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1243
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
bool CheckConstraintSatisfaction(ConstrainedDeclOrNestedRequirement Entity, ArrayRef< AssociatedConstraint > AssociatedConstraints, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction, const ConceptReference *TopLevelConceptId=nullptr, Expr **ConvertedExpr=nullptr)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12515
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, CheckTemplateArgumentInfo &CTAI, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg)
Compare types for equality with respect to possibly compatible function types (noreturn adjustment,...
const LangOptions & getLangOpts() const
Definition Sema.h:928
UnsignedOrNone getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs)
Determine the number of arguments in the given pack expansion type.
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
ExplicitSpecifier instantiateExplicitSpecifier(const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES)
TemplateDeductionResult SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< QualType > &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info)
Substitute the explicitly-provided template arguments into the given function template according to C...
FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult)
Given an expression that refers to an overloaded function, try to resolve that function to a single f...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1491
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition Sema.h:12868
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8449
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr, bool ForTypeDeduction=false)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
QualType getDecltypeForExpr(Expr *E)
getDecltypeForExpr - Given an expr, will return the decltype for that expression, according to the ru...
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl * > Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl * > *OutParams, ExtParameterInfoBuilder &ParamInfos, const QualType *OldParamTypes=nullptr, bool EvaluateConstraints=true, const FunctionDecl *Fn=nullptr, LateInstantiatedAttrVec *ParamAttrs=nullptr)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
TypeSourceInfo * ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraints=true)
bool isSFINAEContext() const
Definition Sema.h:14051
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15891
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are used in a given expression.
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6970
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6939
QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, CallingConv CC)
Get the return type to use for a lambda's conversion function(s) to function pointer type,...
static QualType getTypeOfConstantTemplateParameter(const TemplateArgument &Arg)
Determine the declared type of the constant template parameter that Arg names, if any.
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
TypeSourceInfo * SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
bool IsAtLeastAsConstrained(const NamedDecl *D1, MutableArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, MutableArrayRef< AssociatedConstraint > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init)
TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, SourceLocation Location)
Get a template argument mapping the given template parameter to itself, e.g.
bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD, SourceLocation Loc)
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation, FunctionDecl *Decl, ArrayRef< TemplateArgument > TemplateArgs, ConstraintSatisfaction &Satisfaction)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:642
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6640
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false, bool PartialOverloading=false)
Returns the more specialized function template according to the rules of function template partial or...
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:13254
NamedDecl * getPack() const
Retrieve the parameter pack.
Definition ExprCXX.h:4563
Encodes a location in the source.
A trivial tuple used to represent a source range.
bool isInvalid() const
SourceLocation getEnd() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
A convenient class for passing around template argument information.
void addArgument(const TemplateArgumentLoc &Loc)
A template argument list.
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Location wrapper for a TemplateArgument.
const TemplateArgument & getArgument() const
Represents a template argument.
QualType getParamTypeForDecl() const
Expr * getAsExpr() const
Retrieve the template argument as an expression.
pack_iterator pack_end() const
Iterator referencing one past the last argument of a template argument pack.
const TemplateArgument * pack_iterator
Iterator that traverses the elements of a template argument pack.
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
Used to insert TemplateArguments into FoldingSets.
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
static TemplateArgument getEmptyPack()
unsigned pack_size() const
The number of template arguments in the given template argument pack.
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
The base class of all kinds of template declarations (e.g., class, function, etc.).
void getAssociatedConstraints(llvm::SmallVectorImpl< AssociatedConstraint > &AC) const
Get the total constraint-expression associated with this template, including constraint-expressions d...
bool isTypeAlias() const
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
ArrayRef< TemplateArgument > getInjectedTemplateArgs(const ASTContext &Context)
Get the template argument list of the template parameter list.
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
void getAssociatedConstraints(llvm::SmallVectorImpl< AssociatedConstraint > &AC) const
All associated constraints derived from this template parameter list, including the requires clause a...
ArrayRef< NamedDecl * > asArray()
SourceLocation getTemplateLoc() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateNameKind templateParameterKind() const
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
const Type * getTypeForDecl() const
Definition Decl.h:3719
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void reserve(size_t Requested)
Ensures that this buffer has at least as much capacity as described.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
SourceRange getLocalSourceRange() const
Get the local source range.
Definition TypeLoc.h:160
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition TypeLoc.h:165
void copy(TypeLoc other)
Copies the other type loc into this one.
Definition TypeLoc.cpp:169
A container of type source information.
Definition TypeBase.h:8651
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8662
SourceLocation getNameLoc() const
Definition TypeLoc.h:547
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9306
const TemplateSpecializationType * getAsNonAliasTemplateSpecializationType() const
Look through sugar for an instance of TemplateSpecializationType which is not a type alias,...
Definition Type.cpp:2104
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition TypeBase.h:9282
bool isRValueReferenceType() const
Definition TypeBase.h:8949
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isArrayType() const
Definition TypeBase.h:9016
bool isFunctionPointerType() const
Definition TypeBase.h:8984
bool isPointerType() const
Definition TypeBase.h:8917
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9604
bool isReferenceType() const
Definition TypeBase.h:8941
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2981
bool isLValueReferenceType() const
Definition TypeBase.h:8945
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2864
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3201
bool isMemberPointerType() const
Definition TypeBase.h:8998
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5657
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9453
bool isFunctionType() const
Definition TypeBase.h:8913
bool isMemberFunctionPointerType() const
Definition TypeBase.h:9002
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3003
bool isAnyPointerType() const
Definition TypeBase.h:8925
TypeClass getTypeClass() const
Definition TypeBase.h:2449
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9537
bool isRecordType() const
Definition TypeBase.h:9044
The iterator over UnresolvedSets.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
QualType getType() const
Definition Value.cpp:237
Represents a variable declaration or definition.
Definition Decl.h:934
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1615
Declaration of a variable template.
VarTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this template.
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the variable template specialization.
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
Represents a GCC generic vector type.
Definition TypeBase.h:4399
Provides information about an attempted template argument deduction, whose success or failure was des...
void setExplicitArgs(TemplateArgumentList *NewDeducedSugared, TemplateArgumentList *NewDeducedCanonical)
Provide an initial template argument list that contains the explicitly-specified arguments.
TemplateArgumentList * takeCanonical()
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
SourceLocation getLocation() const
Returns the location at which template argument is occurring.
void clearSFINAEDiagnostic()
Discard any SFINAE diagnostics.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
diag_iterator diag_end() const
Returns an iterator at the end of the sequence of suppressed diagnostics.
void reset(TemplateArgumentList *NewDeducedSugared, TemplateArgumentList *NewDeducedCanonical)
Provide a new template argument list that contains the results of template argument deduction.
unsigned getDeducedDepth() const
The depth of template parameters for which deduction is being performed.
diag_iterator diag_begin() const
Returns an iterator at the beginning of the sequence of suppressed diagnostics.
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
__inline void unsigned int _2
Top level wrappers for InstallAPI frontend operations.
@ OO_None
Not an overloaded operator.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ GNUAutoType
__auto_type (GNU extension)
Definition TypeBase.h:1846
bool isTargetAddressSpace(LangAS AS)
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
@ Both
Look for allocation functions in both the global scope and in the scope of the allocated class.
Definition Sema.h:793
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1801
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1807
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
NamedDecl * getAsNamedDecl(TemplateParameter P)
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ AS_public
Definition Specifiers.h:128
UnsignedOrNone getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
unsigned toTargetAddressSpace(LangAS AS)
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:906
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
OptionalUnsigned< unsigned > UnsignedOrNone
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:581
@ Concept
The name was classified as a concept name.
Definition Sema.h:585
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition ASTLambda.h:69
DeducedKind
Definition TypeBase.h:1811
@ Deduced
The normal deduced case.
Definition TypeBase.h:1818
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1813
@ DeducedAsPack
Same as above, but additionally this represents a case where the deduced entity itself is a pack.
Definition TypeBase.h:1834
@ DeducedAsDependent
This is a special case where the initializer is dependent, so we can't deduce a type yet.
Definition TypeBase.h:1828
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
@ TNK_Concept_template
The name refers to a concept.
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
TPOC
The context in which partial ordering of function templates occurs.
Definition Template.h:310
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition Template.h:316
@ TPOC_Other
Partial ordering of function templates in other contexts, e.g., taking the address of a function temp...
Definition Template.h:321
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:312
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1306
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:374
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:424
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:419
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:422
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:395
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:381
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:417
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:426
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:414
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:384
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:378
@ Success
Template argument deduction was successful.
Definition Sema.h:376
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:398
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:387
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:401
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:390
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:411
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:428
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:405
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:408
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:840
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:845
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6269
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ EST_Uninstantiated
not instantiated yet
@ EST_None
no exception specification
TemplateDeductionFlags
Various flags that control template argument deduction.
@ TDF_None
No template argument deduction flags, which indicates the strictest results for template argument ded...
@ TDF_DerivedClass
Within template argument deduction from a function call, we are matching in a case where we can perfo...
@ TDF_TopLevelParameterTypeList
Whether we are performing template argument deduction for parameters and arguments in a top-level tem...
@ TDF_IgnoreQualifiers
Within template argument deduction from a function call, we are matching in a case where we ignore cv...
@ TDF_ParamWithReferenceType
Within template argument deduction from a function call, we are matching with a parameter type for wh...
@ TDF_SkipNonDependent
Allow non-dependent types to differ, e.g., when performing template argument deduction from a functio...
@ TDF_AllowCompatibleFunctionType
Within template argument deduction from overload resolution per C++ [over.over] allow matching functi...
@ TDF_ArgWithReferenceType
Within template argument deduction for a conversion function, we are matching with an argument type f...
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
#define true
Definition stdbool.h:25
A pack that we're currently deducing.
SmallVector< DeducedTemplateArgument, 4 > New
DeducedTemplateArgument Saved
DeducedTemplateArgument DeferredDeduction
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5709
Extra information about a function prototype.
Definition TypeBase.h:5735
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5740
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:12346
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12342
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12335
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12332
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12332
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition Sema.h:13483
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13490
A stack object to be created when performing template instantiation.
Definition Sema.h:13656
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13809
brief A function argument from which we performed template argument
Definition Sema.h:12967
Location information for a TemplateArgument.
TemplateSpecCandidate - This is a generalization of OverloadCandidate which keeps track of template a...
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)