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"
35#include "clang/Basic/LLVM.h"
43#include "clang/Sema/Sema.h"
44#include "clang/Sema/Template.h"
46#include "llvm/ADT/APInt.h"
47#include "llvm/ADT/APSInt.h"
48#include "llvm/ADT/ArrayRef.h"
49#include "llvm/ADT/DenseMap.h"
50#include "llvm/ADT/FoldingSet.h"
51#include "llvm/ADT/SmallBitVector.h"
52#include "llvm/ADT/SmallPtrSet.h"
53#include "llvm/ADT/SmallVector.h"
54#include "llvm/Support/Casting.h"
55#include "llvm/Support/Compiler.h"
56#include "llvm/Support/ErrorHandling.h"
57#include "llvm/Support/SaveAndRestore.h"
58#include <algorithm>
59#include <cassert>
60#include <optional>
61#include <tuple>
62#include <type_traits>
63#include <utility>
64
65namespace clang {
66
67 /// Various flags that control template argument deduction.
68 ///
69 /// These flags can be bitwise-OR'd together.
71 /// No template argument deduction flags, which indicates the
72 /// strictest results for template argument deduction (as used for, e.g.,
73 /// matching class template partial specializations).
75
76 /// Within template argument deduction from a function call, we are
77 /// matching with a parameter type for which the original parameter was
78 /// a reference.
80
81 /// Within template argument deduction from a function call, we
82 /// are matching in a case where we ignore cv-qualifiers.
84
85 /// Within template argument deduction from a function call,
86 /// we are matching in a case where we can perform template argument
87 /// deduction from a template-id of a derived class of the argument type.
89
90 /// Allow non-dependent types to differ, e.g., when performing
91 /// template argument deduction from a function call where conversions
92 /// may apply.
94
95 /// Whether we are performing template argument deduction for
96 /// parameters and arguments in a top-level template argument
98
99 /// Within template argument deduction from overload resolution per
100 /// C++ [over.over] allow matching function types that are compatible in
101 /// terms of noreturn and default calling convention adjustments, or
102 /// similarly matching a declared template specialization against a
103 /// possible template, per C++ [temp.deduct.decl]. In either case, permit
104 /// deduction where the parameter is a function type that can be converted
105 /// to the argument type.
107
108 /// Within template argument deduction for a conversion function, we are
109 /// matching with an argument type for which the original argument was
110 /// a reference.
112 };
113}
114
115using namespace clang;
116using namespace sema;
117
118/// The kind of PartialOrdering we're performing template argument deduction
119/// for (C++11 [temp.deduct.partial]).
121
123 Sema &S, TemplateParameterList *TemplateParams, QualType Param,
126 PartialOrderingKind POK, bool DeducedFromArrayBound,
127 bool *HasDeducedAnyParam);
128
129/// What directions packs are allowed to match non-packs.
131
138 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
139 PackFold PackFold, bool *HasDeducedAnyParam);
140
143 bool OnlyDeduced, unsigned Depth,
144 llvm::SmallBitVector &Used);
145
147 bool OnlyDeduced, unsigned Level,
148 llvm::SmallBitVector &Deduced);
149
150static const Expr *unwrapExpressionForDeduction(const Expr *E) {
151 // If we are within an alias template, the expression may have undergone
152 // any number of parameter substitutions already.
153 while (true) {
154 if (const auto *IC = dyn_cast<ImplicitCastExpr>(E))
155 E = IC->getSubExpr();
156 else if (const auto *CE = dyn_cast<ConstantExpr>(E))
157 E = CE->getSubExpr();
158 else if (const auto *Subst = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
159 E = Subst->getReplacement();
160 else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) {
161 // Look through implicit copy construction from an lvalue of the same type.
162 if (CCE->getParenOrBraceRange().isValid())
163 break;
164 // Note, there could be default arguments.
165 assert(CCE->getNumArgs() >= 1 && "implicit construct expr should have 1 arg");
166 E = CCE->getArg(0);
167 } else
168 break;
169 }
170 return E;
171}
172
174public:
175 NonTypeOrVarTemplateParmDecl(const NamedDecl *Template) : Template(Template) {
176 assert(
177 !Template || isa<NonTypeTemplateParmDecl>(Template) ||
179 (cast<TemplateTemplateParmDecl>(Template)->templateParameterKind() ==
181 cast<TemplateTemplateParmDecl>(Template)->templateParameterKind() ==
183 }
184
186 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
187 return NTTP->getType();
191 }
192
193 unsigned getDepth() const {
194 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
195 return NTTP->getDepth();
196 return getTemplate()->getDepth();
197 }
198
199 unsigned getIndex() const {
200 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
201 return NTTP->getIndex();
202 return getTemplate()->getIndex();
203 }
204
206 return cast<TemplateTemplateParmDecl>(Template);
207 }
208
210 return cast<NonTypeTemplateParmDecl>(Template);
211 }
212
214 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
215 return const_cast<NonTypeTemplateParmDecl *>(NTTP);
216 return const_cast<TemplateTemplateParmDecl *>(getTemplate());
217 }
218
220 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
221 return NTTP->isExpandedParameterPack();
223 }
224
226 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
227 return NTTP->getLocation();
228 return getTemplate()->getLocation();
229 }
230
231 operator bool() const { return Template; }
232
233private:
234 const NamedDecl *Template;
235};
236
237/// If the given expression is of a form that permits the deduction
238/// of a non-type template parameter, return the declaration of that
239/// non-type template parameter.
241getDeducedNTTParameterFromExpr(const Expr *E, unsigned Depth) {
242 // If we are within an alias template, the expression may have undergone
243 // any number of parameter substitutions already.
245 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
246 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
247 if (NTTP->getDepth() == Depth)
248 return NTTP;
249
250 // A pack-index-template-name is not deducible.
251 if (const auto *DTI = dyn_cast<DependentTemplateIdExpr>(E))
252 if (!DTI->getTemplateName().getAsPackIndexingTemplate() &&
253 DTI->getParameter()->getDepth() == Depth)
254 return DTI->getParameter();
255
256 return nullptr;
257}
258
263
264/// Determine whether two declaration pointers refer to the same
265/// declaration.
266static bool isSameDeclaration(Decl *X, Decl *Y) {
267 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
268 X = NX->getUnderlyingDecl();
269 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
270 Y = NY->getUnderlyingDecl();
271
272 return X->getCanonicalDecl() == Y->getCanonicalDecl();
273}
274
275/// Verify that the given, deduced template arguments are compatible.
276///
277/// \returns The deduced template argument, or a NULL template argument if
278/// the deduced template arguments were incompatible.
283 bool AggregateCandidateDeduction = false) {
284 // We have no deduction for one or both of the arguments; they're compatible.
285 if (X.isNull())
286 return Y;
287 if (Y.isNull())
288 return X;
289
290 // If we have two non-type template argument values deduced for the same
291 // parameter, they must both match the type of the parameter, and thus must
292 // match each other's type. As we're only keeping one of them, we must check
293 // for that now. The exception is that if either was deduced from an array
294 // bound, the type is permitted to differ.
295 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
296 QualType XType = X.getNonTypeTemplateArgumentType();
297 if (!XType.isNull()) {
299 if (YType.isNull() || !Context.hasSameType(XType, YType))
301 }
302 }
303
304 switch (X.getKind()) {
306 llvm_unreachable("Non-deduced template arguments handled above");
307
309 // If two template type arguments have the same type, they're compatible.
310 QualType TX = X.getAsType(), TY = Y.getAsType();
311 if (Y.getKind() == TemplateArgument::Type && Context.hasSameType(TX, TY))
312 return DeducedTemplateArgument(Context.getCommonSugaredType(TX, TY),
313 X.wasDeducedFromArrayBound() ||
315
316 // If one of the two arguments was deduced from an array bound, the other
317 // supersedes it.
318 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
319 return X.wasDeducedFromArrayBound() ? Y : X;
320
321 // The arguments are not compatible.
323 }
324
326 // If we deduced a constant in one case and either a dependent expression or
327 // declaration in another case, keep the integral constant.
328 // If both are integral constants with the same value, keep that value.
332 llvm::APSInt::isSameValue(X.getAsIntegral(), Y.getAsIntegral())))
333 return X.wasDeducedFromArrayBound() ? Y : X;
334
335 // All other combinations are incompatible.
337
339 // If we deduced a value and a dependent expression, keep the value.
342 X.structurallyEquals(Y)))
343 return X;
344
345 // All other combinations are incompatible.
347
350 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
351 return X;
352
353 // All other combinations are incompatible.
355
358 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
360 return X;
361
362 // All other combinations are incompatible.
364
367 return checkDeducedTemplateArguments(Context, Y, X);
368
369 // Compare the expressions for equality
370 llvm::FoldingSetNodeID ID1, ID2;
371 X.getAsExpr()->Profile(ID1, Context, true);
372 Y.getAsExpr()->Profile(ID2, Context, true);
373 if (ID1 == ID2)
374 return X.wasDeducedFromArrayBound() ? Y : X;
375
376 // Differing dependent expressions are incompatible.
378 }
379
381 assert(!X.wasDeducedFromArrayBound());
382
383 // If we deduced a declaration and a dependent expression, keep the
384 // declaration.
386 return X;
387
388 // If we deduced a declaration and an integral constant, keep the
389 // integral constant and whichever type did not come from an array
390 // bound.
393 return TemplateArgument(Context, Y.getAsIntegral(),
394 X.getParamTypeForDecl());
395 return Y;
396 }
397
398 // If we deduced two declarations, make sure that they refer to the
399 // same declaration.
401 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
402 return X;
403
404 // All other combinations are incompatible.
406
408 // If we deduced a null pointer and a dependent expression, keep the
409 // null pointer.
411 return TemplateArgument(Context.getCommonSugaredType(
412 X.getNullPtrType(), Y.getAsExpr()->getType()),
413 true);
414
415 // If we deduced a null pointer and an integral constant, keep the
416 // integral constant.
418 return Y;
419
420 // If we deduced two null pointers, they are the same.
422 return TemplateArgument(
423 Context.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
424 true);
425
426 // All other combinations are incompatible.
428
430 if (Y.getKind() != TemplateArgument::Pack ||
431 (!AggregateCandidateDeduction && X.pack_size() != Y.pack_size()))
433
436 XA = X.pack_begin(),
437 XAEnd = X.pack_end(), YA = Y.pack_begin(), YAEnd = Y.pack_end();
438 XA != XAEnd; ++XA) {
439 if (YA != YAEnd) {
441 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
443 if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
445 NewPack.push_back(Merged);
446 ++YA;
447 } else {
448 NewPack.push_back(*XA);
449 }
450 }
451
453 TemplateArgument::CreatePackCopy(Context, NewPack),
454 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
455 }
456 }
457
458 llvm_unreachable("Invalid TemplateArgument Kind!");
459}
460
461/// Deduce the value of the given non-type template parameter
462/// as the given deduced template argument. All non-type template parameter
463/// deduction is funneled through here.
467 const DeducedTemplateArgument &NewDeduced,
468 QualType ValueType, TemplateDeductionInfo &Info,
469 bool PartialOrdering,
471 bool *HasDeducedAnyParam) {
472 assert(NTTP.getDepth() == Info.getDeducedDepth() &&
473 "deducing non-type template argument with wrong depth");
474
476 S.Context, Deduced[NTTP.getIndex()], NewDeduced);
477 if (Result.isNull()) {
478 Info.Param = NTTP.asTemplateParam();
479 Info.FirstArg = Deduced[NTTP.getIndex()];
480 Info.SecondArg = NewDeduced;
482 }
483 Deduced[NTTP.getIndex()] = Result;
484 if (!S.getLangOpts().CPlusPlus17 && !PartialOrdering)
486
487 if (NTTP.isExpandedParameterPack())
488 // FIXME: We may still need to deduce parts of the type here! But we
489 // don't have any way to find which slice of the type to use, and the
490 // type stored on the NTTP itself is nonsense. Perhaps the type of an
491 // expanded NTTP should be a pack expansion type?
493
494 // Get the type of the parameter for deduction. If it's a (dependent) array
495 // or function type, we will not have decayed it yet, so do that now.
496 QualType ParamType = S.Context.getAdjustedParameterType(NTTP.getType());
497 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
498 ParamType = Expansion->getPattern();
499
500 // FIXME: It's not clear how deduction of a parameter of reference type from
501 // an argument should be performed. For now, we just make the argument have
502 // the same kind of reference type as the parameter.
503 if (ParamType->isReferenceType()) {
504 ValueType = ValueType.getNonReferenceType();
505 ValueType = ParamType->isRValueReferenceType()
506 ? S.Context.getRValueReferenceType(ValueType)
507 : S.Context.getLValueReferenceType(ValueType);
508 }
509
511 S, TemplateParams, ParamType, ValueType, Info, Deduced,
515 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound(), HasDeducedAnyParam);
516}
517
518/// Deduce the value of the given non-type template parameter
519/// from the given integral constant.
521 Sema &S, TemplateParameterList *TemplateParams,
522 NonTypeOrVarTemplateParmDecl NTTP, const llvm::APSInt &Value,
523 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
525 bool *HasDeducedAnyParam) {
527 S, TemplateParams, NTTP,
529 DeducedFromArrayBound),
530 ValueType, Info, PartialOrdering, Deduced, HasDeducedAnyParam);
531}
532
533/// Deduce the value of the given non-type template parameter
534/// from the given null pointer template argument type.
538 QualType NullPtrType, TemplateDeductionInfo &Info,
539 bool PartialOrdering,
541 bool *HasDeducedAnyParam) {
544 NTTP.getLocation()),
545 NullPtrType,
546 NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer
547 : CK_NullToPointer)
548 .get();
550 S, TemplateParams, NTTP, TemplateArgument(Value, /*IsCanonical=*/false),
551 Value->getType(), Info, PartialOrdering, Deduced, HasDeducedAnyParam);
552}
553
554/// Deduce the value of the given non-type template parameter
555/// from the given type- or value-dependent expression.
556///
557/// \returns true if deduction succeeded, false otherwise.
563 bool *HasDeducedAnyParam) {
565 S, TemplateParams, NTTP, TemplateArgument(Value, /*IsCanonical=*/false),
566 Value->getType(), Info, PartialOrdering, Deduced, HasDeducedAnyParam);
567}
568
569/// Deduce the value of the given non-type template parameter
570/// from the given declaration.
571///
572/// \returns true if deduction succeeded, false otherwise.
577 bool PartialOrdering,
579 bool *HasDeducedAnyParam) {
582 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info,
583 PartialOrdering, Deduced, HasDeducedAnyParam);
584}
585
587 Sema &S, TemplateParameterList *TemplateParams, TemplateName Param,
591 bool *HasDeducedAnyParam) {
592 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
593 if (!ParamDecl) {
594 // The parameter type is dependent and is not a template template parameter,
595 // so there is nothing that we can deduce.
597 }
598
599 if (auto *TempParam = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
600 // If we're not deducing at this depth, there's nothing to deduce.
601 if (TempParam->getDepth() != Info.getDeducedDepth())
603
604 ArrayRef<NamedDecl *> Params =
605 ParamDecl->getTemplateParameters()->asArray();
606 unsigned StartPos = 0;
607 for (unsigned I = 0, E = std::min(Params.size(), DefaultArguments.size());
608 I < E; ++I) {
609 if (Params[I]->isParameterPack()) {
610 StartPos = DefaultArguments.size();
611 break;
612 }
613 StartPos = I + 1;
614 }
615
616 // Provisional resolution for CWG2398: If Arg names a template
617 // specialization, then we deduce a synthesized template name
618 // based on A, but using the TS's extra arguments, relative to P, as
619 // defaults.
620 DeducedTemplateArgument NewDeduced =
623 Arg, {StartPos, DefaultArguments.drop_front(StartPos)}))
624 : Arg;
625
627 S.Context, Deduced[TempParam->getIndex()], NewDeduced);
628 if (Result.isNull()) {
629 Info.Param = TempParam;
630 Info.FirstArg = Deduced[TempParam->getIndex()];
631 Info.SecondArg = NewDeduced;
633 }
634
635 Deduced[TempParam->getIndex()] = Result;
636 if (HasDeducedAnyParam)
637 *HasDeducedAnyParam = true;
639 }
640
641 // Verify that the two template names are equivalent.
643 Param, Arg, /*IgnoreDeduced=*/DefaultArguments.size() != 0))
645
646 // Mismatch of non-dependent template parameter to argument.
647 Info.FirstArg = TemplateArgument(Param);
648 Info.SecondArg = TemplateArgument(Arg);
650}
651
652/// Deduce the template arguments by comparing the template parameter
653/// type (which is a template-id) with the template argument type.
654///
655/// \param S the Sema
656///
657/// \param TemplateParams the template parameters that we are deducing
658///
659/// \param P the parameter type
660///
661/// \param A the argument type
662///
663/// \param Info information about the template argument deduction itself
664///
665/// \param Deduced the deduced template arguments
666///
667/// \returns the result of template argument deduction so far. Note that a
668/// "success" result means that template argument deduction has not yet failed,
669/// but it may still fail, later, for other reasons.
670
671static const TemplateSpecializationType *getLastTemplateSpecType(QualType QT) {
672 const TemplateSpecializationType *LastTST = nullptr;
673 for (const Type *T = QT.getTypePtr(); /**/; /**/) {
674 const TemplateSpecializationType *TST =
675 T->getAs<TemplateSpecializationType>();
676 if (!TST)
677 return LastTST;
678 if (!TST->isSugared())
679 return TST;
680 LastTST = TST;
681 T = TST->desugar().getTypePtr();
682 }
683}
684
687 const QualType P, QualType A,
690 bool *HasDeducedAnyParam) {
691 TemplateName TNP;
694 const TemplateSpecializationType *TP = ::getLastTemplateSpecType(P);
695 TNP = TP->getTemplateName();
696
697 // No deduction for specializations of dependent template names.
700
701 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
702 // arguments.
703 PResolved =
704 TP->castAsCanonical<TemplateSpecializationType>()->template_arguments();
705 } else {
706 const auto *TT = P->castAs<InjectedClassNameType>();
707 TNP = TT->getTemplateName(S.Context);
708 PResolved = TT->getTemplateArgs(S.Context);
709 }
710
711 // If the parameter is an alias template, there is nothing to deduce.
712 if (const auto *TD = TNP.getAsTemplateDecl(); TD && TD->isTypeAlias())
714 // Pack-producing templates can only be matched after substitution.
717
718 // Check whether the template argument is a dependent template-id.
720 const TemplateSpecializationType *SA = ::getLastTemplateSpecType(A);
721 TemplateName TNA = SA->getTemplateName();
722
723 // If the argument is an alias template, there is nothing to deduce.
724 if (const auto *TD = TNA.getAsTemplateDecl(); TD && TD->isTypeAlias())
726
727 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
728 // arguments.
730 SA->getCanonicalTypeInternal()
731 ->castAs<TemplateSpecializationType>()
732 ->template_arguments();
733
734 // Perform template argument deduction for the template name.
735 if (auto Result = DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
736 /*DefaultArguments=*/AResolved,
738 HasDeducedAnyParam);
740 return Result;
741
742 // Perform template argument deduction on each template
743 // argument. Ignore any missing/extra arguments, since they could be
744 // filled in by default arguments.
746 S, TemplateParams, PResolved, AResolved, Info, Deduced,
747 /*NumberOfArgumentsMustMatch=*/false, PartialOrdering,
748 PackFold::ParameterToArgument, HasDeducedAnyParam);
749 }
750
751 // If the argument type is a class template specialization, we
752 // perform template argument deduction using its template
753 // arguments.
754 const auto *TA = A->getAs<TagType>();
755 TemplateName TNA;
756 if (TA) {
757 // FIXME: Can't use the template arguments from this TST, as they are not
758 // resolved.
759 if (const auto *TST = A->getAsNonAliasTemplateSpecializationType())
760 TNA = TST->getTemplateName();
761 else
762 TNA = TA->getTemplateName(S.Context);
763 }
764 if (TNA.isNull()) {
765 Info.FirstArg = TemplateArgument(P);
766 Info.SecondArg = TemplateArgument(A);
768 }
769
770 ArrayRef<TemplateArgument> AResolved = TA->getTemplateArgs(S.Context);
771 // Perform template argument deduction for the template name.
772 if (auto Result =
773 DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
774 /*DefaultArguments=*/AResolved,
775 PartialOrdering, Deduced, HasDeducedAnyParam);
777 return Result;
778
779 // Perform template argument deduction for the template arguments.
781 S, TemplateParams, PResolved, AResolved, Info, Deduced,
782 /*NumberOfArgumentsMustMatch=*/true, PartialOrdering,
783 PackFold::ParameterToArgument, HasDeducedAnyParam);
784}
785
787 assert(T->isCanonicalUnqualified());
788
789 switch (T->getTypeClass()) {
790 case Type::TypeOfExpr:
791 case Type::TypeOf:
792 case Type::DependentName:
793 case Type::Decltype:
794 case Type::PackIndexing:
795 case Type::UnresolvedUsing:
796 case Type::TemplateTypeParm:
797 case Type::Auto:
798 return true;
799
800 case Type::ConstantArray:
801 case Type::IncompleteArray:
802 case Type::VariableArray:
803 case Type::DependentSizedArray:
805 cast<ArrayType>(T)->getElementType().getTypePtr());
806
807 default:
808 return false;
809 }
810}
811
812/// Determines whether the given type is an opaque type that
813/// might be more qualified when instantiated.
816 T->getCanonicalTypeInternal().getTypePtr());
817}
818
819/// Helper function to build a TemplateParameter when we don't
820/// know its type statically.
822 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
823 return TemplateParameter(TTP);
824 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
825 return TemplateParameter(NTTP);
826
828}
829
830/// A pack that we're currently deducing.
832 // The index of the pack.
833 unsigned Index;
834
835 // The old value of the pack before we started deducing it.
837
838 // A deferred value of this pack from an inner deduction, that couldn't be
839 // deduced because this deduction hadn't happened yet.
841
842 // The new value of the pack.
844
845 // The outer deduction for this pack, if any.
846 DeducedPack *Outer = nullptr;
847
848 DeducedPack(unsigned Index) : Index(Index) {}
849};
850
851namespace {
852
853/// A scope in which we're performing pack deduction.
854class PackDeductionScope {
855public:
856 /// Prepare to deduce the packs named within Pattern.
857 /// \param FinishingDeduction Don't attempt to deduce the pack. Useful when
858 /// just checking a previous deduction of the pack.
859 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
862 bool DeducePackIfNotAlreadyDeduced = false,
863 bool FinishingDeduction = false)
864 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info),
865 DeducePackIfNotAlreadyDeduced(DeducePackIfNotAlreadyDeduced),
866 FinishingDeduction(FinishingDeduction) {
867 unsigned NumNamedPacks = addPacks(Pattern);
868 finishConstruction(NumNamedPacks);
869 }
870
871 /// Prepare to directly deduce arguments of the parameter with index \p Index.
872 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
873 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
874 TemplateDeductionInfo &Info, unsigned Index)
875 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
876 addPack(Index);
877 finishConstruction(1);
878 }
879
880private:
881 void addPack(unsigned Index) {
882 // Save the deduced template argument for the parameter pack expanded
883 // by this pack expansion, then clear out the deduction.
884 DeducedFromEarlierParameter = !Deduced[Index].isNull();
885 DeducedPack Pack(Index);
886 if (!FinishingDeduction) {
887 Pack.Saved = Deduced[Index];
888 Deduced[Index] = TemplateArgument();
889 }
890
891 // FIXME: What if we encounter multiple packs with different numbers of
892 // pre-expanded expansions? (This should already have been diagnosed
893 // during substitution.)
894 if (UnsignedOrNone ExpandedPackExpansions =
895 getExpandedPackSize(TemplateParams->getParam(Index)))
896 FixedNumExpansions = ExpandedPackExpansions;
897
898 Packs.push_back(Pack);
899 }
900
901 unsigned addPacks(TemplateArgument Pattern) {
902 // Compute the set of template parameter indices that correspond to
903 // parameter packs expanded by the pack expansion.
904 llvm::SmallBitVector SawIndices(TemplateParams->size());
905 llvm::SmallVector<TemplateArgument, 4> ExtraDeductions;
906
907 auto AddPack = [&](unsigned Index) {
908 if (SawIndices[Index])
909 return;
910 SawIndices[Index] = true;
911 addPack(Index);
912
913 // Deducing a parameter pack that is a pack expansion also constrains the
914 // packs appearing in that parameter to have the same deduced arity. Also,
915 // in C++17 onwards, deducing a non-type template parameter deduces its
916 // type, so we need to collect the pending deduced values for those packs.
917 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
918 TemplateParams->getParam(Index))) {
919 if (!NTTP->isExpandedParameterPack())
920 // FIXME: CWG2982 suggests a type-constraint forms a non-deduced
921 // context, however it is not yet resolved.
922 if (auto *Expansion = dyn_cast<PackExpansionType>(
923 S.Context.getUnconstrainedType(NTTP->getType())))
924 ExtraDeductions.push_back(Expansion->getPattern());
925 }
926 // FIXME: Also collect the unexpanded packs in any type and template
927 // parameter packs that are pack expansions.
928 };
929
930 auto Collect = [&](TemplateArgument Pattern) {
931 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
932 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
933 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
934 unsigned Depth, Index;
935
936 // Function parameter packs cannot be deduced.
937 if (isa_and_present<ParmVarDecl>(
938 dyn_cast<NamedDecl *>(Unexpanded[I].first)))
939 continue;
940 if (auto DI = getDepthAndIndex(Unexpanded[I]))
941 std::tie(Depth, Index) = *DI;
942 else
943 continue;
944
945 if (Depth == Info.getDeducedDepth())
946 AddPack(Index);
947 }
948 };
949
950 // Look for unexpanded packs in the pattern.
951 Collect(Pattern);
952
953 unsigned NumNamedPacks = Packs.size();
954
955 // Also look for unexpanded packs that are indirectly deduced by deducing
956 // the sizes of the packs in this pattern.
957 while (!ExtraDeductions.empty())
958 Collect(ExtraDeductions.pop_back_val());
959
960 return NumNamedPacks;
961 }
962
963 void finishConstruction(unsigned NumNamedPacks) {
964 // Dig out the partially-substituted pack, if there is one.
965 const TemplateArgument *PartialPackArgs = nullptr;
966 unsigned NumPartialPackArgs = 0;
967 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
968 if (auto *Scope = S.CurrentInstantiationScope)
969 if (auto *Partial = Scope->getPartiallySubstitutedPack(
970 &PartialPackArgs, &NumPartialPackArgs))
971 PartialPackDepthIndex = getDepthAndIndex(Partial);
972
973 // This pack expansion will have been partially or fully expanded if
974 // it only names explicitly-specified parameter packs (including the
975 // partially-substituted one, if any).
976 bool IsExpanded = true;
977 for (unsigned I = 0; I != NumNamedPacks; ++I) {
978 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
979 IsExpanded = false;
980 IsPartiallyExpanded = false;
981 break;
982 }
983 if (PartialPackDepthIndex ==
984 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
985 IsPartiallyExpanded = true;
986 }
987 }
988
989 // Skip over the pack elements that were expanded into separate arguments.
990 // If we partially expanded, this is the number of partial arguments.
991 // FIXME: `&& FixedNumExpansions` is a workaround for UB described in
992 // https://github.com/llvm/llvm-project/issues/100095
993 if (IsPartiallyExpanded)
994 PackElements += NumPartialPackArgs;
995 else if (IsExpanded && FixedNumExpansions)
996 PackElements += *FixedNumExpansions;
997
998 for (auto &Pack : Packs) {
999 if (Info.PendingDeducedPacks.size() > Pack.Index)
1000 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
1001 else
1002 Info.PendingDeducedPacks.resize(Pack.Index + 1);
1003 Info.PendingDeducedPacks[Pack.Index] = &Pack;
1004
1005 if (PartialPackDepthIndex ==
1006 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
1007 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
1008 }
1009 }
1010 }
1011
1012public:
1013 ~PackDeductionScope() {
1014 for (auto &Pack : Packs)
1015 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
1016 }
1017
1018 // Return the size of the saved packs if all of them has the same size.
1019 UnsignedOrNone getSavedPackSizeIfAllEqual() const {
1020 unsigned PackSize = Packs[0].Saved.pack_size();
1021
1022 if (std::all_of(Packs.begin() + 1, Packs.end(), [&PackSize](const auto &P) {
1023 return P.Saved.pack_size() == PackSize;
1024 }))
1025 return PackSize;
1026 return std::nullopt;
1027 }
1028
1029 /// Determine whether this pack has already been deduced from a previous
1030 /// argument.
1031 bool isDeducedFromEarlierParameter() const {
1032 return DeducedFromEarlierParameter;
1033 }
1034
1035 /// Determine whether this pack has already been partially expanded into a
1036 /// sequence of (prior) function parameters / template arguments.
1037 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
1038
1039 /// Determine whether this pack expansion scope has a known, fixed arity.
1040 /// This happens if it involves a pack from an outer template that has
1041 /// (notionally) already been expanded.
1042 bool hasFixedArity() { return static_cast<bool>(FixedNumExpansions); }
1043
1044 /// Determine whether the next element of the argument is still part of this
1045 /// pack. This is the case unless the pack is already expanded to a fixed
1046 /// length.
1047 bool hasNextElement() {
1048 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
1049 }
1050
1051 /// Move to deducing the next element in each pack that is being deduced.
1052 void nextPackElement() {
1053 // Capture the deduced template arguments for each parameter pack expanded
1054 // by this pack expansion, add them to the list of arguments we've deduced
1055 // for that pack, then clear out the deduced argument.
1056 if (!FinishingDeduction) {
1057 for (auto &Pack : Packs) {
1058 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
1059 if (!Pack.New.empty() || !DeducedArg.isNull()) {
1060 while (Pack.New.size() < PackElements)
1061 Pack.New.push_back(DeducedTemplateArgument());
1062 if (Pack.New.size() == PackElements)
1063 Pack.New.push_back(DeducedArg);
1064 else
1065 Pack.New[PackElements] = DeducedArg;
1066 DeducedArg = Pack.New.size() > PackElements + 1
1067 ? Pack.New[PackElements + 1]
1068 : DeducedTemplateArgument();
1069 }
1070 }
1071 }
1072 ++PackElements;
1073 }
1074
1075 /// Finish template argument deduction for a set of argument packs,
1076 /// producing the argument packs and checking for consistency with prior
1077 /// deductions.
1078 TemplateDeductionResult finish() {
1079 if (FinishingDeduction)
1080 return TemplateDeductionResult::Success;
1081 // Build argument packs for each of the parameter packs expanded by this
1082 // pack expansion.
1083 for (auto &Pack : Packs) {
1084 // Put back the old value for this pack.
1085 if (!FinishingDeduction)
1086 Deduced[Pack.Index] = Pack.Saved;
1087
1088 // Always make sure the size of this pack is correct, even if we didn't
1089 // deduce any values for it.
1090 //
1091 // FIXME: This isn't required by the normative wording, but substitution
1092 // and post-substitution checking will always fail if the arity of any
1093 // pack is not equal to the number of elements we processed. (Either that
1094 // or something else has gone *very* wrong.) We're permitted to skip any
1095 // hard errors from those follow-on steps by the intent (but not the
1096 // wording) of C++ [temp.inst]p8:
1097 //
1098 // If the function selected by overload resolution can be determined
1099 // without instantiating a class template definition, it is unspecified
1100 // whether that instantiation actually takes place
1101 Pack.New.resize(PackElements);
1102
1103 // Build or find a new value for this pack.
1104 DeducedTemplateArgument NewPack;
1105 if (Pack.New.empty()) {
1106 // If we deduced an empty argument pack, create it now.
1107 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
1108 } else {
1109 TemplateArgument *ArgumentPack =
1110 new (S.Context) TemplateArgument[Pack.New.size()];
1111 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
1112 NewPack = DeducedTemplateArgument(
1113 TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())),
1114 // FIXME: This is wrong, it's possible that some pack elements are
1115 // deduced from an array bound and others are not:
1116 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
1117 // g({1, 2, 3}, {{}, {}});
1118 // ... should deduce T = {int, size_t (from array bound)}.
1119 Pack.New[0].wasDeducedFromArrayBound());
1120 }
1121
1122 // Pick where we're going to put the merged pack.
1123 DeducedTemplateArgument *Loc;
1124 if (Pack.Outer) {
1125 if (Pack.Outer->DeferredDeduction.isNull()) {
1126 // Defer checking this pack until we have a complete pack to compare
1127 // it against.
1128 Pack.Outer->DeferredDeduction = NewPack;
1129 continue;
1130 }
1131 Loc = &Pack.Outer->DeferredDeduction;
1132 } else {
1133 Loc = &Deduced[Pack.Index];
1134 }
1135
1136 // Check the new pack matches any previous value.
1137 DeducedTemplateArgument OldPack = *Loc;
1138 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
1139 S.Context, OldPack, NewPack, DeducePackIfNotAlreadyDeduced);
1140
1141 Info.AggregateDeductionCandidateHasMismatchedArity =
1142 OldPack.getKind() == TemplateArgument::Pack &&
1143 NewPack.getKind() == TemplateArgument::Pack &&
1144 OldPack.pack_size() != NewPack.pack_size() && !Result.isNull();
1145
1146 // If we deferred a deduction of this pack, check that one now too.
1147 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
1148 OldPack = Result;
1149 NewPack = Pack.DeferredDeduction;
1150 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
1151 }
1152
1153 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
1154 if (Result.isNull()) {
1155 Info.Param = makeTemplateParameter(Param);
1156 Info.FirstArg = OldPack;
1157 Info.SecondArg = NewPack;
1158 return TemplateDeductionResult::Inconsistent;
1159 }
1160
1161 // If we have a pre-expanded pack and we didn't deduce enough elements
1162 // for it, fail deduction.
1163 if (UnsignedOrNone Expansions = getExpandedPackSize(Param)) {
1164 if (*Expansions != PackElements) {
1165 Info.Param = makeTemplateParameter(Param);
1166 Info.FirstArg = Result;
1167 return TemplateDeductionResult::IncompletePack;
1168 }
1169 }
1170
1171 *Loc = Result;
1172 }
1173
1174 return TemplateDeductionResult::Success;
1175 }
1176
1177private:
1178 Sema &S;
1179 TemplateParameterList *TemplateParams;
1180 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
1181 TemplateDeductionInfo &Info;
1182 unsigned PackElements = 0;
1183 bool IsPartiallyExpanded = false;
1184 bool DeducePackIfNotAlreadyDeduced = false;
1185 bool DeducedFromEarlierParameter = false;
1186 bool FinishingDeduction = false;
1187 /// The number of expansions, if we have a fully-expanded pack in this scope.
1188 UnsignedOrNone FixedNumExpansions = std::nullopt;
1189
1190 SmallVector<DeducedPack, 2> Packs;
1191};
1192
1193} // namespace
1194
1195template <class T>
1197 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1200 bool FinishingDeduction, T &&DeductFunc) {
1201 // C++0x [temp.deduct.type]p10:
1202 // Similarly, if P has a form that contains (T), then each parameter type
1203 // Pi of the respective parameter-type- list of P is compared with the
1204 // corresponding parameter type Ai of the corresponding parameter-type-list
1205 // of A. [...]
1206 unsigned ArgIdx = 0, ParamIdx = 0;
1207 for (; ParamIdx != Params.size(); ++ParamIdx) {
1208 // Check argument types.
1209 const PackExpansionType *Expansion
1210 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1211 if (!Expansion) {
1212 // Simple case: compare the parameter and argument types at this point.
1213
1214 // Make sure we have an argument.
1215 if (ArgIdx >= Args.size())
1217
1218 if (isa<PackExpansionType>(Args[ArgIdx])) {
1219 // C++0x [temp.deduct.type]p22:
1220 // If the original function parameter associated with A is a function
1221 // parameter pack and the function parameter associated with P is not
1222 // a function parameter pack, then template argument deduction fails.
1224 }
1225
1227 DeductFunc(S, TemplateParams, ParamIdx, ArgIdx,
1228 Params[ParamIdx].getUnqualifiedType(),
1229 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, POK);
1231 return Result;
1232
1233 ++ArgIdx;
1234 continue;
1235 }
1236
1237 // C++0x [temp.deduct.type]p10:
1238 // If the parameter-declaration corresponding to Pi is a function
1239 // parameter pack, then the type of its declarator- id is compared with
1240 // each remaining parameter type in the parameter-type-list of A. Each
1241 // comparison deduces template arguments for subsequent positions in the
1242 // template parameter packs expanded by the function parameter pack.
1243
1244 QualType Pattern = Expansion->getPattern();
1245 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern,
1246 /*DeducePackIfNotAlreadyDeduced=*/false,
1247 FinishingDeduction);
1248
1249 // A pack scope with fixed arity is not really a pack any more, so is not
1250 // a non-deduced context.
1251 if (ParamIdx + 1 == Params.size() || PackScope.hasFixedArity()) {
1252 for (; ArgIdx < Args.size() && PackScope.hasNextElement(); ++ArgIdx) {
1253 // Deduce template arguments from the pattern.
1254 if (TemplateDeductionResult Result = DeductFunc(
1255 S, TemplateParams, ParamIdx, ArgIdx,
1256 Pattern.getUnqualifiedType(), Args[ArgIdx].getUnqualifiedType(),
1257 Info, Deduced, POK);
1259 return Result;
1260 PackScope.nextPackElement();
1261 }
1262 } else {
1263 // C++0x [temp.deduct.type]p5:
1264 // The non-deduced contexts are:
1265 // - A function parameter pack that does not occur at the end of the
1266 // parameter-declaration-clause.
1267 //
1268 // FIXME: There is no wording to say what we should do in this case. We
1269 // choose to resolve this by applying the same rule that is applied for a
1270 // function call: that is, deduce all contained packs to their
1271 // explicitly-specified values (or to <> if there is no such value).
1272 //
1273 // This is seemingly-arbitrarily different from the case of a template-id
1274 // with a non-trailing pack-expansion in its arguments, which renders the
1275 // entire template-argument-list a non-deduced context.
1276
1277 // If the parameter type contains an explicitly-specified pack that we
1278 // could not expand, skip the number of parameters notionally created
1279 // by the expansion.
1280 UnsignedOrNone NumExpansions = Expansion->getNumExpansions();
1281 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1282 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
1283 ++I, ++ArgIdx)
1284 PackScope.nextPackElement();
1285 }
1286 }
1287
1288 // Build argument packs for each of the parameter packs expanded by this
1289 // pack expansion.
1290 if (auto Result = PackScope.finish();
1292 return Result;
1293 }
1294
1295 // DR692, DR1395
1296 // C++0x [temp.deduct.type]p10:
1297 // If the parameter-declaration corresponding to P_i ...
1298 // During partial ordering, if Ai was originally a function parameter pack:
1299 // - if P does not contain a function parameter type corresponding to Ai then
1300 // Ai is ignored;
1301 if (POK == PartialOrderingKind::Call && ArgIdx + 1 == Args.size() &&
1302 isa<PackExpansionType>(Args[ArgIdx]))
1304
1305 // Make sure we don't have any extra arguments.
1306 if (ArgIdx < Args.size())
1308
1310}
1311
1312/// Deduce the template arguments by comparing the list of parameter
1313/// types to the list of argument types, as in the parameter-type-lists of
1314/// function types (C++ [temp.deduct.type]p10).
1315///
1316/// \param S The semantic analysis object within which we are deducing
1317///
1318/// \param TemplateParams The template parameters that we are deducing
1319///
1320/// \param Params The list of parameter types
1321///
1322/// \param Args The list of argument types
1323///
1324/// \param Info information about the template argument deduction itself
1325///
1326/// \param Deduced the deduced template arguments
1327///
1328/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1329/// how template argument deduction is performed.
1330///
1331/// \param PartialOrdering If true, we are performing template argument
1332/// deduction for during partial ordering for a call
1333/// (C++0x [temp.deduct.partial]).
1334///
1335/// \param HasDeducedAnyParam If set, the object pointed at will indicate
1336/// whether any template parameter was deduced.
1337///
1338/// \param HasDeducedParam If set, the bit vector will be used to represent
1339/// which template parameters were deduced, in order.
1340///
1341/// \returns the result of template argument deduction so far. Note that a
1342/// "success" result means that template argument deduction has not yet failed,
1343/// but it may still fail, later, for other reasons.
1345 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1348 PartialOrderingKind POK, bool *HasDeducedAnyParam,
1349 llvm::SmallBitVector *HasDeducedParam) {
1350 return ::DeduceForEachType(
1351 S, TemplateParams, Params, Args, Info, Deduced, POK,
1352 /*FinishingDeduction=*/false,
1353 [&](Sema &S, TemplateParameterList *TemplateParams, int ParamIdx,
1354 int ArgIdx, QualType P, QualType A, TemplateDeductionInfo &Info,
1356 PartialOrderingKind POK) {
1357 bool HasDeducedAnyParamCopy = false;
1359 S, TemplateParams, P, A, Info, Deduced, TDF, POK,
1360 /*DeducedFromArrayBound=*/false, &HasDeducedAnyParamCopy);
1361 if (HasDeducedAnyParam && HasDeducedAnyParamCopy)
1362 *HasDeducedAnyParam = true;
1363 if (HasDeducedParam && HasDeducedAnyParamCopy)
1364 (*HasDeducedParam)[ParamIdx] = true;
1365 return TDR;
1366 });
1367}
1368
1369/// Determine whether the parameter has qualifiers that the argument
1370/// lacks. Put another way, determine whether there is no way to add
1371/// a deduced set of qualifiers to the ParamType that would result in
1372/// its qualifiers matching those of the ArgType.
1374 QualType ArgType) {
1375 Qualifiers ParamQs = ParamType.getQualifiers();
1376 Qualifiers ArgQs = ArgType.getQualifiers();
1377
1378 if (ParamQs == ArgQs)
1379 return false;
1380
1381 // Mismatched (but not missing) Objective-C GC attributes.
1382 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1383 ParamQs.hasObjCGCAttr())
1384 return true;
1385
1386 // Mismatched (but not missing) address spaces.
1387 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1388 ParamQs.hasAddressSpace())
1389 return true;
1390
1391 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1392 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1393 ParamQs.hasObjCLifetime())
1394 return true;
1395
1396 // CVR qualifiers inconsistent or a superset.
1397 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1398}
1399
1401 const FunctionType *PF = P->getAs<FunctionType>(),
1402 *AF = A->getAs<FunctionType>();
1403
1404 // Just compare if not functions.
1405 if (!PF || !AF)
1406 return Context.hasSameType(P, A);
1407
1408 // Noreturn and noexcept adjustment.
1409 if (QualType AdjustedParam; TryFunctionConversion(P, A, AdjustedParam))
1410 P = AdjustedParam;
1411
1412 // FIXME: Compatible calling conventions.
1413 return Context.hasSameFunctionTypeIgnoringExceptionSpec(P, A);
1414}
1415
1416/// Get the index of the first template parameter that was originally from the
1417/// innermost template-parameter-list. This is 0 except when we concatenate
1418/// the template parameter lists of a class template and a constructor template
1419/// when forming an implicit deduction guide.
1421 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1422 if (!Guide || !Guide->isImplicit())
1423 return 0;
1424 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1425}
1426
1427/// Determine whether a type denotes a forwarding reference.
1428static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1429 // C++1z [temp.deduct.call]p3:
1430 // A forwarding reference is an rvalue reference to a cv-unqualified
1431 // template parameter that does not represent a template parameter of a
1432 // class template.
1433 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1434 if (ParamRef->getPointeeType().getQualifiers())
1435 return false;
1436 auto *TypeParm =
1437 ParamRef->getPointeeType()->getAsCanonical<TemplateTypeParmType>();
1438 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1439 }
1440 return false;
1441}
1442
1443/// Attempt to deduce the template arguments by checking the base types
1444/// according to (C++20 [temp.deduct.call] p4b3.
1445///
1446/// \param S the semantic analysis object within which we are deducing.
1447///
1448/// \param RD the top level record object we are deducing against.
1449///
1450/// \param TemplateParams the template parameters that we are deducing.
1451///
1452/// \param P the template specialization parameter type.
1453///
1454/// \param Info information about the template argument deduction itself.
1455///
1456/// \param Deduced the deduced template arguments.
1457///
1458/// \returns the result of template argument deduction with the bases. "invalid"
1459/// means no matches, "success" found a single item, and the
1460/// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
1463 TemplateParameterList *TemplateParams, QualType P,
1466 bool *HasDeducedAnyParam) {
1467 // C++14 [temp.deduct.call] p4b3:
1468 // If P is a class and P has the form simple-template-id, then the
1469 // transformed A can be a derived class of the deduced A. Likewise if
1470 // P is a pointer to a class of the form simple-template-id, the
1471 // transformed A can be a pointer to a derived class pointed to by the
1472 // deduced A. However, if there is a class C that is a (direct or
1473 // indirect) base class of D and derived (directly or indirectly) from a
1474 // class B and that would be a valid deduced A, the deduced A cannot be
1475 // B or pointer to B, respectively.
1476 //
1477 // These alternatives are considered only if type deduction would
1478 // otherwise fail. If they yield more than one possible deduced A, the
1479 // type deduction fails.
1480
1481 // Use a breadth-first search through the bases to collect the set of
1482 // successful matches. Visited contains the set of nodes we have already
1483 // visited, while ToVisit is our stack of records that we still need to
1484 // visit. Matches contains a list of matches that have yet to be
1485 // disqualified.
1488 // We iterate over this later, so we have to use MapVector to ensure
1489 // determinism.
1490 struct MatchValue {
1492 bool HasDeducedAnyParam;
1493 };
1494 llvm::MapVector<const CXXRecordDecl *, MatchValue> Matches;
1495
1496 auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
1497 for (const auto &Base : RD->bases()) {
1498 QualType T = Base.getType();
1499 assert(T->isRecordType() && "Base class that isn't a record?");
1500 if (Visited.insert(T->getAsCXXRecordDecl()).second)
1501 ToVisit.push_back(T);
1502 }
1503 };
1504
1505 // Set up the loop by adding all the bases.
1506 AddBases(RD);
1507
1508 // Search each path of bases until we either run into a successful match
1509 // (where all bases of it are invalid), or we run out of bases.
1510 while (!ToVisit.empty()) {
1511 QualType NextT = ToVisit.pop_back_val();
1512
1514 Deduced.end());
1516 bool HasDeducedAnyParamCopy = false;
1518 S, TemplateParams, P, NextT, BaseInfo, PartialOrdering, DeducedCopy,
1519 &HasDeducedAnyParamCopy);
1520
1521 // If this was a successful deduction, add it to the list of matches,
1522 // otherwise we need to continue searching its bases.
1523 const CXXRecordDecl *RD = NextT->getAsCXXRecordDecl();
1525 Matches.insert({RD, {DeducedCopy, HasDeducedAnyParamCopy}});
1526 else
1527 AddBases(RD);
1528 }
1529
1530 // At this point, 'Matches' contains a list of seemingly valid bases, however
1531 // in the event that we have more than 1 match, it is possible that the base
1532 // of one of the matches might be disqualified for being a base of another
1533 // valid match. We can count on cyclical instantiations being invalid to
1534 // simplify the disqualifications. That is, if A & B are both matches, and B
1535 // inherits from A (disqualifying A), we know that A cannot inherit from B.
1536 if (Matches.size() > 1) {
1537 Visited.clear();
1538 for (const auto &Match : Matches)
1539 AddBases(Match.first);
1540
1541 // We can give up once we have a single item (or have run out of things to
1542 // search) since cyclical inheritance isn't valid.
1543 while (Matches.size() > 1 && !ToVisit.empty()) {
1544 const CXXRecordDecl *RD = ToVisit.pop_back_val()->getAsCXXRecordDecl();
1545 Matches.erase(RD);
1546
1547 // Always add all bases, since the inheritance tree can contain
1548 // disqualifications for multiple matches.
1549 AddBases(RD);
1550 }
1551 }
1552
1553 if (Matches.empty())
1555 if (Matches.size() > 1)
1557
1558 std::swap(Matches.front().second.Deduced, Deduced);
1559 if (bool HasDeducedAnyParamCopy = Matches.front().second.HasDeducedAnyParam;
1560 HasDeducedAnyParamCopy && HasDeducedAnyParam)
1561 *HasDeducedAnyParam = HasDeducedAnyParamCopy;
1563}
1564
1565/// When propagating a partial ordering kind into a NonCall context,
1566/// this is used to downgrade a 'Call' into a 'NonCall', so that
1567/// the kind still reflects whether we are in a partial ordering context.
1572
1573/// Deduce the template arguments by comparing the parameter type and
1574/// the argument type (C++ [temp.deduct.type]).
1575///
1576/// \param S the semantic analysis object within which we are deducing
1577///
1578/// \param TemplateParams the template parameters that we are deducing
1579///
1580/// \param P the parameter type
1581///
1582/// \param A the argument type
1583///
1584/// \param Info information about the template argument deduction itself
1585///
1586/// \param Deduced the deduced template arguments
1587///
1588/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1589/// how template argument deduction is performed.
1590///
1591/// \param PartialOrdering Whether we're performing template argument deduction
1592/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1593///
1594/// \returns the result of template argument deduction so far. Note that a
1595/// "success" result means that template argument deduction has not yet failed,
1596/// but it may still fail, later, for other reasons.
1598 Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
1601 PartialOrderingKind POK, bool DeducedFromArrayBound,
1602 bool *HasDeducedAnyParam) {
1603
1604 // If the argument type is a pack expansion, look at its pattern.
1605 // This isn't explicitly called out
1606 if (const auto *AExp = dyn_cast<PackExpansionType>(A))
1607 A = AExp->getPattern();
1609
1610 if (POK == PartialOrderingKind::Call) {
1611 // C++11 [temp.deduct.partial]p5:
1612 // Before the partial ordering is done, certain transformations are
1613 // performed on the types used for partial ordering:
1614 // - If P is a reference type, P is replaced by the type referred to.
1615 const ReferenceType *PRef = P->getAs<ReferenceType>();
1616 if (PRef)
1617 P = PRef->getPointeeType();
1618
1619 // - If A is a reference type, A is replaced by the type referred to.
1620 const ReferenceType *ARef = A->getAs<ReferenceType>();
1621 if (ARef)
1622 A = A->getPointeeType();
1623
1624 if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
1625 // C++11 [temp.deduct.partial]p9:
1626 // If, for a given type, deduction succeeds in both directions (i.e.,
1627 // the types are identical after the transformations above) and both
1628 // P and A were reference types [...]:
1629 // - if [one type] was an lvalue reference and [the other type] was
1630 // not, [the other type] is not considered to be at least as
1631 // specialized as [the first type]
1632 // - if [one type] is more cv-qualified than [the other type],
1633 // [the other type] is not considered to be at least as specialized
1634 // as [the first type]
1635 // Objective-C ARC adds:
1636 // - [one type] has non-trivial lifetime, [the other type] has
1637 // __unsafe_unretained lifetime, and the types are otherwise
1638 // identical
1639 //
1640 // A is "considered to be at least as specialized" as P iff deduction
1641 // succeeds, so we model this as a deduction failure. Note that
1642 // [the first type] is P and [the other type] is A here; the standard
1643 // gets this backwards.
1644 Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
1645 if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
1646 PQuals.isStrictSupersetOf(AQuals) ||
1647 (PQuals.hasNonTrivialObjCLifetime() &&
1648 AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1649 PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
1650 Info.FirstArg = TemplateArgument(P);
1651 Info.SecondArg = TemplateArgument(A);
1653 }
1654 }
1655 Qualifiers DiscardedQuals;
1656 // C++11 [temp.deduct.partial]p7:
1657 // Remove any top-level cv-qualifiers:
1658 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1659 // version of P.
1660 P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
1661 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1662 // version of A.
1663 A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
1664 } else {
1665 // C++0x [temp.deduct.call]p4 bullet 1:
1666 // - If the original P is a reference type, the deduced A (i.e., the type
1667 // referred to by the reference) can be more cv-qualified than the
1668 // transformed A.
1669 if (TDF & TDF_ParamWithReferenceType) {
1670 Qualifiers Quals;
1671 QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
1673 P = S.Context.getQualifiedType(UnqualP, Quals);
1674 }
1675
1676 if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
1677 // C++0x [temp.deduct.type]p10:
1678 // If P and A are function types that originated from deduction when
1679 // taking the address of a function template (14.8.2.2) or when deducing
1680 // template arguments from a function declaration (14.8.2.6) and Pi and
1681 // Ai are parameters of the top-level parameter-type-list of P and A,
1682 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1683 // is an lvalue reference, in
1684 // which case the type of Pi is changed to be the template parameter
1685 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1686 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1687 // deduced as X&. - end note ]
1689 if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
1691 P = P->getPointeeType();
1692 }
1693 }
1694
1695 // C++ [temp.deduct.type]p9:
1696 // A template type argument T, a template template argument TT or a
1697 // template non-type argument i can be deduced if P and A have one of
1698 // the following forms:
1699 //
1700 // T
1701 // cv-list T
1702 if (const auto *TTP = P->getAsCanonical<TemplateTypeParmType>()) {
1703 // Just skip any attempts to deduce from a placeholder type or a parameter
1704 // at a different depth.
1705 if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
1707
1708 unsigned Index = TTP->getIndex();
1709
1710 // If the argument type is an array type, move the qualifiers up to the
1711 // top level, so they can be matched with the qualifiers on the parameter.
1712 if (A->isArrayType()) {
1713 Qualifiers Quals;
1714 A = S.Context.getUnqualifiedArrayType(A, Quals);
1715 if (Quals)
1716 A = S.Context.getQualifiedType(A, Quals);
1717 }
1718
1719 // The argument type can not be less qualified than the parameter
1720 // type.
1721 if (!(TDF & TDF_IgnoreQualifiers) &&
1723 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1724 Info.FirstArg = TemplateArgument(P);
1725 Info.SecondArg = TemplateArgument(A);
1727 }
1728
1729 // Do not match a function type with a cv-qualified type.
1730 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1731 if (A->isFunctionType() && P.hasQualifiers())
1733
1734 assert(TTP->getDepth() == Info.getDeducedDepth() &&
1735 "saw template type parameter with wrong depth");
1736 assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&
1737 "Unresolved overloaded function");
1738 QualType DeducedType = A;
1739
1740 // Remove any qualifiers on the parameter from the deduced type.
1741 // We checked the qualifiers for consistency above.
1742 Qualifiers DeducedQs = DeducedType.getQualifiers();
1743 Qualifiers ParamQs = P.getQualifiers();
1744 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1745 if (ParamQs.hasObjCGCAttr())
1746 DeducedQs.removeObjCGCAttr();
1747 if (ParamQs.hasAddressSpace())
1748 DeducedQs.removeAddressSpace();
1749 if (ParamQs.hasObjCLifetime())
1750 DeducedQs.removeObjCLifetime();
1751
1752 // Objective-C ARC:
1753 // If template deduction would produce a lifetime qualifier on a type
1754 // that is not a lifetime type, template argument deduction fails.
1755 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1756 !DeducedType->isDependentType()) {
1757 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1758 Info.FirstArg = TemplateArgument(P);
1759 Info.SecondArg = TemplateArgument(A);
1761 }
1762
1763 // Objective-C ARC:
1764 // If template deduction would produce an argument type with lifetime type
1765 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1766 if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
1767 !DeducedQs.hasObjCLifetime())
1769
1770 DeducedType =
1771 S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
1772
1773 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1775 checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
1776 if (Result.isNull()) {
1777 // We can also get inconsistencies when matching NTTP type.
1778 switch (NamedDecl *Param = TemplateParams->getParam(Index);
1779 Param->getKind()) {
1780 case Decl::TemplateTypeParm:
1781 Info.Param = cast<TemplateTypeParmDecl>(Param);
1782 break;
1783 case Decl::NonTypeTemplateParm:
1785 break;
1786 case Decl::TemplateTemplateParm:
1788 break;
1789 default:
1790 llvm_unreachable("unexpected kind");
1791 }
1792 Info.FirstArg = Deduced[Index];
1793 Info.SecondArg = NewDeduced;
1795 }
1796
1797 Deduced[Index] = Result;
1798 if (HasDeducedAnyParam)
1799 *HasDeducedAnyParam = true;
1801 }
1802
1803 // Set up the template argument deduction information for a failure.
1804 Info.FirstArg = TemplateArgument(P);
1805 Info.SecondArg = TemplateArgument(A);
1806
1807 // If the parameter is an already-substituted template parameter
1808 // pack, do nothing: we don't know which of its arguments to look
1809 // at, so we have to wait until all of the parameter packs in this
1810 // expansion have arguments.
1811 if (P->getAs<SubstTemplateTypeParmPackType>())
1813
1814 // Check the cv-qualifiers on the parameter and argument types.
1815 if (!(TDF & TDF_IgnoreQualifiers)) {
1816 if (TDF & TDF_ParamWithReferenceType) {
1819 } else if (TDF & TDF_ArgWithReferenceType) {
1820 // C++ [temp.deduct.conv]p4:
1821 // If the original A is a reference type, A can be more cv-qualified
1822 // than the deduced A
1824 S.getASTContext()))
1826
1827 // Strip out all extra qualifiers from the argument to figure out the
1828 // type we're converting to, prior to the qualification conversion.
1829 Qualifiers Quals;
1830 A = S.Context.getUnqualifiedArrayType(A, Quals);
1832 } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
1833 if (P.getCVRQualifiers() != A.getCVRQualifiers())
1835 }
1836 }
1837
1838 // If the parameter type is not dependent, there is nothing to deduce.
1839 if (!P->isDependentType()) {
1840 if (TDF & TDF_SkipNonDependent)
1843 : S.Context.hasSameType(P, A))
1848 if (!(TDF & TDF_IgnoreQualifiers))
1850 // Otherwise, when ignoring qualifiers, the types not having the same
1851 // unqualified type does not mean they do not match, so in this case we
1852 // must keep going and analyze with a non-dependent parameter type.
1853 }
1854
1855 switch (P.getCanonicalType()->getTypeClass()) {
1856 // Non-canonical types cannot appear here.
1857#define NON_CANONICAL_TYPE(Class, Base) \
1858 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1859#define TYPE(Class, Base)
1860#include "clang/AST/TypeNodes.inc"
1861
1862 case Type::TemplateTypeParm:
1863 case Type::SubstTemplateTypeParmPack:
1864 case Type::SubstBuiltinTemplatePack:
1865 llvm_unreachable("Type nodes handled above");
1866
1867 case Type::Auto:
1868 // C++23 [temp.deduct.funcaddr]/3:
1869 // A placeholder type in the return type of a function template is a
1870 // non-deduced context.
1871 // There's no corresponding wording for [temp.deduct.decl], but we treat
1872 // it the same to match other compilers.
1873 if (P->isDependentType())
1875 [[fallthrough]];
1876 case Type::Builtin:
1877 case Type::VariableArray:
1878 case Type::Vector:
1879 case Type::FunctionNoProto:
1880 case Type::Record:
1881 case Type::Enum:
1882 case Type::ObjCObject:
1883 case Type::ObjCInterface:
1884 case Type::ObjCObjectPointer:
1885 case Type::BitInt:
1886 return (TDF & TDF_SkipNonDependent) ||
1887 ((TDF & TDF_IgnoreQualifiers)
1889 : S.Context.hasSameType(P, A))
1892
1893 // _Complex T [placeholder extension]
1894 case Type::Complex: {
1895 const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
1896 if (!CA)
1899 S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
1901 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1902 }
1903
1904 // _Atomic T [extension]
1905 case Type::Atomic: {
1906 const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
1907 if (!AA)
1910 S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
1912 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1913 }
1914
1915 // T *
1916 case Type::Pointer: {
1917 QualType PointeeType;
1918 if (const auto *PA = A->getAs<PointerType>()) {
1919 PointeeType = PA->getPointeeType();
1920 } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
1921 PointeeType = PA->getPointeeType();
1922 } else {
1924 }
1926 S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
1927 PointeeType, Info, Deduced,
1930 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1931 }
1932
1933 // T &
1934 case Type::LValueReference: {
1935 const auto *RP = P->castAs<LValueReferenceType>(),
1936 *RA = A->getAs<LValueReferenceType>();
1937 if (!RA)
1939
1941 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1943 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1944 }
1945
1946 // T && [C++0x]
1947 case Type::RValueReference: {
1948 const auto *RP = P->castAs<RValueReferenceType>(),
1949 *RA = A->getAs<RValueReferenceType>();
1950 if (!RA)
1952
1954 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1956 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1957 }
1958
1959 // T [] (implied, but not stated explicitly)
1960 case Type::IncompleteArray: {
1961 const auto *IAA = S.Context.getAsIncompleteArrayType(A);
1962 if (!IAA)
1964
1965 const auto *IAP = S.Context.getAsIncompleteArrayType(P);
1966 assert(IAP && "Template parameter not of incomplete array type");
1967
1969 S, TemplateParams, IAP->getElementType(), IAA->getElementType(), Info,
1972 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1973 }
1974
1975 // T [integer-constant]
1976 case Type::ConstantArray: {
1977 const auto *CAA = S.Context.getAsConstantArrayType(A),
1978 *CAP = S.Context.getAsConstantArrayType(P);
1979 assert(CAP);
1980 if (!CAA || CAA->getSize() != CAP->getSize())
1982
1984 S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
1987 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1988 }
1989
1990 // type [i]
1991 case Type::DependentSizedArray: {
1992 const auto *AA = S.Context.getAsArrayType(A);
1993 if (!AA)
1995
1996 // Check the element type of the arrays
1997 const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
1998 assert(DAP);
2000 S, TemplateParams, DAP->getElementType(), AA->getElementType(),
2001 Info, Deduced, TDF & TDF_IgnoreQualifiers,
2003 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2005 return Result;
2006
2007 // Determine the array bound is something we can deduce.
2009 getDeducedNTTParameterFromExpr(Info, DAP->getSizeExpr());
2010 if (!NTTP)
2012
2013 // We can perform template argument deduction for the given non-type
2014 // template parameter.
2015 assert(NTTP.getDepth() == Info.getDeducedDepth() &&
2016 "saw non-type template parameter with wrong depth");
2017 if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
2018 llvm::APSInt Size(CAA->getSize());
2020 S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
2021 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
2022 Deduced, HasDeducedAnyParam);
2023 }
2024 if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
2025 if (DAA->getSizeExpr())
2027 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info,
2028 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2029
2030 // Incomplete type does not match a dependently-sized array type
2032 }
2033
2034 // type(*)(T)
2035 // T(*)()
2036 // T(*)(T)
2037 case Type::FunctionProto: {
2038 const auto *FPP = P->castAs<FunctionProtoType>(),
2039 *FPA = A->getAs<FunctionProtoType>();
2040 if (!FPA)
2042
2043 if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
2044 FPP->getRefQualifier() != FPA->getRefQualifier() ||
2045 FPP->isVariadic() != FPA->isVariadic())
2047
2048 // Check return types.
2050 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
2052 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2054 return Result;
2055
2056 // Check parameter types.
2058 S, TemplateParams, FPP->param_types(), FPA->param_types(), Info,
2060 HasDeducedAnyParam,
2061 /*HasDeducedParam=*/nullptr);
2063 return Result;
2064
2067
2068 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
2069 // deducing through the noexcept-specifier if it's part of the canonical
2070 // type. libstdc++ relies on this.
2071 Expr *NoexceptExpr = FPP->getNoexceptExpr();
2073 NoexceptExpr ? getDeducedNTTParameterFromExpr(Info, NoexceptExpr)
2074 : nullptr) {
2075 assert(NTTP.getDepth() == Info.getDeducedDepth() &&
2076 "saw non-type template parameter with wrong depth");
2077
2078 llvm::APSInt Noexcept(1);
2079 switch (FPA->canThrow()) {
2080 case CT_Cannot:
2081 Noexcept = 1;
2082 [[fallthrough]];
2083
2084 case CT_Can:
2085 // We give E in noexcept(E) the "deduced from array bound" treatment.
2086 // FIXME: Should we?
2088 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
2089 /*DeducedFromArrayBound=*/true, Info,
2090 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2091
2092 case CT_Dependent:
2093 if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
2095 S, TemplateParams, NTTP, ArgNoexceptExpr, Info,
2096 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2097 // Can't deduce anything from throw(T...).
2098 break;
2099 }
2100 }
2101 // FIXME: Detect non-deduced exception specification mismatches?
2102 //
2103 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
2104 // top-level differences in noexcept-specifications.
2105
2107 }
2108
2109 case Type::InjectedClassName:
2110 // Treat a template's injected-class-name as if the template
2111 // specialization type had been used.
2112
2113 // template-name<T> (where template-name refers to a class template)
2114 // template-name<i>
2115 // TT<T>
2116 // TT<i>
2117 // TT<>
2118 case Type::TemplateSpecialization: {
2119 // When Arg cannot be a derived class, we can just try to deduce template
2120 // arguments from the template-id.
2121 if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
2122 return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
2124 Deduced, HasDeducedAnyParam);
2125
2127 Deduced.end());
2128
2130 S, TemplateParams, P, A, Info, POK != PartialOrderingKind::None,
2131 Deduced, HasDeducedAnyParam);
2133 return Result;
2134
2135 // We cannot inspect base classes as part of deduction when the type
2136 // is incomplete, so either instantiate any templates necessary to
2137 // complete the type, or skip over it if it cannot be completed.
2138 if (!S.isCompleteType(Info.getLocation(), A))
2139 return Result;
2140
2141 const CXXRecordDecl *RD = A->getAsCXXRecordDecl();
2142 if (RD->isInvalidDecl())
2143 return Result;
2144
2145 // Reset the incorrectly deduced argument from above.
2146 Deduced = DeducedOrig;
2147
2148 // Check bases according to C++14 [temp.deduct.call] p4b3:
2149 auto BaseResult = DeduceTemplateBases(S, RD, TemplateParams, P, Info,
2151 Deduced, HasDeducedAnyParam);
2153 : Result;
2154 }
2155
2156 // T type::*
2157 // T T::*
2158 // T (type::*)()
2159 // type (T::*)()
2160 // type (type::*)(T)
2161 // type (T::*)(T)
2162 // T (type::*)(T)
2163 // T (T::*)()
2164 // T (T::*)(T)
2165 case Type::MemberPointer: {
2166 const auto *MPP = P->castAs<MemberPointerType>(),
2167 *MPA = A->getAs<MemberPointerType>();
2168 if (!MPA)
2170
2171 QualType PPT = MPP->getPointeeType();
2172 if (PPT->isFunctionType())
2173 S.adjustMemberFunctionCC(PPT, /*HasThisPointer=*/false,
2174 /*IsCtorOrDtor=*/false, Info.getLocation());
2175 QualType APT = MPA->getPointeeType();
2176 if (APT->isFunctionType())
2177 S.adjustMemberFunctionCC(APT, /*HasThisPointer=*/false,
2178 /*IsCtorOrDtor=*/false, Info.getLocation());
2179
2180 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
2182 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF,
2184 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2186 return Result;
2187
2188 QualType TP =
2189 MPP->isSugared()
2190 ? S.Context.getCanonicalTagType(MPP->getMostRecentCXXRecordDecl())
2191 : QualType(MPP->getQualifier().getAsType(), 0);
2192 assert(!TP.isNull() && "member pointer with non-type class");
2193
2194 QualType TA =
2195 MPA->isSugared()
2196 ? S.Context.getCanonicalTagType(MPA->getMostRecentCXXRecordDecl())
2197 : QualType(MPA->getQualifier().getAsType(), 0)
2199 assert(!TA.isNull() && "member pointer with non-type class");
2200
2202 S, TemplateParams, TP, TA, Info, Deduced, SubTDF,
2204 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2205 }
2206
2207 // (clang extension)
2208 //
2209 // type(^)(T)
2210 // T(^)()
2211 // T(^)(T)
2212 case Type::BlockPointer: {
2213 const auto *BPP = P->castAs<BlockPointerType>(),
2214 *BPA = A->getAs<BlockPointerType>();
2215 if (!BPA)
2218 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
2220 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2221 }
2222
2223 // (clang extension)
2224 //
2225 // T __attribute__(((ext_vector_type(<integral constant>))))
2226 case Type::ExtVector: {
2227 const auto *VP = P->castAs<ExtVectorType>();
2228 QualType ElementType;
2229 if (const auto *VA = A->getAs<ExtVectorType>()) {
2230 // Make sure that the vectors have the same number of elements.
2231 if (VP->getNumElements() != VA->getNumElements())
2233 ElementType = VA->getElementType();
2234 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2235 // We can't check the number of elements, since the argument has a
2236 // dependent number of elements. This can only occur during partial
2237 // ordering.
2238 ElementType = VA->getElementType();
2239 } else {
2241 }
2242 // Perform deduction on the element types.
2244 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
2246 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2247 }
2248
2249 case Type::DependentVector: {
2250 const auto *VP = P->castAs<DependentVectorType>();
2251
2252 if (const auto *VA = A->getAs<VectorType>()) {
2253 // Perform deduction on the element types.
2255 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2256 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2257 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2259 return Result;
2260
2261 // Perform deduction on the vector size, if we can.
2263 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2264 if (!NTTP)
2266
2267 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2268 ArgSize = VA->getNumElements();
2269 // Note that we use the "array bound" rules here; just like in that
2270 // case, we don't have any particular type for the vector size, but
2271 // we can provide one if necessary.
2273 S, TemplateParams, NTTP, ArgSize, S.Context.UnsignedIntTy, true,
2274 Info, POK != PartialOrderingKind::None, Deduced,
2275 HasDeducedAnyParam);
2276 }
2277
2278 if (const auto *VA = A->getAs<DependentVectorType>()) {
2279 // Perform deduction on the element types.
2281 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2282 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2283 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2285 return Result;
2286
2287 // Perform deduction on the vector size, if we can.
2289 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2290 if (!NTTP)
2292
2294 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2295 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2296 }
2297
2299 }
2300
2301 // (clang extension)
2302 //
2303 // T __attribute__(((ext_vector_type(N))))
2304 case Type::DependentSizedExtVector: {
2305 const auto *VP = P->castAs<DependentSizedExtVectorType>();
2306
2307 if (const auto *VA = A->getAs<ExtVectorType>()) {
2308 // Perform deduction on the element types.
2310 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2311 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2312 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2314 return Result;
2315
2316 // Perform deduction on the vector size, if we can.
2318 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2319 if (!NTTP)
2321
2322 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2323 ArgSize = VA->getNumElements();
2324 // Note that we use the "array bound" rules here; just like in that
2325 // case, we don't have any particular type for the vector size, but
2326 // we can provide one if necessary.
2328 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2329 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2330 }
2331
2332 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2333 // Perform deduction on the element types.
2335 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2336 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2337 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2339 return Result;
2340
2341 // Perform deduction on the vector size, if we can.
2343 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2344 if (!NTTP)
2346
2348 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2349 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2350 }
2351
2353 }
2354
2355 // (clang extension)
2356 //
2357 // T __attribute__((matrix_type(<integral constant>,
2358 // <integral constant>)))
2359 case Type::ConstantMatrix: {
2360 const auto *MP = P->castAs<ConstantMatrixType>(),
2361 *MA = A->getAs<ConstantMatrixType>();
2362 if (!MA)
2364
2365 // Check that the dimensions are the same
2366 if (MP->getNumRows() != MA->getNumRows() ||
2367 MP->getNumColumns() != MA->getNumColumns()) {
2369 }
2370 // Perform deduction on element types.
2372 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2374 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2375 }
2376
2377 case Type::DependentSizedMatrix: {
2378 const auto *MP = P->castAs<DependentSizedMatrixType>();
2379 const auto *MA = A->getAs<MatrixType>();
2380 if (!MA)
2382
2383 // Check the element type of the matrixes.
2385 S, TemplateParams, MP->getElementType(), MA->getElementType(),
2386 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2387 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2389 return Result;
2390
2391 // Try to deduce a matrix dimension.
2392 auto DeduceMatrixArg =
2393 [&S, &Info, &Deduced, &TemplateParams, &HasDeducedAnyParam, POK](
2394 Expr *ParamExpr, const MatrixType *A,
2395 unsigned (ConstantMatrixType::*GetArgDimension)() const,
2396 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2397 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2398 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
2399 if (!ParamExpr->isValueDependent()) {
2400 std::optional<llvm::APSInt> ParamConst =
2401 ParamExpr->getIntegerConstantExpr(S.Context);
2402 if (!ParamConst)
2404
2405 if (ACM) {
2406 if ((ACM->*GetArgDimension)() == *ParamConst)
2409 }
2410
2411 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2412 if (std::optional<llvm::APSInt> ArgConst =
2413 ArgExpr->getIntegerConstantExpr(S.Context))
2414 if (*ArgConst == *ParamConst)
2417 }
2418
2420 getDeducedNTTParameterFromExpr(Info, ParamExpr);
2421 if (!NTTP)
2423
2424 if (ACM) {
2425 llvm::APSInt ArgConst(
2427 ArgConst = (ACM->*GetArgDimension)();
2429 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
2430 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
2431 Deduced, HasDeducedAnyParam);
2432 }
2433
2435 S, TemplateParams, NTTP, (ADM->*GetArgDimensionExpr)(), Info,
2436 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2437 };
2438
2439 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
2443 return Result;
2444
2445 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2448 }
2449
2450 // (clang extension)
2451 //
2452 // T __attribute__(((address_space(N))))
2453 case Type::DependentAddressSpace: {
2454 const auto *ASP = P->castAs<DependentAddressSpaceType>();
2455
2456 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
2457 // Perform deduction on the pointer type.
2459 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2460 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2461 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2463 return Result;
2464
2465 // Perform deduction on the address space, if we can.
2467 getDeducedNTTParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2468 if (!NTTP)
2470
2472 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info,
2473 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2474 }
2475
2477 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2478 false);
2479 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
2480
2481 // Perform deduction on the pointer types.
2483 S, TemplateParams, ASP->getPointeeType(),
2484 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF,
2486 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2488 return Result;
2489
2490 // Perform deduction on the address space, if we can.
2492 getDeducedNTTParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2493 if (!NTTP)
2495
2497 S, TemplateParams, NTTP, ArgAddressSpace, S.Context.IntTy, true,
2498 Info, POK != PartialOrderingKind::None, Deduced,
2499 HasDeducedAnyParam);
2500 }
2501
2503 }
2504 case Type::DependentBitInt: {
2505 const auto *IP = P->castAs<DependentBitIntType>();
2506
2507 if (const auto *IA = A->getAs<BitIntType>()) {
2508 if (IP->isUnsigned() != IA->isUnsigned())
2510
2512 getDeducedNTTParameterFromExpr(Info, IP->getNumBitsExpr());
2513 if (!NTTP)
2515
2516 // Deduce the size parameter of _BitInt as std::size_t
2518 llvm::APSInt ArgSize(S.Context.getTypeSize(T), /*IsUnsigned=*/true);
2519 ArgSize = IA->getNumBits();
2520
2522 S, TemplateParams, NTTP, ArgSize, T, true, Info,
2523 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2524 }
2525
2526 if (const auto *IA = A->getAs<DependentBitIntType>()) {
2527 if (IP->isUnsigned() != IA->isUnsigned())
2530 }
2531
2533 }
2534
2535 case Type::TypeOfExpr:
2536 case Type::TypeOf:
2537 case Type::DependentName:
2538 case Type::UnresolvedUsing:
2539 case Type::Decltype:
2540 case Type::UnaryTransform:
2541 case Type::DeducedTemplateSpecialization:
2542 case Type::PackExpansion:
2543 case Type::Pipe:
2544 case Type::ArrayParameter:
2545 case Type::HLSLAttributedResource:
2546 case Type::HLSLInlineSpirv:
2547 case Type::OverflowBehavior:
2548 // No template argument deduction for these types
2550
2551 case Type::PackIndexing: {
2552 const PackIndexingType *PIT = P->getAs<PackIndexingType>();
2553 if (PIT->hasSelectedType()) {
2555 S, TemplateParams, PIT->getSelectedType(), A, Info, Deduced, TDF,
2557 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2558 }
2560 }
2561 }
2562
2563 llvm_unreachable("Invalid Type Class!");
2564}
2565
2566/// C++26 [temp.deduct.type]p13:
2567/// When the value of the argument corresponding to a constant template
2568/// parameter P that is declared with a dependent type is deduced from an
2569/// expression, the template parameters in the type of P are deduced from the
2570/// type of the value.
2572 const TemplateArgument &A) {
2573 const Expr *E = A.getAsExpr();
2576 return NTTP.getType();
2578}
2579
2585 bool *HasDeducedAnyParam) {
2586 // If the template argument is a pack expansion, perform template argument
2587 // deduction against the pattern of that expansion. This only occurs during
2588 // partial ordering.
2589 if (A.isPackExpansion())
2591
2592 switch (P.getKind()) {
2594 llvm_unreachable("Null template argument in parameter list");
2595
2599 S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0,
2602 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2603 Info.FirstArg = P;
2604 Info.SecondArg = A;
2606
2608 // PartialOrdering does not matter here, since template specializations are
2609 // not being deduced.
2612 S, TemplateParams, P.getAsTemplate(), A.getAsTemplate(), Info,
2613 /*DefaultArguments=*/{}, /*PartialOrdering=*/false, Deduced,
2614 HasDeducedAnyParam);
2615 Info.FirstArg = P;
2616 Info.SecondArg = A;
2618
2620 llvm_unreachable("caller should handle pack expansions");
2621
2626
2627 Info.FirstArg = P;
2628 Info.SecondArg = A;
2630
2632 // 'nullptr' has only one possible value, so it always matches.
2635 Info.FirstArg = P;
2636 Info.SecondArg = A;
2638
2641 if (llvm::APSInt::isSameValue(P.getAsIntegral(), A.getAsIntegral()))
2643 }
2644 Info.FirstArg = P;
2645 Info.SecondArg = A;
2647
2649 // FIXME: structural equality will also compare types,
2650 // but they should match iff they have the same value.
2652 A.structurallyEquals(P))
2654
2655 Info.FirstArg = P;
2656 Info.SecondArg = A;
2658
2662 switch (A.getKind()) {
2665 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2667 Deduced, HasDeducedAnyParam);
2668 }
2672 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2674 HasDeducedAnyParam);
2675
2678 S, TemplateParams, NTTP, A.getNullPtrType(), Info, PartialOrdering,
2679 Deduced, HasDeducedAnyParam);
2680
2683 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
2684 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
2685
2691 Info.FirstArg = P;
2692 Info.SecondArg = A;
2694 }
2695 llvm_unreachable("Unknown template argument kind");
2696 }
2697 // Can't deduce anything, but that's okay.
2700 llvm_unreachable("Argument packs should be expanded by the caller!");
2701 }
2702
2703 llvm_unreachable("Invalid TemplateArgument Kind!");
2704}
2705
2706/// Determine whether there is a template argument to be used for
2707/// deduction.
2708///
2709/// This routine "expands" argument packs in-place, overriding its input
2710/// parameters so that \c Args[ArgIdx] will be the available template argument.
2711///
2712/// \returns true if there is another template argument (which will be at
2713/// \c Args[ArgIdx]), false otherwise.
2715 unsigned &ArgIdx) {
2716 if (ArgIdx == Args.size())
2717 return false;
2718
2719 const TemplateArgument &Arg = Args[ArgIdx];
2720 if (Arg.getKind() != TemplateArgument::Pack)
2721 return true;
2722
2723 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2724 Args = Arg.pack_elements();
2725 ArgIdx = 0;
2726 return ArgIdx < Args.size();
2727}
2728
2729/// Determine whether the given set of template arguments has a pack
2730/// expansion that is not the last template argument.
2732 bool FoundPackExpansion = false;
2733 for (const auto &A : Args) {
2734 if (FoundPackExpansion)
2735 return true;
2736
2737 if (A.getKind() == TemplateArgument::Pack)
2738 return hasPackExpansionBeforeEnd(A.pack_elements());
2739
2740 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2741 // templates, it should not be treated as a pack expansion.
2742 if (A.isPackExpansion())
2743 FoundPackExpansion = true;
2744 }
2745
2746 return false;
2747}
2748
2755 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
2756 PackFold PackFold, bool *HasDeducedAnyParam) {
2757 bool FoldPackParameter = PackFold == PackFold::ParameterToArgument ||
2759 FoldPackArgument = PackFold == PackFold::ArgumentToParameter ||
2761
2762 // C++0x [temp.deduct.type]p9:
2763 // If the template argument list of P contains a pack expansion that is not
2764 // the last template argument, the entire template argument list is a
2765 // non-deduced context.
2766 if (FoldPackParameter && hasPackExpansionBeforeEnd(Ps))
2768
2769 // C++0x [temp.deduct.type]p9:
2770 // If P has a form that contains <T> or <i>, then each argument Pi of the
2771 // respective template argument list P is compared with the corresponding
2772 // argument Ai of the corresponding template argument list of A.
2773 for (unsigned ArgIdx = 0, ParamIdx = 0; /**/; /**/) {
2775 return !FoldPackParameter && hasTemplateArgumentForDeduction(As, ArgIdx)
2778
2779 if (!Ps[ParamIdx].isPackExpansion()) {
2780 // The simple case: deduce template arguments by matching Pi and Ai.
2781
2782 // Check whether we have enough arguments.
2783 if (!hasTemplateArgumentForDeduction(As, ArgIdx))
2784 return !FoldPackArgument && NumberOfArgumentsMustMatch
2787
2788 if (As[ArgIdx].isPackExpansion()) {
2789 // C++1z [temp.deduct.type]p9:
2790 // During partial ordering, if Ai was originally a pack expansion
2791 // [and] Pi is not a pack expansion, template argument deduction
2792 // fails.
2793 if (!FoldPackArgument)
2795
2796 TemplateArgument Pattern = As[ArgIdx].getPackExpansionPattern();
2797 for (;;) {
2798 // Deduce template parameters from the pattern.
2800 S, TemplateParams, Ps[ParamIdx], Pattern, Info,
2801 PartialOrdering, Deduced, HasDeducedAnyParam);
2803 return Result;
2804
2805 ++ParamIdx;
2808 if (Ps[ParamIdx].isPackExpansion())
2809 break;
2810 }
2811 } else {
2812 // Perform deduction for this Pi/Ai pair.
2814 S, TemplateParams, Ps[ParamIdx], As[ArgIdx], Info,
2815 PartialOrdering, Deduced, HasDeducedAnyParam);
2817 return Result;
2818
2819 ++ArgIdx;
2820 ++ParamIdx;
2821 continue;
2822 }
2823 }
2824
2825 // The parameter is a pack expansion.
2826
2827 // C++0x [temp.deduct.type]p9:
2828 // If Pi is a pack expansion, then the pattern of Pi is compared with
2829 // each remaining argument in the template argument list of A. Each
2830 // comparison deduces template arguments for subsequent positions in the
2831 // template parameter packs expanded by Pi.
2832 TemplateArgument Pattern = Ps[ParamIdx].getPackExpansionPattern();
2833
2834 // Prepare to deduce the packs within the pattern.
2835 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2836
2837 // Keep track of the deduced template arguments for each parameter pack
2838 // expanded by this pack expansion (the outer index) and for each
2839 // template argument (the inner SmallVectors).
2840 for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
2841 PackScope.hasNextElement();
2842 ++ArgIdx) {
2843 if (!As[ArgIdx].isPackExpansion()) {
2844 if (!FoldPackParameter)
2846 if (FoldPackArgument)
2847 Info.setStrictPackMatch();
2848 }
2849 // Deduce template arguments from the pattern.
2851 S, TemplateParams, Pattern, As[ArgIdx], Info, PartialOrdering,
2852 Deduced, HasDeducedAnyParam);
2854 return Result;
2855
2856 PackScope.nextPackElement();
2857 }
2858
2859 // Build argument packs for each of the parameter packs expanded by this
2860 // pack expansion.
2861 return PackScope.finish();
2862 }
2863}
2864
2869 bool NumberOfArgumentsMustMatch) {
2870 return ::DeduceTemplateArguments(
2871 *this, TemplateParams, Ps, As, Info, Deduced, NumberOfArgumentsMustMatch,
2872 /*PartialOrdering=*/false, PackFold::ParameterToArgument,
2873 /*HasDeducedAnyParam=*/nullptr);
2874}
2875
2878 QualType NTTPType, SourceLocation Loc) {
2879 switch (Arg.getKind()) {
2881 llvm_unreachable("Can't get a NULL template argument here");
2882
2884 return TemplateArgumentLoc(
2885 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2886
2888 if (NTTPType.isNull())
2889 NTTPType = Arg.getParamTypeForDecl();
2890 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2891 .getAs<Expr>();
2892 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
2893 }
2894
2896 if (NTTPType.isNull())
2897 NTTPType = Arg.getNullPtrType();
2898 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2899 .getAs<Expr>();
2900 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2901 E);
2902 }
2903
2907 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
2908 }
2909
2914 Builder.MakeTrivial(Context, Template.getQualifier(), Loc);
2915 return TemplateArgumentLoc(
2916 Context, Arg, Loc, Builder.getWithLocInContext(Context), Loc,
2917 /*EllipsisLoc=*/Arg.getKind() == TemplateArgument::TemplateExpansion
2918 ? Loc
2919 : SourceLocation());
2920 }
2921
2923 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2924
2927 }
2928
2929 llvm_unreachable("Invalid TemplateArgument Kind!");
2930}
2931
2934 SourceLocation Location) {
2936 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2937}
2938
2939/// Convert the given deduced template argument and add it to the set of
2940/// fully-converted template arguments.
2941static bool
2944 TemplateDeductionInfo &Info, bool IsDeduced,
2946 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2947 unsigned ArgumentPackIndex) {
2948 // Convert the deduced template argument into a template
2949 // argument that we can check, almost as if the user had written
2950 // the template argument explicitly.
2951 TemplateArgumentLoc ArgLoc =
2953
2954 SaveAndRestore _1(CTAI.MatchingTTP, false);
2955 SaveAndRestore _2(CTAI.StrictPackMatch, false);
2956 // Check the template argument, converting it as necessary.
2957 auto Res = S.CheckTemplateArgument(
2958 Param, ArgLoc, Template, Template->getLocation(),
2959 Template->getSourceRange().getEnd(), ArgumentPackIndex, CTAI,
2960 IsDeduced
2964 if (CTAI.StrictPackMatch)
2965 Info.setStrictPackMatch();
2966 return Res;
2967 };
2968
2969 if (Arg.getKind() == TemplateArgument::Pack) {
2970 // This is a template argument pack, so check each of its arguments against
2971 // the template parameter.
2972 SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
2973 CanonicalPackedArgsBuilder;
2974 for (const auto &P : Arg.pack_elements()) {
2975 // When converting the deduced template argument, append it to the
2976 // general output list. We need to do this so that the template argument
2977 // checking logic has all of the prior template arguments available.
2978 DeducedTemplateArgument InnerArg(P);
2980 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2981 "deduced nested pack");
2982 if (P.isNull()) {
2983 // We deduced arguments for some elements of this pack, but not for
2984 // all of them. This happens if we get a conditionally-non-deduced
2985 // context in a pack expansion (such as an overload set in one of the
2986 // arguments).
2987 S.Diag(Param->getLocation(),
2988 diag::err_template_arg_deduced_incomplete_pack)
2989 << Arg << Param;
2990 return true;
2991 }
2992 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
2993 return true;
2994
2995 // Move the converted template argument into our argument pack.
2996 SugaredPackedArgsBuilder.push_back(CTAI.SugaredConverted.pop_back_val());
2997 CanonicalPackedArgsBuilder.push_back(
2998 CTAI.CanonicalConverted.pop_back_val());
2999 }
3000
3001 // If the pack is empty, we still need to substitute into the parameter
3002 // itself, in case that substitution fails.
3003 if (SugaredPackedArgsBuilder.empty()) {
3006 /*Final=*/true);
3007 Sema::ArgPackSubstIndexRAII OnlySubstNonPackExpansion(S, std::nullopt);
3008
3009 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3010 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
3011 NTTP, CTAI.SugaredConverted,
3012 Template->getSourceRange());
3013 if (Inst.isInvalid() ||
3014 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
3015 NTTP->getDeclName()).isNull())
3016 return true;
3017 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3018 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
3019 TTP, CTAI.SugaredConverted,
3020 Template->getSourceRange());
3021 if (Inst.isInvalid() ||
3022 !S.SubstTemplateParams(TTP->getTemplateParameters(), S.CurContext,
3023 Args))
3024 return true;
3025 }
3026 // For type parameters, no substitution is ever required.
3027 }
3028
3029 // Create the resulting argument pack.
3030 CTAI.SugaredConverted.push_back(
3031 TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
3033 S.Context, CanonicalPackedArgsBuilder));
3034 return false;
3035 }
3036
3037 return ConvertArg(Arg, 0);
3038}
3039
3040/// \param IsIncomplete When used, we only consider template parameters that
3041/// were deduced, disregarding any default arguments. After the function
3042/// finishes, the object pointed at will contain a value indicating if the
3043/// conversion was actually incomplete.
3045 Sema &S, NamedDecl *Template, TemplateParameterList *TemplateParams,
3048 LocalInstantiationScope *CurrentInstantiationScope,
3049 unsigned NumAlreadyConverted, bool *IsIncomplete) {
3050 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3051 NamedDecl *Param = TemplateParams->getParam(I);
3052
3053 // C++0x [temp.arg.explicit]p3:
3054 // A trailing template parameter pack (14.5.3) not otherwise deduced will
3055 // be deduced to an empty sequence of template arguments.
3056 // FIXME: Where did the word "trailing" come from?
3057 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
3058 if (auto Result =
3059 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish();
3061 return Result;
3062 }
3063
3064 if (!Deduced[I].isNull()) {
3065 if (I < NumAlreadyConverted) {
3066 // We may have had explicitly-specified template arguments for a
3067 // template parameter pack (that may or may not have been extended
3068 // via additional deduced arguments).
3069 if (Param->isParameterPack() && CurrentInstantiationScope &&
3070 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
3071 // Forget the partially-substituted pack; its substitution is now
3072 // complete.
3073 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
3074 // We still need to check the argument in case it was extended by
3075 // deduction.
3076 } else {
3077 // We have already fully type-checked and converted this
3078 // argument, because it was explicitly-specified. Just record the
3079 // presence of this argument.
3080 CTAI.SugaredConverted.push_back(Deduced[I]);
3081 CTAI.CanonicalConverted.push_back(
3083 continue;
3084 }
3085 }
3086
3087 // We may have deduced this argument, so it still needs to be
3088 // checked and converted.
3089 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
3090 IsDeduced, CTAI)) {
3091 Info.Param = makeTemplateParameter(Param);
3092 // FIXME: These template arguments are temporary. Free them!
3093 Info.reset(
3096 CTAI.CanonicalConverted));
3098 }
3099
3100 continue;
3101 }
3102
3103 // [C++26][temp.deduct.partial]p12 - When partial ordering, it's ok for
3104 // template parameters to remain not deduced. As a provisional fix for a
3105 // core issue that does not exist yet, which may be related to CWG2160, only
3106 // consider template parameters that were deduced, disregarding any default
3107 // arguments.
3108 if (IsIncomplete) {
3109 *IsIncomplete = true;
3110 CTAI.SugaredConverted.push_back({});
3111 CTAI.CanonicalConverted.push_back({});
3112 continue;
3113 }
3114
3115 // Substitute into the default template argument, if available.
3116 bool HasDefaultArg = false;
3117 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
3118 if (!TD) {
3122 }
3123
3124 TemplateArgumentLoc DefArg;
3125 {
3126 Qualifiers ThisTypeQuals;
3127 CXXRecordDecl *ThisContext = nullptr;
3128 if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
3129 if (Rec->isLambda())
3130 if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
3131 ThisContext = Method->getParent();
3132 ThisTypeQuals = Method->getMethodQualifiers();
3133 }
3134
3135 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
3136 S.getLangOpts().CPlusPlus17);
3137
3139 TD, /*TemplateKWLoc=*/SourceLocation(), TD->getLocation(),
3140 TD->getSourceRange().getEnd(), Param, CTAI.SugaredConverted,
3141 CTAI.CanonicalConverted, HasDefaultArg);
3142 }
3143
3144 // If there was no default argument, deduction is incomplete.
3145 if (DefArg.getArgument().isNull()) {
3146 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3147 Info.reset(
3150
3153 }
3154
3155 SaveAndRestore _1(CTAI.PartialOrdering, false);
3156 SaveAndRestore _2(CTAI.MatchingTTP, false);
3157 SaveAndRestore _3(CTAI.StrictPackMatch, false);
3158 // Check whether we can actually use the default argument.
3160 Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
3161 /*ArgumentPackIndex=*/0, CTAI, Sema::CTAK_Specified)) {
3162 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3163 // FIXME: These template arguments are temporary. Free them!
3164 Info.reset(
3168 }
3169
3170 // If we get here, we successfully used the default template argument.
3171 }
3172
3174}
3175
3177 if (auto *DC = dyn_cast<DeclContext>(D))
3178 return DC;
3179 return D->getDeclContext();
3180}
3181
3182template<typename T> struct IsPartialSpecialization {
3183 static constexpr bool value = false;
3184};
3185template<>
3189template<>
3191 static constexpr bool value = true;
3192};
3193
3196 ArrayRef<TemplateArgument> SugaredDeducedArgs,
3197 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
3198 TemplateDeductionInfo &Info) {
3199 llvm::SmallVector<AssociatedConstraint, 3> AssociatedConstraints;
3200 bool DeducedArgsNeedReplacement = false;
3201 if (auto *TD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Template)) {
3202 TD->getAssociatedConstraints(AssociatedConstraints);
3203 DeducedArgsNeedReplacement = !TD->isClassScopeExplicitSpecialization();
3204 } else if (auto *TD =
3205 dyn_cast<VarTemplatePartialSpecializationDecl>(Template)) {
3206 TD->getAssociatedConstraints(AssociatedConstraints);
3207 DeducedArgsNeedReplacement = !TD->isClassScopeExplicitSpecialization();
3208 } else {
3209 cast<TemplateDecl>(Template)->getAssociatedConstraints(
3210 AssociatedConstraints);
3211 }
3212
3213 std::optional<ArrayRef<TemplateArgument>> Innermost;
3214 // If we don't need to replace the deduced template arguments,
3215 // we can add them immediately as the inner-most argument list.
3216 if (!DeducedArgsNeedReplacement)
3217 Innermost = SugaredDeducedArgs;
3218
3220 Template, Template->getDeclContext(), /*Final=*/false, Innermost,
3221 /*RelativeToPrimary=*/true, /*Pattern=*/
3222 nullptr, /*ForConstraintInstantiation=*/true);
3223
3224 // getTemplateInstantiationArgs picks up the non-deduced version of the
3225 // template args when this is a variable template partial specialization and
3226 // not class-scope explicit specialization, so replace with Deduced Args
3227 // instead of adding to inner-most.
3228 if (!Innermost)
3229 MLTAL.replaceInnermostTemplateArguments(Template, SugaredDeducedArgs);
3230
3231 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
3232 Info.getLocation(),
3235 Info.reset(
3236 TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
3237 TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
3239 }
3241}
3242
3246 TemplateDeductionInfo &Info) {
3247 TemplateParameterList *TPL = Template->getTemplateParameters();
3248 TemplateArgumentListInfo InstArgs(TPL->getLAngleLoc(), TPL->getRAngleLoc());
3249 if (S.SubstTemplateArguments(Ps, MLTAL, InstArgs)) {
3250 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
3251 if (ParamIdx >= TPL->size())
3252 ParamIdx = TPL->size() - 1;
3253
3254 Decl *Param = TPL->getParam(ParamIdx);
3255 Info.Param = makeTemplateParameter(Param);
3256 Info.FirstArg = Ps[ArgIdx].getArgument();
3258 }
3259
3262 if (S.CheckTemplateArgumentList(Template, Template->getLocation(), InstArgs,
3263 /*DefaultArgs=*/{}, false, InstCTAI,
3264 /*UpdateArgsWithConversions=*/true,
3269
3270 // Check that we produced the correct argument list.
3272 AsStack{As};
3273 for (;;) {
3274 auto take = [](SmallVectorImpl<ArrayRef<TemplateArgument>> &Stack)
3276 while (!Stack.empty()) {
3277 auto &Xs = Stack.back();
3278 if (Xs.empty()) {
3279 Stack.pop_back();
3280 continue;
3281 }
3282 auto &X = Xs.front();
3283 if (X.getKind() == TemplateArgument::Pack) {
3284 Stack.emplace_back(X.getPackAsArray());
3285 Xs = Xs.drop_front();
3286 continue;
3287 }
3288 assert(!X.isNull());
3289 return {Xs, X};
3290 }
3291 static constexpr ArrayRef<TemplateArgument> None;
3292 return {const_cast<ArrayRef<TemplateArgument> &>(None),
3294 };
3295 auto [Ps, P] = take(PsStack);
3296 auto [As, A] = take(AsStack);
3297 if (P.isNull() && A.isNull())
3298 break;
3299 TemplateArgument PP = P.isPackExpansion() ? P.getPackExpansionPattern() : P,
3300 PA = A.isPackExpansion() ? A.getPackExpansionPattern() : A;
3301 if (!S.Context.isSameTemplateArgument(PP, PA)) {
3302 if (!P.isPackExpansion() && !A.isPackExpansion()) {
3304 (AsStack.empty() ? As.end() : AsStack.back().begin()) -
3305 As.begin()));
3306 Info.FirstArg = P;
3307 Info.SecondArg = A;
3309 }
3310 if (P.isPackExpansion()) {
3311 Ps = Ps.drop_front();
3312 continue;
3313 }
3314 if (A.isPackExpansion()) {
3315 As = As.drop_front();
3316 continue;
3317 }
3318 }
3319 Ps = Ps.drop_front(P.isPackExpansion() ? 0 : 1);
3320 As = As.drop_front(A.isPackExpansion() && !P.isPackExpansion() ? 0 : 1);
3321 }
3322 assert(PsStack.empty());
3323 assert(AsStack.empty());
3325}
3326
3327/// Complete template argument deduction.
3329 Sema &S, NamedDecl *Entity, TemplateParameterList *EntityTPL,
3333 TemplateDeductionInfo &Info, bool CopyDeducedArgs) {
3334 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Entity));
3335
3336 // C++ [temp.deduct.type]p2:
3337 // [...] or if any template argument remains neither deduced nor
3338 // explicitly specified, template argument deduction fails.
3341 S, Entity, EntityTPL, /*IsDeduced=*/PartialOrdering, Deduced, Info,
3342 CTAI,
3343 /*CurrentInstantiationScope=*/nullptr,
3344 /*NumAlreadyConverted=*/0U, /*IsIncomplete=*/nullptr);
3346 return Result;
3347
3348 if (CopyDeducedArgs) {
3349 // Form the template argument list from the deduced template arguments.
3350 TemplateArgumentList *SugaredDeducedArgumentList =
3352 TemplateArgumentList *CanonicalDeducedArgumentList =
3354 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3355 }
3356
3358 /*Final=*/true);
3359 MLTAL.addOuterRetainedLevels(Template->getTemplateParameters()->getDepth());
3360 if (auto Result =
3361 CheckDeducedTemplateArgumentList(S, Template, Ps, As, MLTAL, Info);
3363 return Result;
3364
3365 if (!PartialOrdering) {
3367 S, Entity, CTAI.SugaredConverted, CTAI.CanonicalConverted, Info);
3369 return Result;
3370 }
3371
3373}
3375 Sema &S, NamedDecl *Entity, TemplateParameterList *EntityTPL,
3379 TemplateDeductionInfo &Info, bool CopyDeducedArgs) {
3380 TemplateParameterList *TPL = Template->getTemplateParameters();
3381 SmallVector<TemplateArgumentLoc, 8> PsLoc(Ps.size());
3382 for (unsigned I = 0, N = Ps.size(); I != N; ++I)
3383 PsLoc[I] = S.getTrivialTemplateArgumentLoc(Ps[I], QualType(),
3384 TPL->getParam(I)->getLocation());
3385 return FinishTemplateArgumentDeduction(S, Entity, EntityTPL, Template,
3386 PartialOrdering, PsLoc, As, Deduced,
3387 Info, CopyDeducedArgs);
3388}
3389
3390/// Complete template argument deduction for DeduceTemplateArgumentsFromType.
3391/// FIXME: this is mostly duplicated with the above two versions. Deduplicate
3392/// the three implementations.
3394 Sema &S, TemplateDecl *TD,
3396 TemplateDeductionInfo &Info) {
3398
3399 // C++ [temp.deduct.type]p2:
3400 // [...] or if any template argument remains neither deduced nor
3401 // explicitly specified, template argument deduction fails.
3404 S, TD, TD->getTemplateParameters(), /*IsDeduced=*/false, Deduced,
3405 Info, CTAI,
3406 /*CurrentInstantiationScope=*/nullptr, /*NumAlreadyConverted=*/0,
3407 /*IsIncomplete=*/nullptr);
3409 return Result;
3410
3411 return ::CheckDeducedArgumentConstraints(S, TD, CTAI.SugaredConverted,
3412 CTAI.CanonicalConverted, Info);
3413}
3414
3415/// Perform template argument deduction to determine whether the given template
3416/// arguments match the given class or variable template partial specialization
3417/// per C++ [temp.class.spec.match].
3418template <typename T>
3419static std::enable_if_t<IsPartialSpecialization<T>::value,
3422 ArrayRef<TemplateArgument> TemplateArgs,
3423 TemplateDeductionInfo &Info) {
3424 if (Partial->isInvalidDecl())
3426
3427 // C++ [temp.class.spec.match]p2:
3428 // A partial specialization matches a given actual template
3429 // argument list if the template arguments of the partial
3430 // specialization can be deduced from the actual template argument
3431 // list (14.8.2).
3432
3433 // Unevaluated SFINAE context.
3436 Sema::SFINAETrap Trap(S, Info);
3437
3438 // This deduction has no relation to any outer instantiation we might be
3439 // performing.
3440 LocalInstantiationScope InstantiationScope(S);
3441
3443 Deduced.resize(Partial->getTemplateParameters()->size());
3445 S, Partial->getTemplateParameters(),
3446 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3447 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/false,
3449 /*HasDeducedAnyParam=*/nullptr);
3451 return Result;
3452
3453 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3454 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs);
3455 if (Inst.isInvalid())
3457
3460 Result = ::FinishTemplateArgumentDeduction(
3461 S, Partial, Partial->getTemplateParameters(),
3462 Partial->getSpecializedTemplate(),
3463 /*IsPartialOrdering=*/false,
3464 Partial->getTemplateArgsAsWritten()->arguments(), TemplateArgs, Deduced,
3465 Info, /*CopyDeducedArgs=*/true);
3466 });
3467
3469 return Result;
3470
3471 if (Trap.hasErrorOccurred())
3473
3475}
3476
3479 ArrayRef<TemplateArgument> TemplateArgs,
3480 TemplateDeductionInfo &Info) {
3481 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3482}
3485 ArrayRef<TemplateArgument> TemplateArgs,
3486 TemplateDeductionInfo &Info) {
3487 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3488}
3489
3493 if (TD->isInvalidDecl())
3495
3496 QualType PType;
3497 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
3498 // Use the InjectedClassNameType.
3499 PType = Context.getCanonicalTagType(CTD->getTemplatedDecl());
3500 } else if (const auto *AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(TD)) {
3501 PType = AliasTemplate->getTemplatedDecl()->getUnderlyingType();
3502 } else {
3503 assert(false && "Expected a class or alias template");
3504 }
3505
3506 // Unevaluated SFINAE context.
3509 SFINAETrap Trap(*this, Info);
3510
3511 // This deduction has no relation to any outer instantiation we might be
3512 // performing.
3513 LocalInstantiationScope InstantiationScope(*this);
3514
3516 TD->getTemplateParameters()->size());
3519 if (auto DeducedResult = DeduceTemplateArguments(
3520 TD->getTemplateParameters(), PArgs, AArgs, Info, Deduced, false);
3521 DeducedResult != TemplateDeductionResult::Success) {
3522 return DeducedResult;
3523 }
3524
3525 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3526 InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs);
3527 if (Inst.isInvalid())
3529
3532 Result = ::FinishTemplateArgumentDeduction(*this, TD, Deduced, Info);
3533 });
3534
3536 return Result;
3537
3538 if (Trap.hasErrorOccurred())
3540
3542}
3543
3544/// Determine whether the given type T is a simple-template-id type.
3546 if (const TemplateSpecializationType *Spec
3547 = T->getAs<TemplateSpecializationType>())
3548 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
3549
3550 // C++17 [temp.local]p2:
3551 // the injected-class-name [...] is equivalent to the template-name followed
3552 // by the template-arguments of the class template specialization or partial
3553 // specialization enclosed in <>
3554 // ... which means it's equivalent to a simple-template-id.
3555 //
3556 // This only arises during class template argument deduction for a copy
3557 // deduction candidate, where it permits slicing.
3558 if (isa<InjectedClassNameType>(T.getCanonicalType()))
3559 return true;
3560
3561 return false;
3562}
3563
3566 TemplateArgumentListInfo &ExplicitTemplateArgs,
3569 TemplateDeductionInfo &Info) {
3570 assert(isSFINAEContext());
3571 assert(isUnevaluatedContext());
3572
3573 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3574 TemplateParameterList *TemplateParams
3575 = FunctionTemplate->getTemplateParameters();
3576
3577 if (ExplicitTemplateArgs.size() == 0) {
3578 // No arguments to substitute; just copy over the parameter types and
3579 // fill in the function type.
3580 for (auto *P : Function->parameters())
3581 ParamTypes.push_back(P->getType());
3582
3583 if (FunctionType)
3584 *FunctionType = Function->getType();
3586 }
3587
3588 // C++ [temp.arg.explicit]p3:
3589 // Template arguments that are present shall be specified in the
3590 // declaration order of their corresponding template-parameters. The
3591 // template argument list shall not specify more template-arguments than
3592 // there are corresponding template-parameters.
3593
3594 // Enter a new template instantiation context where we check the
3595 // explicitly-specified template arguments against this function template,
3596 // and then substitute them into the function parameter types.
3599 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3601 if (Inst.isInvalid())
3603
3606 ExplicitTemplateArgs, /*DefaultArgs=*/{},
3607 /*PartialTemplateArgs=*/true, CTAI,
3608 /*UpdateArgsWithConversions=*/false)) {
3609 unsigned Index = CTAI.SugaredConverted.size();
3610 if (Index >= TemplateParams->size())
3612 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3614 }
3615
3616 // Form the template argument list from the explicitly-specified
3617 // template arguments.
3618 TemplateArgumentList *SugaredExplicitArgumentList =
3620 TemplateArgumentList *CanonicalExplicitArgumentList =
3622 Info.setExplicitArgs(SugaredExplicitArgumentList,
3623 CanonicalExplicitArgumentList);
3624
3625 // Template argument deduction and the final substitution should be
3626 // done in the context of the templated declaration. Explicit
3627 // argument substitution, on the other hand, needs to happen in the
3628 // calling context.
3629 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3630
3631 // If we deduced template arguments for a template parameter pack,
3632 // note that the template argument pack is partially substituted and record
3633 // the explicit template arguments. They'll be used as part of deduction
3634 // for this template parameter pack.
3635 unsigned PartiallySubstitutedPackIndex = -1u;
3636 if (!CTAI.SugaredConverted.empty()) {
3637 const TemplateArgument &Arg = CTAI.SugaredConverted.back();
3638 if (Arg.getKind() == TemplateArgument::Pack) {
3639 auto *Param = TemplateParams->getParam(CTAI.SugaredConverted.size() - 1);
3640 // If this is a fully-saturated fixed-size pack, it should be
3641 // fully-substituted, not partially-substituted.
3642 UnsignedOrNone Expansions = getExpandedPackSize(Param);
3643 if (!Expansions || Arg.pack_size() < *Expansions) {
3644 PartiallySubstitutedPackIndex = CTAI.SugaredConverted.size() - 1;
3645 CurrentInstantiationScope->SetPartiallySubstitutedPack(
3646 Param, Arg.pack_begin(), Arg.pack_size());
3647 }
3648 }
3649 }
3650
3651 const FunctionProtoType *Proto
3652 = Function->getType()->getAs<FunctionProtoType>();
3653 assert(Proto && "Function template does not have a prototype?");
3654
3655 // Isolate our substituted parameters from our caller.
3656 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3657
3658 ExtParameterInfoBuilder ExtParamInfos;
3659
3661 SugaredExplicitArgumentList->asArray(),
3662 /*Final=*/true);
3663
3664 // Instantiate the types of each of the function parameters given the
3665 // explicitly-specified template arguments. If the function has a trailing
3666 // return type, substitute it after the arguments to ensure we substitute
3667 // in lexical order.
3668 if (Proto->hasTrailingReturn()) {
3669 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3670 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3671 /*params=*/nullptr, ExtParamInfos))
3673 }
3674
3675 // Instantiate the return type.
3676 QualType ResultType;
3677 {
3678 // C++11 [expr.prim.general]p3:
3679 // If a declaration declares a member function or member function
3680 // template of a class X, the expression this is a prvalue of type
3681 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3682 // and the end of the function-definition, member-declarator, or
3683 // declarator.
3684 Qualifiers ThisTypeQuals;
3685 CXXRecordDecl *ThisContext = nullptr;
3686 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3687 ThisContext = Method->getParent();
3688 ThisTypeQuals = Method->getMethodQualifiers();
3689 }
3690
3691 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3693
3694 ResultType =
3695 SubstType(Proto->getReturnType(), MLTAL,
3696 Function->getTypeSpecStartLoc(), Function->getDeclName());
3697 if (ResultType.isNull())
3699 // CUDA: Kernel function must have 'void' return type.
3700 if (getLangOpts().CUDA)
3701 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3702 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3703 << Function->getType() << Function->getSourceRange();
3705 }
3706 }
3707
3708 // Instantiate the types of each of the function parameters given the
3709 // explicitly-specified template arguments if we didn't do so earlier.
3710 if (!Proto->hasTrailingReturn() &&
3711 SubstParmTypes(Function->getLocation(), Function->parameters(),
3712 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3713 /*params*/ nullptr, ExtParamInfos))
3715
3716 if (FunctionType) {
3717 auto EPI = Proto->getExtProtoInfo();
3718 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3719 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3720 Function->getLocation(),
3721 Function->getDeclName(),
3722 EPI);
3723 if (FunctionType->isNull())
3725 }
3726
3727 // C++ [temp.arg.explicit]p2:
3728 // Trailing template arguments that can be deduced (14.8.2) may be
3729 // omitted from the list of explicit template-arguments. If all of the
3730 // template arguments can be deduced, they may all be omitted; in this
3731 // case, the empty template argument list <> itself may also be omitted.
3732 //
3733 // Take all of the explicitly-specified arguments and put them into
3734 // the set of deduced template arguments. The partially-substituted
3735 // parameter pack, however, will be set to NULL since the deduction
3736 // mechanism handles the partially-substituted argument pack directly.
3737 Deduced.reserve(TemplateParams->size());
3738 for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3739 const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
3740 if (I == PartiallySubstitutedPackIndex)
3741 Deduced.push_back(DeducedTemplateArgument());
3742 else
3743 Deduced.push_back(Arg);
3744 }
3745
3747}
3748
3749/// Check whether the deduced argument type for a call to a function
3750/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3753 Sema::OriginalCallArg OriginalArg,
3754 QualType DeducedA) {
3755 ASTContext &Context = S.Context;
3756
3757 auto Failed = [&]() -> TemplateDeductionResult {
3758 Info.FirstArg = TemplateArgument(DeducedA);
3759 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3760 Info.CallArgIndex = OriginalArg.ArgIdx;
3761 return OriginalArg.DecomposedParam
3764 };
3765
3766 QualType A = OriginalArg.OriginalArgType;
3767 QualType OriginalParamType = OriginalArg.OriginalParamType;
3768
3769 // Check for type equality (top-level cv-qualifiers and _Atomic are ignored,
3770 // since _Atomic is treated as a qualifier).
3771 if (Context.hasSameType(A.getAtomicUnqualifiedType(),
3772 DeducedA.getAtomicUnqualifiedType()))
3774
3775 // Strip off references on the argument types; they aren't needed for
3776 // the following checks.
3777 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3778 DeducedA = DeducedARef->getPointeeType();
3779 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3780 A = ARef->getPointeeType();
3781
3782 // C++ [temp.deduct.call]p4:
3783 // [...] However, there are three cases that allow a difference:
3784 // - If the original P is a reference type, the deduced A (i.e., the
3785 // type referred to by the reference) can be more cv-qualified than
3786 // the transformed A.
3787 if (const ReferenceType *OriginalParamRef
3788 = OriginalParamType->getAs<ReferenceType>()) {
3789 // We don't want to keep the reference around any more.
3790 OriginalParamType = OriginalParamRef->getPointeeType();
3791
3792 // FIXME: Resolve core issue (no number yet): if the original P is a
3793 // reference type and the transformed A is function type "noexcept F",
3794 // the deduced A can be F.
3795 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA))
3797
3798 Qualifiers AQuals = A.getQualifiers();
3799 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3800
3801 // Under Objective-C++ ARC, the deduced type may have implicitly
3802 // been given strong or (when dealing with a const reference)
3803 // unsafe_unretained lifetime. If so, update the original
3804 // qualifiers to include this lifetime.
3805 if (S.getLangOpts().ObjCAutoRefCount &&
3806 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3808 (DeducedAQuals.hasConst() &&
3809 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3810 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3811 }
3812
3813 if (AQuals == DeducedAQuals) {
3814 // Qualifiers match; there's nothing to do.
3815 } else if (!DeducedAQuals.compatiblyIncludes(AQuals, S.getASTContext())) {
3816 return Failed();
3817 } else {
3818 // Qualifiers are compatible, so have the argument type adopt the
3819 // deduced argument type's qualifiers as if we had performed the
3820 // qualification conversion.
3821 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3822 }
3823 }
3824
3825 // - The transformed A can be another pointer or pointer to member
3826 // type that can be converted to the deduced A via a function pointer
3827 // conversion and/or a qualification conversion.
3828 //
3829 // Also allow conversions which merely strip __attribute__((noreturn)) from
3830 // function types (recursively).
3831 bool ObjCLifetimeConversion = false;
3832 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3833 (S.IsQualificationConversion(A, DeducedA, false,
3834 ObjCLifetimeConversion) ||
3835 S.IsFunctionConversion(A, DeducedA)))
3837
3838 // - If P is a class and P has the form simple-template-id, then the
3839 // transformed A can be a derived class of the deduced A. [...]
3840 // [...] Likewise, if P is a pointer to a class of the form
3841 // simple-template-id, the transformed A can be a pointer to a
3842 // derived class pointed to by the deduced A.
3843 if (const PointerType *OriginalParamPtr
3844 = OriginalParamType->getAs<PointerType>()) {
3845 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3846 if (const PointerType *APtr = A->getAs<PointerType>()) {
3847 if (A->getPointeeType()->isRecordType()) {
3848 OriginalParamType = OriginalParamPtr->getPointeeType();
3849 DeducedA = DeducedAPtr->getPointeeType();
3850 A = APtr->getPointeeType();
3851 }
3852 }
3853 }
3854 }
3855
3856 if (Context.hasSameUnqualifiedType(A, DeducedA))
3858
3859 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3860 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3862
3863 return Failed();
3864}
3865
3866/// Find the pack index for a particular parameter index in an instantiation of
3867/// a function template with specific arguments.
3868///
3869/// \return The pack index for whichever pack produced this parameter, or -1
3870/// if this was not produced by a parameter. Intended to be used as the
3871/// ArgumentPackSubstitutionIndex for further substitutions.
3872// FIXME: We should track this in OriginalCallArgs so we don't need to
3873// reconstruct it here.
3874static UnsignedOrNone
3877 unsigned ParamIdx) {
3878 unsigned Idx = 0;
3879 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3880 if (PD->isParameterPack()) {
3881 UnsignedOrNone NumArgs =
3882 S.getNumArgumentsInExpansion(PD->getType(), Args);
3883 unsigned NumExpansions = NumArgs ? *NumArgs : 1;
3884 if (Idx + NumExpansions > ParamIdx)
3885 return ParamIdx - Idx;
3886 Idx += NumExpansions;
3887 } else {
3888 if (Idx == ParamIdx)
3889 return std::nullopt; // Not a pack expansion
3890 ++Idx;
3891 }
3892 }
3893
3894 llvm_unreachable("parameter index would not be produced from template");
3895}
3896
3897// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`,
3898// we'll try to instantiate and update its explicit specifier after constraint
3899// checking.
3902 const MultiLevelTemplateArgumentList &SubstArgs,
3904 ArrayRef<TemplateArgument> DeducedArgs) {
3905 auto GetExplicitSpecifier = [](FunctionDecl *D) {
3906 return isa<CXXConstructorDecl>(D)
3907 ? cast<CXXConstructorDecl>(D)->getExplicitSpecifier()
3908 : cast<CXXConversionDecl>(D)->getExplicitSpecifier();
3909 };
3910 auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) {
3912 ? cast<CXXConstructorDecl>(D)->setExplicitSpecifier(ES)
3913 : cast<CXXConversionDecl>(D)->setExplicitSpecifier(ES);
3914 };
3915
3916 ExplicitSpecifier ES = GetExplicitSpecifier(Specialization);
3917 Expr *ExplicitExpr = ES.getExpr();
3918 if (!ExplicitExpr)
3920 if (!ExplicitExpr->isValueDependent())
3922
3923 // By this point, FinishTemplateArgumentDeduction will have been reverted back
3924 // to a regular non-SFINAE template instantiation context, so setup a new
3925 // SFINAE context.
3927 S, Info.getLocation(), FunctionTemplate, DeducedArgs,
3929 if (Inst.isInvalid())
3931 Sema::SFINAETrap Trap(S, Info);
3932 const ExplicitSpecifier InstantiatedES =
3933 S.instantiateExplicitSpecifier(SubstArgs, ES);
3934 if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) {
3935 Specialization->setInvalidDecl(true);
3937 }
3938 SetExplicitSpecifier(Specialization, InstantiatedES);
3940}
3941
3945 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3947 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3948 bool PartialOverloading, bool PartialOrdering,
3949 bool ForOverloadSetAddressResolution,
3950 llvm::function_ref<bool(bool)> CheckNonDependent) {
3951 // Enter a new template instantiation context while we instantiate the
3952 // actual function declaration.
3953 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3955 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3957 if (Inst.isInvalid())
3959
3960 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3961
3962 // C++ [temp.deduct.type]p2:
3963 // [...] or if any template argument remains neither deduced nor
3964 // explicitly specified, template argument deduction fails.
3965 bool IsIncomplete = false;
3968 *this, FunctionTemplate, FunctionTemplate->getTemplateParameters(),
3969 /*IsDeduced=*/true, Deduced, Info, CTAI, CurrentInstantiationScope,
3970 NumExplicitlySpecified, PartialOverloading ? &IsIncomplete : nullptr);
3972 return Result;
3973
3974 // Form the template argument list from the deduced template arguments.
3975 TemplateArgumentList *SugaredDeducedArgumentList =
3977 TemplateArgumentList *CanonicalDeducedArgumentList =
3979 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3980
3981 // Substitute the deduced template arguments into the function template
3982 // declaration to produce the function template specialization.
3983 DeclContext *Owner = FunctionTemplate->getDeclContext();
3984 if (FunctionTemplate->getFriendObjectKind())
3985 Owner = FunctionTemplate->getLexicalDeclContext();
3986 FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
3987
3988 if (CheckNonDependent(/*OnlyInitializeNonUserDefinedConversions=*/true))
3990
3991 // C++20 [temp.deduct.general]p5: [CWG2369]
3992 // If the function template has associated constraints, those constraints
3993 // are checked for satisfaction. If the constraints are not satisfied, type
3994 // deduction fails.
3995 //
3996 // FIXME: We haven't implemented CWG2369 for lambdas yet, because we need
3997 // to figure out how to instantiate lambda captures to the scope without
3998 // first instantiating the lambda.
3999 bool IsLambda = isLambdaCallOperator(FD) || isLambdaConversionOperator(FD);
4000 if (!IsLambda && !IsIncomplete) {
4002 Info.getLocation(),
4003 FunctionTemplate->getCanonicalDecl()->getTemplatedDecl(),
4009 }
4010 }
4011 // C++ [temp.deduct.call]p10: [CWG1391]
4012 // If deduction succeeds for all parameters that contain
4013 // template-parameters that participate in template argument deduction,
4014 // and all template arguments are explicitly specified, deduced, or
4015 // obtained from default template arguments, remaining parameters are then
4016 // compared with the corresponding arguments. For each remaining parameter
4017 // P with a type that was non-dependent before substitution of any
4018 // explicitly-specified template arguments, if the corresponding argument
4019 // A cannot be implicitly converted to P, deduction fails.
4020 if (CheckNonDependent(/*OnlyInitializeNonUserDefinedConversions=*/false))
4022
4024 FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
4025 /*Final=*/false);
4026 Specialization = cast_or_null<FunctionDecl>(
4027 SubstDecl(FD, Owner, SubstArgs));
4028 if (!Specialization || Specialization->isInvalidDecl())
4030
4031 assert(isSameDeclaration(Specialization->getPrimaryTemplate(),
4033
4034 // If the template argument list is owned by the function template
4035 // specialization, release it.
4036 if (Specialization->getTemplateSpecializationArgs() ==
4037 CanonicalDeducedArgumentList)
4038 Info.takeCanonical();
4039
4040 // C++2a [temp.deduct]p5
4041 // [...] When all template arguments have been deduced [...] all uses of
4042 // template parameters [...] are replaced with the corresponding deduced
4043 // or default argument values.
4044 // [...] If the function template has associated constraints
4045 // ([temp.constr.decl]), those constraints are checked for satisfaction
4046 // ([temp.constr.constr]). If the constraints are not satisfied, type
4047 // deduction fails.
4048 if (IsLambda && !IsIncomplete) {
4056 }
4057 }
4058
4059 // We skipped the instantiation of the explicit-specifier during the
4060 // substitution of `FD` before. So, we try to instantiate it back if
4061 // `Specialization` is either a constructor or a conversion function.
4065 Info, FunctionTemplate,
4066 DeducedArgs)) {
4068 }
4069 }
4070
4071 if (OriginalCallArgs) {
4072 // C++ [temp.deduct.call]p4:
4073 // In general, the deduction process attempts to find template argument
4074 // values that will make the deduced A identical to A (after the type A
4075 // is transformed as described above). [...]
4076 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
4077 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
4078 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
4079
4080 auto ParamIdx = OriginalArg.ArgIdx;
4081 unsigned ExplicitOffset =
4082 (Specialization->hasCXXExplicitFunctionObjectParameter() &&
4083 !ForOverloadSetAddressResolution)
4084 ? 1
4085 : 0;
4086 if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset)
4087 // FIXME: This presumably means a pack ended up smaller than we
4088 // expected while deducing. Should this not result in deduction
4089 // failure? Can it even happen?
4090 continue;
4091
4092 QualType DeducedA;
4093 if (!OriginalArg.DecomposedParam) {
4094 // P is one of the function parameters, just look up its substituted
4095 // type.
4096 DeducedA =
4097 Specialization->getParamDecl(ParamIdx + ExplicitOffset)->getType();
4098 } else {
4099 // P is a decomposed element of a parameter corresponding to a
4100 // braced-init-list argument. Substitute back into P to find the
4101 // deduced A.
4102 QualType &CacheEntry =
4103 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
4104 if (CacheEntry.isNull()) {
4106 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
4107 ParamIdx));
4108 CacheEntry =
4109 SubstType(OriginalArg.OriginalParamType, SubstArgs,
4110 Specialization->getTypeSpecStartLoc(),
4111 Specialization->getDeclName());
4112 }
4113 DeducedA = CacheEntry;
4114 }
4115
4116 if (auto TDK =
4117 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
4119 return TDK;
4120 }
4121 }
4122
4123 // If we suppressed any diagnostics while performing template argument
4124 // deduction, and if we haven't already instantiated this declaration,
4125 // keep track of these diagnostics. They'll be emitted if this specialization
4126 // is actually used.
4127 if (Info.diag_begin() != Info.diag_end()) {
4128 auto [Pos, Inserted] =
4129 SuppressedDiagnostics.try_emplace(Specialization->getCanonicalDecl());
4130 if (Inserted)
4131 Pos->second.append(Info.diag_begin(), Info.diag_end());
4132 }
4133
4135}
4136
4140 if (!FailedTSC)
4141 return;
4142
4143 Decl *TemplatedDecl = TD->getTemplatedDecl();
4144 for (TemplateSpecCandidate &Candidate : *FailedTSC) {
4145 if (Candidate.Specialization &&
4146 declaresSameEntity(Candidate.Specialization, TemplatedDecl))
4147 return;
4148 }
4149
4150 FailedTSC->addCandidate().set(
4151 DeclAccessPair::make(TD, AS_public), TemplatedDecl,
4153}
4154
4156 FriendTemplateDecl *FTD, ClassTemplateDecl *PatternCTD,
4158 ArrayRef<TemplateArgument> PatternArgs,
4159 ArrayRef<TemplateArgument> CandidateArgs, SourceLocation Loc,
4160 TemplateSpecCandidateSet *FailedTSC,
4161 MultiLevelTemplateArgumentList &DeducedArgs) {
4164 ContextRAII SavedContext(*this, FTD->getDeclContext());
4165 LocalInstantiationScope InstantiationScope(*this);
4166 InstantiatingTemplate Inst(*this, Loc, FTD);
4167 if (Inst.isInvalid()) {
4168 TemplateDeductionInfo Info(Loc);
4170 *this, PatternCTD, Info, TemplateDeductionResult::InstantiationDepth,
4171 FailedTSC);
4172 return false;
4173 }
4174
4176 DeducedArgLists.reserve(TPLs.size());
4177 for (TemplateParameterList *Params : TPLs) {
4178 TemplateDeductionInfo Info(Loc, Params->getDepth());
4179 SFINAETrap Trap(*this, Info);
4182 Params, PatternArgs, CandidateArgs, Info, Deduced,
4183 /*NumberOfArgumentsMustMatch=*/false);
4184
4186 bool IsIncomplete = false;
4189 *this, PatternCTD, Params, /*IsDeduced=*/false, Deduced, Info, CTAI,
4190 &InstantiationScope, /*NumAlreadyConverted=*/0, &IsIncomplete);
4191 if (Result == TemplateDeductionResult::Success && IsIncomplete) {
4192 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
4193 if (!Deduced[I].isNull())
4194 continue;
4195 Info.Param = makeTemplateParameter(Params->getParam(I));
4196 break;
4197 }
4198 Info.reset(
4202 }
4206 AddFriendTemplateDeductionCandidate(*this, PatternCTD, Info, Result,
4207 FailedTSC);
4208 return false;
4209 }
4210
4211 DeducedArgLists.push_back(
4213 }
4214
4215 for (TemplateArgumentList *Args : llvm::reverse(DeducedArgLists))
4216 DeducedArgs.addOuterTemplateArguments(FTD, Args->asArray(),
4217 /*Final=*/true);
4218 if (!TPLs.empty())
4219 DeducedArgs.addOuterRetainedLevels(TPLs.front()->getDepth());
4220
4221 if (DeducedArgs.isAnyArgInstantiationDependent() &&
4222 llvm::any_of(TPLs, [](TemplateParameterList *Params) {
4223 return Params->hasAssociatedConstraints();
4224 }))
4225 return false;
4226
4228 PatternArgLocs.reserve(PatternArgs.size());
4229 for (const TemplateArgument &Arg : PatternArgs)
4230 PatternArgLocs.push_back(
4232
4233 {
4234 TemplateDeductionInfo Info(Loc);
4235 SFINAETrap Trap(*this, Info);
4237 *this, CandidateCTD, PatternArgLocs, CandidateArgs, DeducedArgs, Info);
4241 AddFriendTemplateDeductionCandidate(*this, PatternCTD, Info, Result,
4242 FailedTSC);
4243 return false;
4244 }
4245 }
4246
4247 for (TemplateParameterList *Params : TPLs) {
4249 Params->getAssociatedConstraints(Constraints);
4250 if (Constraints.empty())
4251 continue;
4252
4253 TemplateDeductionInfo Info(Loc, Params->getDepth());
4254 SFINAETrap Trap(*this, Info);
4255 if (CheckConstraintSatisfaction(PatternCTD, Constraints, DeducedArgs,
4256 SourceRange(Loc),
4259 Trap.hasErrorOccurred()) {
4260 SmallVector<TemplateArgument, 4> CanonicalCandidateArgs;
4261 CanonicalCandidateArgs.reserve(CandidateArgs.size());
4262 for (const TemplateArgument &Arg : CandidateArgs)
4263 CanonicalCandidateArgs.push_back(
4264 Context.getCanonicalTemplateArgument(Arg));
4265 Info.reset(
4267 TemplateArgumentList::CreateCopy(Context, CanonicalCandidateArgs));
4269 *this, PatternCTD, Info,
4271 return false;
4272 }
4273 }
4274
4275 return true;
4276}
4277
4278/// Gets the type of a function for template-argument-deducton
4279/// purposes when it's considered as part of an overload set.
4281 FunctionDecl *Fn) {
4282 // We may need to deduce the return type of the function now.
4283 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
4284 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
4285 return {};
4286
4287 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
4288 if (Method->isImplicitObjectMemberFunction()) {
4289 // An instance method that's referenced in a form that doesn't
4290 // look like a member pointer is just invalid.
4291 if (!R.HasFormOfMemberPointer)
4292 return {};
4293
4295 Fn->getType(), /*Qualifier=*/std::nullopt, Method->getParent());
4296 }
4297
4298 if (!R.IsAddressOfOperand) return Fn->getType();
4299 return S.Context.getPointerType(Fn->getType());
4300}
4301
4302/// Apply the deduction rules for overload sets.
4303///
4304/// \return the null type if this argument should be treated as an
4305/// undeduced context
4306static QualType
4308 Expr *Arg, QualType ParamType,
4309 bool ParamWasReference,
4310 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4311
4313
4314 OverloadExpr *Ovl = R.Expression;
4315
4316 // C++0x [temp.deduct.call]p4
4317 unsigned TDF = 0;
4318 if (ParamWasReference)
4320 if (R.IsAddressOfOperand)
4321 TDF |= TDF_IgnoreQualifiers;
4322
4323 // C++0x [temp.deduct.call]p6:
4324 // When P is a function type, pointer to function type, or pointer
4325 // to member function type:
4326
4327 if (!ParamType->isFunctionType() &&
4328 !ParamType->isFunctionPointerType() &&
4329 !ParamType->isMemberFunctionPointerType()) {
4330 if (Ovl->hasExplicitTemplateArgs()) {
4331 // But we can still look for an explicit specialization.
4332 if (FunctionDecl *ExplicitSpec =
4334 Ovl, /*Complain=*/false,
4335 /*Found=*/nullptr, FailedTSC,
4336 /*ForTypeDeduction=*/true))
4337 return GetTypeOfFunction(S, R, ExplicitSpec);
4338 }
4339
4340 DeclAccessPair DAP;
4341 if (FunctionDecl *Viable =
4343 return GetTypeOfFunction(S, R, Viable);
4344
4345 return {};
4346 }
4347
4348 // Gather the explicit template arguments, if any.
4349 TemplateArgumentListInfo ExplicitTemplateArgs;
4350 if (Ovl->hasExplicitTemplateArgs())
4351 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4353 for (UnresolvedSetIterator I = Ovl->decls_begin(),
4354 E = Ovl->decls_end(); I != E; ++I) {
4355 NamedDecl *D = (*I)->getUnderlyingDecl();
4356
4357 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
4358 // - If the argument is an overload set containing one or more
4359 // function templates, the parameter is treated as a
4360 // non-deduced context.
4361 if (!Ovl->hasExplicitTemplateArgs())
4362 return {};
4363
4364 // Otherwise, see if we can resolve a function type
4365 FunctionDecl *Specialization = nullptr;
4366 TemplateDeductionInfo Info(Ovl->getNameLoc());
4367 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
4370 continue;
4371
4372 D = Specialization;
4373 }
4374
4376 QualType ArgType = GetTypeOfFunction(S, R, Fn);
4377 if (ArgType.isNull()) continue;
4378
4379 // Function-to-pointer conversion.
4380 if (!ParamWasReference && ParamType->isPointerType() &&
4381 ArgType->isFunctionType())
4382 ArgType = S.Context.getPointerType(ArgType);
4383
4384 // - If the argument is an overload set (not containing function
4385 // templates), trial argument deduction is attempted using each
4386 // of the members of the set. If deduction succeeds for only one
4387 // of the overload set members, that member is used as the
4388 // argument value for the deduction. If deduction succeeds for
4389 // more than one member of the overload set the parameter is
4390 // treated as a non-deduced context.
4391
4392 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
4393 // Type deduction is done independently for each P/A pair, and
4394 // the deduced template argument values are then combined.
4395 // So we do not reject deductions which were made elsewhere.
4397 Deduced(TemplateParams->size());
4398 TemplateDeductionInfo Info(Ovl->getNameLoc());
4400 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4401 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4402 /*HasDeducedAnyParam=*/nullptr);
4404 continue;
4405 // C++ [temp.deduct.call]p6:
4406 // [...] If all successful deductions yield the same deduced A, that
4407 // deduced A is the result of deduction; otherwise, the parameter is
4408 // treated as a non-deduced context. [...]
4409 if (!Match.isNull() && !S.isSameOrCompatibleFunctionType(Match, ArgType))
4410 return {};
4411 Match = ArgType;
4412 }
4413
4414 return Match;
4415}
4416
4417/// Perform the adjustments to the parameter and argument types
4418/// described in C++ [temp.deduct.call].
4419///
4420/// \returns true if the caller should not attempt to perform any template
4421/// argument deduction based on this P/A pair because the argument is an
4422/// overloaded function set that could not be resolved.
4424 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4425 QualType &ParamType, QualType &ArgType,
4426 Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
4427 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4428 // C++0x [temp.deduct.call]p3:
4429 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
4430 // are ignored for type deduction.
4431 if (ParamType.hasQualifiers())
4432 ParamType = ParamType.getUnqualifiedType();
4433
4434 // [...] If P is a reference type, the type referred to by P is
4435 // used for type deduction.
4436 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
4437 if (ParamRefType)
4438 ParamType = ParamRefType->getPointeeType();
4439
4440 // Overload sets usually make this parameter an undeduced context,
4441 // but there are sometimes special circumstances. Typically
4442 // involving a template-id-expr.
4443 if (ArgType == S.Context.OverloadTy) {
4444 assert(Arg && "expected a non-null arg expression");
4445 ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType,
4446 ParamRefType != nullptr, FailedTSC);
4447 if (ArgType.isNull())
4448 return true;
4449 }
4450
4451 if (ParamRefType) {
4452 // If the argument has incomplete array type, try to complete its type.
4453 if (ArgType->isIncompleteArrayType()) {
4454 assert(Arg && "expected a non-null arg expression");
4455 ArgType = S.getCompletedType(Arg);
4456 }
4457
4458 // C++1z [temp.deduct.call]p3:
4459 // If P is a forwarding reference and the argument is an lvalue, the type
4460 // "lvalue reference to A" is used in place of A for type deduction.
4461 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
4462 ArgClassification.isLValue()) {
4463 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
4464 ArgType = S.Context.getAddrSpaceQualType(
4466 ArgType = S.Context.getLValueReferenceType(ArgType);
4467 }
4468 } else {
4469 // C++ [temp.deduct.call]p2:
4470 // If P is not a reference type:
4471 // - If A is an array type, the pointer type produced by the
4472 // array-to-pointer standard conversion (4.2) is used in place of
4473 // A for type deduction; otherwise,
4474 // - If A is a function type, the pointer type produced by the
4475 // function-to-pointer standard conversion (4.3) is used in place
4476 // of A for type deduction; otherwise,
4477 if (ArgType->canDecayToPointerType())
4478 ArgType = S.Context.getDecayedType(ArgType);
4479 else {
4480 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
4481 // type are ignored for type deduction.
4482 ArgType = ArgType.getUnqualifiedType();
4483 }
4484 }
4485
4486 // C++0x [temp.deduct.call]p4:
4487 // In general, the deduction process attempts to find template argument
4488 // values that will make the deduced A identical to A (after the type A
4489 // is transformed as described above). [...]
4491
4492 // - If the original P is a reference type, the deduced A (i.e., the
4493 // type referred to by the reference) can be more cv-qualified than
4494 // the transformed A.
4495 if (ParamRefType)
4497 // - The transformed A can be another pointer or pointer to member
4498 // type that can be converted to the deduced A via a qualification
4499 // conversion (4.4).
4500 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
4501 ArgType->isObjCObjectPointerType())
4502 TDF |= TDF_IgnoreQualifiers;
4503 // - If P is a class and P has the form simple-template-id, then the
4504 // transformed A can be a derived class of the deduced A. Likewise,
4505 // if P is a pointer to a class of the form simple-template-id, the
4506 // transformed A can be a pointer to a derived class pointed to by
4507 // the deduced A.
4508 if (isSimpleTemplateIdType(ParamType) ||
4509 (ParamType->getAs<PointerType>() &&
4511 ParamType->castAs<PointerType>()->getPointeeType())))
4512 TDF |= TDF_DerivedClass;
4513
4514 return false;
4515}
4516
4517static bool
4519 QualType T);
4520
4522 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4523 QualType ParamType, QualType ArgType,
4524 Expr::Classification ArgClassification, Expr *Arg,
4528 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4529 TemplateSpecCandidateSet *FailedTSC = nullptr);
4530
4531/// Attempt template argument deduction from an initializer list
4532/// deemed to be an argument in a function call.
4534 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
4537 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
4538 unsigned TDF) {
4539 // C++ [temp.deduct.call]p1: (CWG 1591)
4540 // If removing references and cv-qualifiers from P gives
4541 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
4542 // a non-empty initializer list, then deduction is performed instead for
4543 // each element of the initializer list, taking P0 as a function template
4544 // parameter type and the initializer element as its argument
4545 //
4546 // We've already removed references and cv-qualifiers here.
4547 if (!ILE->getNumInits())
4549
4550 QualType ElTy;
4551 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
4552 if (ArrTy)
4553 ElTy = ArrTy->getElementType();
4554 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
4555 // Otherwise, an initializer list argument causes the parameter to be
4556 // considered a non-deduced context
4558 }
4559
4560 // Resolving a core issue: a braced-init-list containing any designators is
4561 // a non-deduced context.
4562 for (Expr *E : ILE->inits())
4565
4566 // Deduction only needs to be done for dependent types.
4567 if (ElTy->isDependentType()) {
4568 for (Expr *E : ILE->inits()) {
4570 S, TemplateParams, 0, ElTy, E->getType(),
4571 E->Classify(S.getASTContext()), E, Info, Deduced,
4572 OriginalCallArgs, true, ArgIdx, TDF);
4574 return Result;
4575 }
4576 }
4577
4578 // in the P0[N] case, if N is a non-type template parameter, N is deduced
4579 // from the length of the initializer list.
4580 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
4581 // Determine the array bound is something we can deduce.
4583 Info, DependentArrTy->getSizeExpr())) {
4584 // We can perform template argument deduction for the given non-type
4585 // template parameter.
4586 // C++ [temp.deduct.type]p13:
4587 // The type of N in the type T[N] is std::size_t.
4589 llvm::APInt Size(S.Context.getIntWidth(T),
4592 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
4593 /*ArrayBound=*/true, Info, /*PartialOrdering=*/false, Deduced,
4594 /*HasDeducedAnyParam=*/nullptr);
4596 return Result;
4597 }
4598 }
4599
4601}
4602
4603/// Perform template argument deduction per [temp.deduct.call] for a
4604/// single parameter / argument pair.
4606 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4607 QualType ParamType, QualType ArgType,
4608 Expr::Classification ArgClassification, Expr *Arg,
4612 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4613 TemplateSpecCandidateSet *FailedTSC) {
4614
4615 QualType OrigParamType = ParamType;
4616
4617 // If P is a reference type [...]
4618 // If P is a cv-qualified type [...]
4620 S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
4621 ArgClassification, Arg, TDF, FailedTSC))
4623
4624 // If [...] the argument is a non-empty initializer list [...]
4625 if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
4626 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
4627 Deduced, OriginalCallArgs, ArgIdx, TDF);
4628
4629 // [...] the deduction process attempts to find template argument values
4630 // that will make the deduced A identical to A
4631 //
4632 // Keep track of the argument type and corresponding parameter index,
4633 // so we can check for compatibility between the deduced A and A.
4634 if (Arg)
4635 OriginalCallArgs.push_back(
4636 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
4638 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4639 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4640 /*HasDeducedAnyParam=*/nullptr);
4641}
4642
4645 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4647 bool PartialOverloading, bool AggregateDeductionCandidate,
4648 bool PartialOrdering, QualType ObjectType,
4649 Expr::Classification ObjectClassification,
4650 bool ForOverloadSetAddressResolution,
4651 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent) {
4652 if (FunctionTemplate->isInvalidDecl())
4654
4655 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4656 unsigned NumParams = Function->getNumParams();
4657 bool HasExplicitObject = false;
4658 int ExplicitObjectOffset = 0;
4659
4660 // [C++26] [over.call.func]p3
4661 // If the primary-expression is the address of an overload set,
4662 // the argument list is the same as the expression-list in the call.
4663 // Otherwise, the argument list is the expression-list in the call augmented
4664 // by the addition of an implied object argument as in a qualified function
4665 // call.
4666 if (!ForOverloadSetAddressResolution &&
4667 Function->hasCXXExplicitFunctionObjectParameter()) {
4668 HasExplicitObject = true;
4669 ExplicitObjectOffset = 1;
4670 }
4671
4672 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
4673
4674 // C++ [temp.deduct.call]p1:
4675 // Template argument deduction is done by comparing each function template
4676 // parameter type (call it P) with the type of the corresponding argument
4677 // of the call (call it A) as described below.
4678 if (Args.size() < Function->getMinRequiredExplicitArguments() &&
4679 !PartialOverloading)
4681 else if (TooManyArguments(NumParams, Args.size() + ExplicitObjectOffset,
4682 PartialOverloading)) {
4683 const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
4684 if (Proto->isTemplateVariadic())
4685 /* Do nothing */;
4686 else if (!Proto->isVariadic())
4688 }
4689
4692 Sema::SFINAETrap Trap(*this, Info);
4693
4694 // The types of the parameters from which we will perform template argument
4695 // deduction.
4696 LocalInstantiationScope InstScope(*this);
4697 TemplateParameterList *TemplateParams
4698 = FunctionTemplate->getTemplateParameters();
4700 SmallVector<QualType, 8> ParamTypes;
4701 unsigned NumExplicitlySpecified = 0;
4702 if (ExplicitTemplateArgs) {
4705 Result = SubstituteExplicitTemplateArguments(
4706 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4707 Info);
4708 });
4710 return Result;
4711 if (Trap.hasErrorOccurred())
4713
4714 NumExplicitlySpecified = Deduced.size();
4715 } else {
4716 // Just fill in the parameter types from the function declaration.
4717 for (unsigned I = 0; I != NumParams; ++I)
4718 ParamTypes.push_back(Function->getParamDecl(I)->getType());
4719 }
4720
4721 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
4722
4723 // Deduce an argument of type ParamType from an expression with index ArgIdx.
4724 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx,
4725 bool ExplicitObjectArgument) {
4726 // C++ [demp.deduct.call]p1: (DR1391)
4727 // Template argument deduction is done by comparing each function template
4728 // parameter that contains template-parameters that participate in
4729 // template argument deduction ...
4730 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4732
4733 if (ExplicitObjectArgument) {
4734 // ... with the type of the corresponding argument
4736 *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
4737 ObjectClassification,
4738 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4739 /*Decomposed*/ false, ArgIdx, /*TDF*/ 0);
4740 }
4741
4742 // ... with the type of the corresponding argument
4744 *this, TemplateParams, FirstInnerIndex, ParamType,
4745 Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()),
4746 Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false,
4747 ArgIdx, /*TDF*/ 0);
4748 };
4749
4750 // Deduce template arguments from the function parameters.
4751 Deduced.resize(TemplateParams->size());
4752 SmallVector<QualType, 8> ParamTypesForArgChecking;
4753 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4754 ParamIdx != NumParamTypes; ++ParamIdx) {
4755 QualType ParamType = ParamTypes[ParamIdx];
4756
4757 const PackExpansionType *ParamExpansion =
4758 dyn_cast<PackExpansionType>(ParamType);
4759 if (!ParamExpansion) {
4760 // Simple case: matching a function parameter to a function argument.
4761 if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0))
4762 break;
4763
4764 ParamTypesForArgChecking.push_back(ParamType);
4765
4766 if (ParamIdx == 0 && HasExplicitObject) {
4767 if (ObjectType.isNull())
4769
4770 if (auto Result = DeduceCallArgument(ParamType, 0,
4771 /*ExplicitObjectArgument=*/true);
4773 return Result;
4774 continue;
4775 }
4776
4777 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4778 /*ExplicitObjectArgument=*/false);
4780 return Result;
4781
4782 continue;
4783 }
4784
4785 bool IsTrailingPack = ParamIdx + 1 == NumParamTypes;
4786
4787 QualType ParamPattern = ParamExpansion->getPattern();
4788 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
4789 ParamPattern,
4790 AggregateDeductionCandidate && IsTrailingPack);
4791
4792 // C++0x [temp.deduct.call]p1:
4793 // For a function parameter pack that occurs at the end of the
4794 // parameter-declaration-list, the type A of each remaining argument of
4795 // the call is compared with the type P of the declarator-id of the
4796 // function parameter pack. Each comparison deduces template arguments
4797 // for subsequent positions in the template parameter packs expanded by
4798 // the function parameter pack. When a function parameter pack appears
4799 // in a non-deduced context [not at the end of the list], the type of
4800 // that parameter pack is never deduced.
4801 //
4802 // FIXME: The above rule allows the size of the parameter pack to change
4803 // after we skip it (in the non-deduced case). That makes no sense, so
4804 // we instead notionally deduce the pack against N arguments, where N is
4805 // the length of the explicitly-specified pack if it's expanded by the
4806 // parameter pack and 0 otherwise, and we treat each deduction as a
4807 // non-deduced context.
4808 if (IsTrailingPack || PackScope.hasFixedArity()) {
4809 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4810 PackScope.nextPackElement(), ++ArgIdx) {
4811 ParamTypesForArgChecking.push_back(ParamPattern);
4812 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4813 /*ExplicitObjectArgument=*/false);
4815 return Result;
4816 }
4817 } else {
4818 // If the parameter type contains an explicitly-specified pack that we
4819 // could not expand, skip the number of parameters notionally created
4820 // by the expansion.
4821 UnsignedOrNone NumExpansions = ParamExpansion->getNumExpansions();
4822 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4823 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4824 ++I, ++ArgIdx) {
4825 ParamTypesForArgChecking.push_back(ParamPattern);
4826 // FIXME: Should we add OriginalCallArgs for these? What if the
4827 // corresponding argument is a list?
4828 PackScope.nextPackElement();
4829 }
4830 } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4831 PackScope.isDeducedFromEarlierParameter()) {
4832 // [temp.deduct.general#3]
4833 // When all template arguments have been deduced
4834 // or obtained from default template arguments, all uses of template
4835 // parameters in the template parameter list of the template are
4836 // replaced with the corresponding deduced or default argument values
4837 //
4838 // If we have a trailing parameter pack, that has been deduced
4839 // previously we substitute the pack here in a similar fashion as
4840 // above with the trailing parameter packs. The main difference here is
4841 // that, in this case we are not processing all of the remaining
4842 // arguments. We are only process as many arguments as we have in
4843 // the already deduced parameter.
4844 UnsignedOrNone ArgPosAfterSubstitution =
4845 PackScope.getSavedPackSizeIfAllEqual();
4846 if (!ArgPosAfterSubstitution)
4847 continue;
4848
4849 unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4850 for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4851 ParamTypesForArgChecking.push_back(ParamPattern);
4852 if (auto Result =
4853 DeduceCallArgument(ParamPattern, ArgIdx,
4854 /*ExplicitObjectArgument=*/false);
4856 return Result;
4857
4858 PackScope.nextPackElement();
4859 }
4860 }
4861 }
4862
4863 // Build argument packs for each of the parameter packs expanded by this
4864 // pack expansion.
4865 if (auto Result = PackScope.finish();
4867 return Result;
4868 }
4869
4870 // Capture the context in which the function call is made. This is the context
4871 // that is needed when the accessibility of template arguments is checked.
4872 DeclContext *CallingCtx = CurContext;
4873
4876 Result = FinishTemplateArgumentDeduction(
4877 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4878 &OriginalCallArgs, PartialOverloading, PartialOrdering,
4879 ForOverloadSetAddressResolution,
4880 [&, CallingCtx](bool OnlyInitializeNonUserDefinedConversions) {
4881 ContextRAII SavedContext(*this, CallingCtx);
4882 return CheckNonDependent(ParamTypesForArgChecking,
4883 OnlyInitializeNonUserDefinedConversions);
4884 });
4885 });
4886 if (Trap.hasErrorOccurred()) {
4887 if (Specialization)
4888 Specialization->setInvalidDecl(true);
4890 }
4891 return Result;
4892}
4893
4896 bool AdjustExceptionSpec) {
4897 if (ArgFunctionType.isNull())
4898 return ArgFunctionType;
4899
4900 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4901 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4902 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4903 bool Rebuild = false;
4904
4905 CallingConv CC = FunctionTypeP->getCallConv();
4906 if (EPI.ExtInfo.getCC() != CC) {
4907 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4908 Rebuild = true;
4909 }
4910
4911 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4912 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4913 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4914 Rebuild = true;
4915 }
4916
4917 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4918 ArgFunctionTypeP->hasExceptionSpec())) {
4919 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4920 Rebuild = true;
4921 }
4922
4923 if (!Rebuild)
4924 return ArgFunctionType;
4925
4926 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4927 ArgFunctionTypeP->getParamTypes(), EPI);
4928}
4929
4932 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4934 bool IsAddressOfFunction) {
4935 if (FunctionTemplate->isInvalidDecl())
4937
4938 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4939 TemplateParameterList *TemplateParams
4940 = FunctionTemplate->getTemplateParameters();
4941 QualType FunctionType = Function->getType();
4942
4945
4946 // Unevaluated SFINAE context.
4949 SFINAETrap Trap(*this, Info);
4950
4951 // Substitute any explicit template arguments.
4952 LocalInstantiationScope InstScope(*this);
4954 unsigned NumExplicitlySpecified = 0;
4955 SmallVector<QualType, 4> ParamTypes;
4956 if (ExplicitTemplateArgs) {
4959 Result = SubstituteExplicitTemplateArguments(
4960 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4961 &FunctionType, Info);
4962 });
4964 return Result;
4965 if (Trap.hasErrorOccurred())
4967
4968 NumExplicitlySpecified = Deduced.size();
4969 }
4970
4971 // When taking the address of a function, we require convertibility of
4972 // the resulting function type. Otherwise, we allow arbitrary mismatches
4973 // of calling convention and noreturn.
4974 if (!IsAddressOfFunction)
4975 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4976 /*AdjustExceptionSpec*/false);
4977
4978 Deduced.resize(TemplateParams->size());
4979
4980 // If the function has a deduced return type, substitute it for a dependent
4981 // type so that we treat it as a non-deduced context in what follows.
4982 bool HasDeducedReturnType = false;
4983 if (getLangOpts().CPlusPlus14 &&
4984 Function->getReturnType()->getContainedAutoType()) {
4986 HasDeducedReturnType = true;
4987 }
4988
4989 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
4990 unsigned TDF =
4992 // Deduce template arguments from the function type.
4994 *this, TemplateParams, FunctionType, ArgFunctionType, Info, Deduced,
4995 TDF, PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4996 /*HasDeducedAnyParam=*/nullptr);
4998 return Result;
4999 // Substituting the function type can instantiate the trailing return type,
5000 // so handle the same immediate-context substitution failure here.
5001 if (Trap.hasErrorOccurred())
5003 }
5004
5007 Result = FinishTemplateArgumentDeduction(
5008 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
5009 /*OriginalCallArgs=*/nullptr, /*PartialOverloading=*/false,
5010 /*PartialOrdering=*/true, IsAddressOfFunction);
5011 });
5012 // Taking the address of a function template forms its function type, and
5013 // substituting into that type can require instantiating a trailing return
5014 // type whose expression selects a deleted function. That is a deduction
5015 // failure, not a hard error:
5016 //
5017 // C++ [temp.deduct.funcaddr]p1:
5018 // [...] If there is a target, the function template's function type and
5019 // the target type are used as the types of P and A, and the deduction is
5020 // done as described in [temp.deduct.type].
5021 //
5022 // C++ [temp.deduct.general]p7:
5023 // [...] The substitution occurs in all types and expressions that are
5024 // used in the deduction substitution loci. The expressions include [...]
5025 // general expressions (i.e., non-constant expressions) inside sizeof,
5026 // decltype, and other contexts that allow non-constant expressions. [...]
5027 //
5028 // C++ [dcl.fct.def.delete]p2:
5029 // A construct that designates a deleted function implicitly or
5030 // explicitly, other than to declare it [...], is ill-formed.
5031 // [Note: [...] It applies even for references in expressions that are not
5032 // potentially evaluated. - end note]
5033 //
5034 // C++ [temp.deduct.general]p8:
5035 // If a substitution results in an invalid type or expression, type
5036 // deduction fails. [...] Invalid types and expressions can result in a
5037 // deduction failure only in the immediate context of the deduction
5038 // substitution loci. [...]
5039 //
5040 // This substitution is in that immediate context, so treat diagnostics
5041 // recorded by the SFINAE trap as deduction failure instead of replaying
5042 // them as hard errors.
5043 if (Trap.hasErrorOccurred()) {
5044 if (Specialization)
5045 Specialization->setInvalidDecl(true);
5047 }
5049 return Result;
5050
5051 // If the function has a deduced return type, deduce it now, so we can check
5052 // that the deduced function type matches the requested type.
5053 if (HasDeducedReturnType && IsAddressOfFunction &&
5054 Specialization->getReturnType()->isUndeducedType() &&
5057
5058 // [C++26][expr.const]/p17
5059 // An expression or conversion is immediate-escalating if it is not initially
5060 // in an immediate function context and it is [...]
5061 // a potentially-evaluated id-expression that denotes an immediate function.
5062 if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
5063 Specialization->isImmediateEscalating() && PotentiallyEvaluated &&
5065 Info.getLocation()))
5067
5068 // Adjust the exception specification of the argument to match the
5069 // substituted and resolved type we just formed. (Calling convention and
5070 // noreturn can't be dependent, so we don't actually need this for them
5071 // right now.)
5072 QualType SpecializationType = Specialization->getType();
5073 if (!IsAddressOfFunction) {
5074 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
5075 /*AdjustExceptionSpec*/true);
5076
5077 // Revert placeholder types in the return type back to undeduced types so
5078 // that the comparison below compares the declared return types.
5079 if (HasDeducedReturnType) {
5080 SpecializationType = SubstAutoType(SpecializationType, QualType());
5081 ArgFunctionType = SubstAutoType(ArgFunctionType, QualType());
5082 }
5083 }
5084
5085 // If the requested function type does not match the actual type of the
5086 // specialization with respect to arguments of compatible pointer to function
5087 // types, template argument deduction fails.
5088 if (!ArgFunctionType.isNull()) {
5089 if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
5090 SpecializationType, ArgFunctionType)
5091 : !Context.hasSameFunctionTypeIgnoringExceptionSpec(
5092 SpecializationType, ArgFunctionType)) {
5093 Info.FirstArg = TemplateArgument(SpecializationType);
5094 Info.SecondArg = TemplateArgument(ArgFunctionType);
5096 }
5097 }
5098
5100}
5101
5103 FunctionTemplateDecl *ConversionTemplate, QualType ObjectType,
5104 Expr::Classification ObjectClassification, QualType A,
5106 if (ConversionTemplate->isInvalidDecl())
5108
5109 CXXConversionDecl *ConversionGeneric
5110 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
5111
5112 QualType P = ConversionGeneric->getConversionType();
5113 bool IsReferenceP = P->isReferenceType();
5114 bool IsReferenceA = A->isReferenceType();
5115
5116 // C++0x [temp.deduct.conv]p2:
5117 // If P is a reference type, the type referred to by P is used for
5118 // type deduction.
5119 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
5120 P = PRef->getPointeeType();
5121
5122 // C++0x [temp.deduct.conv]p4:
5123 // [...] If A is a reference type, the type referred to by A is used
5124 // for type deduction.
5125 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
5126 A = ARef->getPointeeType();
5127 // We work around a defect in the standard here: cv-qualifiers are also
5128 // removed from P and A in this case, unless P was a reference type. This
5129 // seems to mostly match what other compilers are doing.
5130 if (!IsReferenceP) {
5131 A = A.getUnqualifiedType();
5132 P = P.getUnqualifiedType();
5133 }
5134
5135 // C++ [temp.deduct.conv]p3:
5136 //
5137 // If A is not a reference type:
5138 } else {
5139 assert(!A->isReferenceType() && "Reference types were handled above");
5140
5141 // - If P is an array type, the pointer type produced by the
5142 // array-to-pointer standard conversion (4.2) is used in place
5143 // of P for type deduction; otherwise,
5144 if (P->isArrayType())
5145 P = Context.getArrayDecayedType(P);
5146 // - If P is a function type, the pointer type produced by the
5147 // function-to-pointer standard conversion (4.3) is used in
5148 // place of P for type deduction; otherwise,
5149 else if (P->isFunctionType())
5150 P = Context.getPointerType(P);
5151 // - If P is a cv-qualified type, the top level cv-qualifiers of
5152 // P's type are ignored for type deduction.
5153 else
5154 P = P.getUnqualifiedType();
5155
5156 // C++0x [temp.deduct.conv]p4:
5157 // If A is a cv-qualified type, the top level cv-qualifiers of A's
5158 // type are ignored for type deduction. If A is a reference type, the type
5159 // referred to by A is used for type deduction.
5160 A = A.getUnqualifiedType();
5161 }
5162
5163 // Unevaluated SFINAE context.
5166 SFINAETrap Trap(*this, Info);
5167
5168 // C++ [temp.deduct.conv]p1:
5169 // Template argument deduction is done by comparing the return
5170 // type of the template conversion function (call it P) with the
5171 // type that is required as the result of the conversion (call it
5172 // A) as described in 14.8.2.4.
5173 TemplateParameterList *TemplateParams
5174 = ConversionTemplate->getTemplateParameters();
5176 Deduced.resize(TemplateParams->size());
5177
5178 // C++0x [temp.deduct.conv]p4:
5179 // In general, the deduction process attempts to find template
5180 // argument values that will make the deduced A identical to
5181 // A. However, there are two cases that allow a difference:
5182 unsigned TDF = 0;
5183 // - If the original A is a reference type, A can be more
5184 // cv-qualified than the deduced A (i.e., the type referred to
5185 // by the reference)
5186 if (IsReferenceA)
5188 // - The deduced A can be another pointer or pointer to member
5189 // type that can be converted to A via a qualification
5190 // conversion.
5191 //
5192 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
5193 // both P and A are pointers or member pointers. In this case, we
5194 // just ignore cv-qualifiers completely).
5195 if ((P->isPointerType() && A->isPointerType()) ||
5197 TDF |= TDF_IgnoreQualifiers;
5198
5200 if (ConversionGeneric->isExplicitObjectMemberFunction()) {
5201 QualType ParamType = ConversionGeneric->getParamDecl(0)->getType();
5204 *this, TemplateParams, getFirstInnerIndex(ConversionTemplate),
5205 ParamType, ObjectType, ObjectClassification,
5206 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
5207 /*Decomposed*/ false, 0, /*TDF*/ 0);
5209 return Result;
5210 }
5211
5213 *this, TemplateParams, P, A, Info, Deduced, TDF,
5214 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
5215 /*HasDeducedAnyParam=*/nullptr);
5217 return Result;
5218
5219 // Create an Instantiation Scope for finalizing the operator.
5220 LocalInstantiationScope InstScope(*this);
5221 // Finish template argument deduction.
5222 FunctionDecl *ConversionSpecialized = nullptr;
5225 Result = FinishTemplateArgumentDeduction(
5226 ConversionTemplate, Deduced, 0, ConversionSpecialized, Info,
5227 &OriginalCallArgs, /*PartialOverloading=*/false,
5228 /*PartialOrdering=*/false, /*ForOverloadSetAddressResolution*/ false);
5229 });
5230 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
5231 return Result;
5232}
5233
5236 TemplateArgumentListInfo *ExplicitTemplateArgs,
5239 bool IsAddressOfFunction) {
5240 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
5241 QualType(), Specialization, Info,
5242 IsAddressOfFunction);
5243}
5244
5245namespace {
5246 struct DependentAuto { bool IsPack; };
5247
5248 /// Substitute the 'auto' specifier or deduced template specialization type
5249 /// specifier within a type for a given replacement type.
5250 class SubstituteDeducedTypeTransform :
5251 public TreeTransform<SubstituteDeducedTypeTransform> {
5252 DeducedKind DK;
5253 QualType Replacement;
5254 bool UseTypeSugar;
5256
5257 public:
5258 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
5259 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5260 DK(DA.IsPack ? DeducedKind::DeducedAsPack
5262 UseTypeSugar(true) {}
5263
5264 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
5265 bool UseTypeSugar = true)
5266 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5267 DK(Replacement.isNull() ? DeducedKind::Undeduced
5268 : DeducedKind::Deduced),
5269 Replacement(Replacement), UseTypeSugar(UseTypeSugar) {
5270 assert((!Replacement.isNull() || UseTypeSugar) &&
5271 "An undeduced auto type is never type sugar");
5272 }
5273
5274 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
5275 assert(isa<TemplateTypeParmType>(Replacement) &&
5276 "unexpected unsugared replacement kind");
5277 QualType Result = Replacement;
5278 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
5279 NewTL.setNameLoc(TL.getNameLoc());
5280 return Result;
5281 }
5282
5283 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
5284 // If we're building the type pattern to deduce against, don't wrap the
5285 // substituted type in an AutoType. Certain template deduction rules
5286 // apply only when a template type parameter appears directly (and not if
5287 // the parameter is found through desugaring). For instance:
5288 // auto &&lref = lvalue;
5289 // must transform into "rvalue reference to T" not "rvalue reference to
5290 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
5291 //
5292 // FIXME: Is this still necessary?
5293 if (!UseTypeSugar)
5294 return TransformDesugared(TLB, TL);
5295
5296 QualType Result = SemaRef.Context.getAutoType(
5297 DK, Replacement, TL.getTypePtr()->getKeyword(),
5298 TL.getTypePtr()->getTypeConstraintConcept(),
5299 TL.getTypePtr()->getTypeConstraintArguments());
5300 auto NewTL = TLB.push<AutoTypeLoc>(Result);
5301 NewTL.copy(TL);
5302 return Result;
5303 }
5304
5305 QualType TransformDeducedTemplateSpecializationType(
5306 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
5307 if (!UseTypeSugar)
5308 return TransformDesugared(TLB, TL);
5309
5311 DK, Replacement, TL.getTypePtr()->getKeyword(),
5312 TL.getTypePtr()->getTemplateName());
5313 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5314 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5315 NewTL.setNameLoc(TL.getNameLoc());
5316 NewTL.setQualifierLoc(TL.getQualifierLoc());
5317 return Result;
5318 }
5319
5320 QualType TransformAtomicType(TypeLocBuilder &TLB, AtomicTypeLoc TL) {
5321 // When building the function parameter for placeholder type deduction
5322 // (Replacement is the invented template parameter), dig through _Atomic
5323 // around an auto placeholder so deduction matches the non-atomic
5324 // argument. The _Atomic wrapper is re-applied by the final substitution
5325 // pass, which uses a concrete Replacement and falls through to the
5326 // default transform.
5327 //
5328 // This handles only the simple case where _Atomic wraps auto directly
5329 // (e.g. _Atomic(auto)), which is what the C standard currently permits.
5330 // If more complex forms such as _Atomic(auto*) are ever allowed, the
5331 // correct fix would be to treat _Atomic as a qualifier inside
5332 // DeduceTemplateArgumentsByTypeMatch instead.
5333 if (isa_and_nonnull<TemplateTypeParmType>(Replacement) &&
5335 return getDerived().TransformType(TLB, TL.getValueLoc());
5336 return inherited::TransformAtomicType(TLB, TL);
5337 }
5338
5339 ExprResult TransformLambdaExpr(LambdaExpr *E) {
5340 // Lambdas never need to be transformed.
5341 return E;
5342 }
5343 bool TransformExceptionSpec(SourceLocation Loc,
5344 FunctionProtoType::ExceptionSpecInfo &ESI,
5345 SmallVectorImpl<QualType> &Exceptions,
5346 bool &Changed) {
5347 if (ESI.Type == EST_Uninstantiated) {
5348 ESI.instantiate();
5349 Changed = true;
5350 }
5351 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
5352 }
5353
5354 QualType Apply(TypeLoc TL) {
5355 // Create some scratch storage for the transformed type locations.
5356 // FIXME: We're just going to throw this information away. Don't build it.
5357 TypeLocBuilder TLB;
5358 TLB.reserve(TL.getFullDataSize());
5359 return TransformType(TLB, TL);
5360 }
5361 };
5362
5363} // namespace
5364
5365static bool CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type,
5367 QualType Deduced) {
5368 ConstraintSatisfaction Satisfaction;
5370 cast<ConceptDecl>(Type.getTypeConstraintConcept().getAsTemplateDecl());
5371 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
5372 TypeLoc.getRAngleLoc());
5373 TemplateArgs.addArgument(
5376 Deduced, TypeLoc.getNameLoc())));
5377 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
5378 TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
5379
5381 if (S.CheckTemplateArgumentList(Concept, TypeLoc.getNameLoc(), TemplateArgs,
5382 /*DefaultArgs=*/{},
5383 /*PartialTemplateArgs=*/false, CTAI))
5384 return true;
5386 /*Final=*/true);
5388 Concept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
5389 TypeLoc.getLocalSourceRange(), Satisfaction))
5390 return true;
5391 if (!Satisfaction.IsSatisfied) {
5392 std::string Buf;
5393 llvm::raw_string_ostream OS(Buf);
5394 OS << "'" << Concept->getName();
5395 if (TypeLoc.hasExplicitTemplateArgs()) {
5396 printTemplateArgumentList(OS, Type.getTypeConstraintArguments(),
5398 Type.getTypeConstraintConcept()
5399 .getAsTemplateDecl()
5400 ->getTemplateParameters());
5401 }
5402 OS << "'";
5403 S.Diag(TypeLoc.getConceptNameLoc(),
5404 diag::err_placeholder_constraints_not_satisfied)
5405 << Deduced << Buf << TypeLoc.getLocalSourceRange();
5406 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
5407 return true;
5408 }
5409 return false;
5410}
5411
5414 TemplateDeductionInfo &Info, bool DependentDeduction,
5415 bool IgnoreConstraints,
5416 TemplateSpecCandidateSet *FailedTSC) {
5417 assert(DependentDeduction || Info.getDeducedDepth() == 0);
5418 if (Init->containsErrors())
5420
5421 const AutoType *AT = Type.getType()->getContainedAutoType();
5422 assert(AT);
5423
5424 if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
5425 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
5426 if (NonPlaceholder.isInvalid())
5428 Init = NonPlaceholder.get();
5429 }
5430
5431 DependentAuto DependentResult = {
5432 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
5433
5434 if (!DependentDeduction &&
5435 (Type.getType()->isDependentType() || Init->isTypeDependent() ||
5436 Init->containsUnexpandedParameterPack())) {
5437 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5438 assert(!Result.isNull() && "substituting DependentTy can't fail");
5440 }
5441
5442 auto *InitList = dyn_cast<InitListExpr>(Init);
5443 bool IsArrayType = Type.getType()->isArrayType();
5444 if (!getLangOpts().CPlusPlus && (InitList || IsArrayType)) {
5445 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c)
5446 << (int)AT->getKeyword() << IsArrayType;
5448 }
5449
5450 // Emit a warning if 'auto*' is used in pedantic and in C23 mode.
5451 if (getLangOpts().C23 && Type.getType()->isPointerType()) {
5452 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5453 }
5454
5455 // Deduce type of TemplParam in Func(Init)
5457 Deduced.resize(1);
5458
5459 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
5460
5461 QualType DeducedType;
5462 // If this is a 'decltype(auto)' specifier, do the decltype dance.
5463 if (AT->isDecltypeAuto()) {
5464 if (InitList) {
5465 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
5467 }
5468
5469 DeducedType = getDecltypeForExpr(Init);
5470 assert(!DeducedType.isNull());
5471 } else {
5472 LocalInstantiationScope InstScope(*this);
5473
5474 // Build template<class TemplParam> void Func(FuncParam);
5475 SourceLocation Loc = Init->getExprLoc();
5477 Context, nullptr, SourceLocation(), Loc, Info.getDeducedDepth(), 0,
5478 nullptr, false, false, false);
5479 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
5480 NamedDecl *TemplParamPtr = TemplParam;
5482 Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
5483
5484 if (InitList) {
5485 // Notionally, we substitute std::initializer_list<T> for 'auto' and
5486 // deduce against that. Such deduction only succeeds if removing
5487 // cv-qualifiers and references results in std::initializer_list<T>.
5488 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
5490
5491 SourceRange DeducedFromInitRange;
5492 for (Expr *Init : InitList->inits()) {
5493 // Resolving a core issue: a braced-init-list containing any designators
5494 // is a non-deduced context.
5498 *this, TemplateParamsSt.get(), 0, TemplArg, Init->getType(),
5499 Init->Classify(getASTContext()), Init, Info, Deduced,
5500 OriginalCallArgs,
5501 /*Decomposed=*/true,
5502 /*ArgIdx=*/0, /*TDF=*/0);
5505 Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction)
5506 << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
5507 << Init->getSourceRange();
5509 }
5510 return TDK;
5511 }
5512
5513 if (DeducedFromInitRange.isInvalid() &&
5514 Deduced[0].getKind() != TemplateArgument::Null)
5515 DeducedFromInitRange = Init->getSourceRange();
5516 }
5517 } else {
5518 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
5519 Diag(Loc, diag::err_auto_bitfield);
5521 }
5522 QualType FuncParam =
5523 SubstituteDeducedTypeTransform(*this, TemplArg).Apply(Type);
5524 assert(!FuncParam.isNull() &&
5525 "substituting template parameter for 'auto' failed");
5527 *this, TemplateParamsSt.get(), 0, FuncParam, Init->getType(),
5528 Init->Classify(getASTContext()), Init, Info, Deduced,
5529 OriginalCallArgs,
5530 /*Decomposed=*/false, /*ArgIdx=*/0, /*TDF=*/0, FailedTSC);
5532 return TDK;
5533 }
5534
5535 // Could be null if somehow 'auto' appears in a non-deduced context.
5538 DeducedType = Deduced[0].getAsType();
5539
5540 if (InitList) {
5541 DeducedType = BuildStdInitializerList(DeducedType, Loc);
5542 if (DeducedType.isNull())
5544 }
5545 }
5546
5547 if (!Result.isNull()) {
5548 if (!Context.hasSameType(DeducedType, Result)) {
5549 Info.FirstArg = Result;
5550 Info.SecondArg = DeducedType;
5552 }
5553 DeducedType = Context.getCommonSugaredType(Result, DeducedType);
5554 }
5555
5556 if (AT->isConstrained() && !IgnoreConstraints &&
5558 *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType))
5560
5561 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
5562 if (Result.isNull())
5564
5565 // Check that the deduced argument type is compatible with the original
5566 // argument type per C++ [temp.deduct.call]p4.
5567 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
5568 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
5569 assert((bool)InitList == OriginalArg.DecomposedParam &&
5570 "decomposed non-init-list in auto deduction?");
5571 if (auto TDK =
5572 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
5574 Result = QualType();
5575 return TDK;
5576 }
5577 }
5578
5580}
5581
5583 QualType TypeToReplaceAuto) {
5584 assert(TypeToReplaceAuto != Context.DependentTy);
5585 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5586 .TransformType(TypeWithAuto);
5587}
5588
5590 QualType TypeToReplaceAuto) {
5591 assert(TypeToReplaceAuto != Context.DependentTy);
5592 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5593 .TransformType(TypeWithAuto);
5594}
5595
5597 return SubstituteDeducedTypeTransform(
5598 *this,
5599 DependentAuto{/*IsPack=*/isa<PackExpansionType>(TypeWithAuto)})
5600 .TransformType(TypeWithAuto);
5601}
5602
5605 return SubstituteDeducedTypeTransform(
5606 *this, DependentAuto{/*IsPack=*/isa<PackExpansionType>(
5607 TypeWithAuto->getType())})
5608 .TransformType(TypeWithAuto);
5609}
5610
5612 QualType TypeToReplaceAuto) {
5613 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5614 /*UseTypeSugar*/ false)
5615 .TransformType(TypeWithAuto);
5616}
5617
5619 QualType TypeToReplaceAuto) {
5620 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5621 /*UseTypeSugar*/ false)
5622 .TransformType(TypeWithAuto);
5623}
5624
5626 const Expr *Init) {
5628 Diag(VDecl->getLocation(),
5629 VDecl->isInitCapture()
5630 ? diag::err_init_capture_deduction_failure_from_init_list
5631 : diag::err_auto_var_deduction_failure_from_init_list)
5632 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
5633 else
5634 Diag(VDecl->getLocation(),
5635 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
5636 : diag::err_auto_var_deduction_failure)
5637 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5638 << Init->getSourceRange();
5639}
5640
5642 bool Diagnose) {
5643 assert(FD->getReturnType()->isUndeducedType());
5644
5645 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
5646 // within the return type from the call operator's type.
5648 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5649 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5650
5651 // For a generic lambda, instantiate the call operator if needed.
5652 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5654 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5655 if (!CallOp || CallOp->isInvalidDecl())
5656 return true;
5657
5658 // We might need to deduce the return type by instantiating the definition
5659 // of the operator() function.
5660 if (CallOp->getReturnType()->isUndeducedType()) {
5662 InstantiateFunctionDefinition(Loc, CallOp);
5663 });
5664 }
5665 }
5666
5667 if (CallOp->isInvalidDecl())
5668 return true;
5669 assert(!CallOp->getReturnType()->isUndeducedType() &&
5670 "failed to deduce lambda return type");
5671
5672 // Build the new return type from scratch.
5673 CallingConv RetTyCC = FD->getReturnType()
5674 ->getPointeeType()
5675 ->castAs<FunctionType>()
5676 ->getCallConv();
5678 CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
5679 if (FD->getReturnType()->getAs<PointerType>())
5680 RetType = Context.getPointerType(RetType);
5681 else {
5682 assert(FD->getReturnType()->getAs<BlockPointerType>());
5683 RetType = Context.getBlockPointerType(RetType);
5684 }
5685 Context.adjustDeducedFunctionResultType(FD, RetType);
5686 return false;
5687 }
5688
5692 });
5693 }
5694
5695 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
5696 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
5697 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
5698 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
5699 }
5700
5701 return StillUndeduced;
5702}
5703
5705 SourceLocation Loc) {
5706 assert(FD->isImmediateEscalating());
5707
5709 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5710 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5711
5712 // For a generic lambda, instantiate the call operator if needed.
5713 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5715 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5716 if (!CallOp || CallOp->isInvalidDecl())
5717 return true;
5719 Loc, [&] { InstantiateFunctionDefinition(Loc, CallOp); });
5720 }
5721 return CallOp->isInvalidDecl();
5722 }
5723
5726 Loc, [&] { InstantiateFunctionDefinition(Loc, FD); });
5727 }
5728 return false;
5729}
5730
5732 const CXXMethodDecl *Method,
5733 QualType RawType,
5734 bool IsOtherRvr) {
5735 // C++20 [temp.func.order]p3.1, p3.2:
5736 // - The type X(M) is "rvalue reference to cv A" if the optional
5737 // ref-qualifier of M is && or if M has no ref-qualifier and the
5738 // positionally-corresponding parameter of the other transformed template
5739 // has rvalue reference type; if this determination depends recursively
5740 // upon whether X(M) is an rvalue reference type, it is not considered to
5741 // have rvalue reference type.
5742 //
5743 // - Otherwise, X(M) is "lvalue reference to cv A".
5744 assert(Method && !Method->isExplicitObjectMemberFunction() &&
5745 "expected a member function with no explicit object parameter");
5746
5747 RawType = Context.getQualifiedType(RawType, Method->getMethodQualifiers());
5748 if (Method->getRefQualifier() == RQ_RValue ||
5749 (IsOtherRvr && Method->getRefQualifier() == RQ_None))
5750 return Context.getRValueReferenceType(RawType);
5751 return Context.getLValueReferenceType(RawType);
5752}
5753
5756 QualType A, ArrayRef<TemplateArgument> DeducedArgs, bool CheckConsistency) {
5757 MultiLevelTemplateArgumentList MLTAL(FTD, DeducedArgs,
5758 /*Final=*/true);
5760 S,
5761 ArgIdx ? ::getPackIndexForParam(S, FTD, MLTAL, *ArgIdx) : std::nullopt);
5762 bool IsIncompleteSubstitution = false;
5763 // FIXME: A substitution can be incomplete on a non-structural part of the
5764 // type. Use the canonical type for now, until the TemplateInstantiator can
5765 // deal with that.
5766
5767 // Workaround: Implicit deduction guides use InjectedClassNameTypes, whereas
5768 // the explicit guides don't. The substitution doesn't transform these types,
5769 // so let it transform their specializations instead.
5770 bool IsDeductionGuide = isa<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
5771 if (IsDeductionGuide) {
5772 if (auto *Injected = P->getAsCanonical<InjectedClassNameType>())
5773 P = Injected->getDecl()->getCanonicalTemplateSpecializationType(
5774 S.Context);
5775 }
5776 QualType InstP = S.SubstType(P.getCanonicalType(), MLTAL, FTD->getLocation(),
5777 FTD->getDeclName(), &IsIncompleteSubstitution);
5778 if (InstP.isNull() && !IsIncompleteSubstitution)
5780 if (!CheckConsistency)
5782 if (IsIncompleteSubstitution)
5784
5785 // [temp.deduct.call]/4 - Check we produced a consistent deduction.
5786 // This handles just the cases that can appear when partial ordering.
5787 if (auto *PA = dyn_cast<PackExpansionType>(A);
5788 PA && !isa<PackExpansionType>(InstP))
5789 A = PA->getPattern();
5792 if (IsDeductionGuide) {
5793 if (auto *Injected = T1->getAsCanonical<InjectedClassNameType>())
5794 T1 = Injected->getDecl()->getCanonicalTemplateSpecializationType(
5795 S.Context);
5796 if (auto *Injected = T2->getAsCanonical<InjectedClassNameType>())
5797 T2 = Injected->getDecl()->getCanonicalTemplateSpecializationType(
5798 S.Context);
5799 }
5800 if (!S.Context.hasSameType(T1, T2))
5803}
5804
5805template <class T>
5807 Sema &S, FunctionTemplateDecl *FTD,
5810 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(FTD));
5811
5812 // C++26 [temp.deduct.type]p2:
5813 // [...] or if any template argument remains neither deduced nor
5814 // explicitly specified, template argument deduction fails.
5815 bool IsIncomplete = false;
5816 Sema::CheckTemplateArgumentInfo CTAI(/*PartialOrdering=*/true);
5818 S, FTD, FTD->getTemplateParameters(), /*IsDeduced=*/true, Deduced,
5819 Info, CTAI,
5820 /*CurrentInstantiationScope=*/nullptr,
5821 /*NumAlreadyConverted=*/0, &IsIncomplete);
5823 return Result;
5824
5825 // Form the template argument list from the deduced template arguments.
5826 TemplateArgumentList *SugaredDeducedArgumentList =
5828 TemplateArgumentList *CanonicalDeducedArgumentList =
5830
5831 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
5832
5833 // Substitute the deduced template arguments into the argument
5834 // and verify that the instantiated argument is both valid
5835 // and equivalent to the parameter.
5836 LocalInstantiationScope InstScope(S);
5837 return CheckDeductionConsistency(S, FTD, CTAI.SugaredConverted);
5838}
5839
5840/// Determine whether the function template \p FT1 is at least as
5841/// specialized as \p FT2.
5845 ArrayRef<QualType> Args1, ArrayRef<QualType> Args2, bool Args1Offset) {
5846 FunctionDecl *FD1 = FT1->getTemplatedDecl();
5847 FunctionDecl *FD2 = FT2->getTemplatedDecl();
5848 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
5849 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
5850 assert(Proto1 && Proto2 && "Function templates must have prototypes");
5851
5852 // C++26 [temp.deduct.partial]p3:
5853 // The types used to determine the ordering depend on the context in which
5854 // the partial ordering is done:
5855 // - In the context of a function call, the types used are those function
5856 // parameter types for which the function call has arguments.
5857 // - In the context of a call to a conversion operator, the return types
5858 // of the conversion function templates are used.
5859 // - In other contexts (14.6.6.2) the function template's function type
5860 // is used.
5861
5862 if (TPOC == TPOC_Other) {
5863 // We wouldn't be partial ordering these candidates if these didn't match.
5864 assert(Proto1->getMethodQuals() == Proto2->getMethodQuals() &&
5865 Proto1->getRefQualifier() == Proto2->getRefQualifier() &&
5866 Proto1->isVariadic() == Proto2->isVariadic() &&
5867 "shouldn't partial order functions with different qualifiers in a "
5868 "context where the function type is used");
5869
5870 assert(Args1.empty() && Args2.empty() &&
5871 "Only call context should have arguments");
5872 Args1 = Proto1->getParamTypes();
5873 Args2 = Proto2->getParamTypes();
5874 }
5875
5876 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
5878 TemplateDeductionInfo Info(Loc);
5879
5880 bool HasDeducedAnyParamFromReturnType = false;
5881 if (TPOC != TPOC_Call) {
5883 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
5885 /*DeducedFromArrayBound=*/false,
5886 &HasDeducedAnyParamFromReturnType) !=
5888 return false;
5889 }
5890
5891 llvm::SmallBitVector HasDeducedParam;
5892 if (TPOC != TPOC_Conversion) {
5893 HasDeducedParam.resize(Args2.size());
5894 if (DeduceTemplateArguments(S, TemplateParams, Args2, Args1, Info, Deduced,
5896 /*HasDeducedAnyParam=*/nullptr,
5897 &HasDeducedParam) !=
5899 return false;
5900 }
5901
5902 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
5905 Sema::SFINAETrap Trap(S, Info);
5907 S, Info.getLocation(), FT2, DeducedArgs,
5909 if (Inst.isInvalid())
5910 return false;
5911
5912 bool AtLeastAsSpecialized;
5914 AtLeastAsSpecialized =
5915 ::FinishTemplateArgumentDeduction(
5916 S, FT2, Deduced, Info,
5917 [&](Sema &S, FunctionTemplateDecl *FTD,
5918 ArrayRef<TemplateArgument> DeducedArgs) {
5919 // As a provisional fix for a core issue that does not
5920 // exist yet, which may be related to CWG2160, only check the
5921 // consistency of parameters and return types which participated
5922 // in deduction. We will still try to substitute them though.
5923 if (TPOC != TPOC_Call) {
5924 if (auto TDR = ::CheckDeductionConsistency(
5925 S, FTD, /*ArgIdx=*/std::nullopt,
5926 Proto2->getReturnType(), Proto1->getReturnType(),
5927 DeducedArgs,
5928 /*CheckConsistency=*/HasDeducedAnyParamFromReturnType);
5929 TDR != TemplateDeductionResult::Success)
5930 return TDR;
5931 }
5932
5933 if (TPOC == TPOC_Conversion)
5934 return TemplateDeductionResult::Success;
5935
5936 return ::DeduceForEachType(
5937 S, TemplateParams, Args2, Args1, Info, Deduced,
5938 PartialOrderingKind::Call, /*FinishingDeduction=*/true,
5939 [&](Sema &S, TemplateParameterList *, int ParamIdx,
5940 UnsignedOrNone ArgIdx, QualType P, QualType A,
5941 TemplateDeductionInfo &Info,
5942 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5943 PartialOrderingKind) {
5944 if (ArgIdx && *ArgIdx >= static_cast<unsigned>(Args1Offset))
5945 ArgIdx = *ArgIdx - Args1Offset;
5946 else
5947 ArgIdx = std::nullopt;
5948 return ::CheckDeductionConsistency(
5949 S, FTD, ArgIdx, P, A, DeducedArgs,
5950 /*CheckConsistency=*/HasDeducedParam[ParamIdx]);
5951 });
5953 });
5954 if (!AtLeastAsSpecialized || Trap.hasErrorOccurred())
5955 return false;
5956
5957 // C++0x [temp.deduct.partial]p11:
5958 // In most cases, all template parameters must have values in order for
5959 // deduction to succeed, but for partial ordering purposes a template
5960 // parameter may remain without a value provided it is not used in the
5961 // types being used for partial ordering. [ Note: a template parameter used
5962 // in a non-deduced context is considered used. -end note]
5963 unsigned ArgIdx = 0, NumArgs = Deduced.size();
5964 for (; ArgIdx != NumArgs; ++ArgIdx)
5965 if (Deduced[ArgIdx].isNull())
5966 break;
5967
5968 if (ArgIdx == NumArgs) {
5969 // All template arguments were deduced. FT1 is at least as specialized
5970 // as FT2.
5971 return true;
5972 }
5973
5974 // Figure out which template parameters were used.
5975 llvm::SmallBitVector UsedParameters(TemplateParams->size());
5976 switch (TPOC) {
5977 case TPOC_Call:
5978 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
5979 ::MarkUsedTemplateParameters(S.Context, Args2[I], /*OnlyDeduced=*/false,
5980 TemplateParams->getDepth(), UsedParameters);
5981 break;
5982
5983 case TPOC_Conversion:
5984 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(),
5985 /*OnlyDeduced=*/false,
5986 TemplateParams->getDepth(), UsedParameters);
5987 break;
5988
5989 case TPOC_Other:
5990 // We do not deduce template arguments from the exception specification
5991 // when determining the primary template of a function template
5992 // specialization or when taking the address of a function template.
5993 // Therefore, we do not mark template parameters in the exception
5994 // specification as used during partial ordering to prevent the following
5995 // from being ambiguous:
5996 //
5997 // template<typename T, typename U>
5998 // void f(U) noexcept(noexcept(T())); // #1
5999 //
6000 // template<typename T>
6001 // void f(T*) noexcept; // #2
6002 //
6003 // template<>
6004 // void f<int>(int*) noexcept; // explicit specialization of #2
6005 //
6006 // Although there is no corresponding wording in the standard, this seems
6007 // to be the intended behavior given the definition of
6008 // 'deduction substitution loci' in [temp.deduct].
6010 S.Context,
6011 S.Context.getFunctionTypeWithExceptionSpec(FD2->getType(), EST_None),
6012 /*OnlyDeduced=*/false, TemplateParams->getDepth(), UsedParameters);
6013 break;
6014 }
6015
6016 for (; ArgIdx != NumArgs; ++ArgIdx)
6017 // If this argument had no value deduced but was used in one of the types
6018 // used for partial ordering, then deduction fails.
6019 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
6020 return false;
6021
6022 return true;
6023}
6024
6026
6027// This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
6028// there is no wording or even resolution for this issue.
6031 const TemplateSpecializationType *TST1,
6032 const TemplateSpecializationType *TST2) {
6033 ArrayRef<TemplateArgument> As1 = TST1->template_arguments(),
6034 As2 = TST2->template_arguments();
6035 const TemplateArgument &TA1 = As1.back(), &TA2 = As2.back();
6036 bool IsPack = TA1.getKind() == TemplateArgument::Pack;
6037 assert(IsPack == (TA2.getKind() == TemplateArgument::Pack));
6038 if (!IsPack)
6040 assert(As1.size() == As2.size());
6041
6042 unsigned PackSize1 = TA1.pack_size(), PackSize2 = TA2.pack_size();
6043 bool IsPackExpansion1 =
6044 PackSize1 && TA1.pack_elements().back().isPackExpansion();
6045 bool IsPackExpansion2 =
6046 PackSize2 && TA2.pack_elements().back().isPackExpansion();
6047 if (PackSize1 == PackSize2 && IsPackExpansion1 == IsPackExpansion2)
6049 if (PackSize1 > PackSize2 && IsPackExpansion1)
6051 if (PackSize1 < PackSize2 && IsPackExpansion2)
6054}
6055
6058 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
6059 QualType RawObj1Ty, QualType RawObj2Ty, bool Reversed,
6060 bool PartialOverloading) {
6063 const FunctionDecl *FD1 = FT1->getTemplatedDecl();
6064 const FunctionDecl *FD2 = FT2->getTemplatedDecl();
6065 bool ShouldConvert1 = false;
6066 bool ShouldConvert2 = false;
6067 bool Args1Offset = false;
6068 bool Args2Offset = false;
6069 QualType Obj1Ty;
6070 QualType Obj2Ty;
6071 if (TPOC == TPOC_Call) {
6072 const FunctionProtoType *Proto1 =
6073 FD1->getType()->castAs<FunctionProtoType>();
6074 const FunctionProtoType *Proto2 =
6075 FD2->getType()->castAs<FunctionProtoType>();
6076
6077 // - In the context of a function call, the function parameter types are
6078 // used.
6079 const CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
6080 const CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
6081 // C++20 [temp.func.order]p3
6082 // [...] Each function template M that is a member function is
6083 // considered to have a new first parameter of type
6084 // X(M), described below, inserted in its function parameter list.
6085 //
6086 // Note that we interpret "that is a member function" as
6087 // "that is a member function with no expicit object argument".
6088 // Otherwise the ordering rules for methods with expicit objet arguments
6089 // against anything else make no sense.
6090
6091 bool NonStaticMethod1 = Method1 && !Method1->isStatic(),
6092 NonStaticMethod2 = Method2 && !Method2->isStatic();
6093
6094 auto Params1Begin = Proto1->param_type_begin(),
6095 Params2Begin = Proto2->param_type_begin();
6096
6097 size_t NumComparedArguments = NumCallArguments1;
6098
6099 if (auto OO = FD1->getOverloadedOperator();
6100 (NonStaticMethod1 && NonStaticMethod2) ||
6101 (OO != OO_None && OO != OO_Call && OO != OO_Subscript)) {
6102 ShouldConvert1 =
6103 NonStaticMethod1 && !Method1->hasCXXExplicitFunctionObjectParameter();
6104 ShouldConvert2 =
6105 NonStaticMethod2 && !Method2->hasCXXExplicitFunctionObjectParameter();
6106 NumComparedArguments += 1;
6107
6108 if (ShouldConvert1) {
6109 bool IsRValRef2 =
6110 ShouldConvert2
6111 ? Method2->getRefQualifier() == RQ_RValue
6112 : Proto2->param_type_begin()[0]->isRValueReferenceType();
6113 // Compare 'this' from Method1 against first parameter from Method2.
6114 Obj1Ty = GetImplicitObjectParameterType(this->Context, Method1,
6115 RawObj1Ty, IsRValRef2);
6116 Args1.push_back(Obj1Ty);
6117 Args1Offset = true;
6118 }
6119 if (ShouldConvert2) {
6120 bool IsRValRef1 =
6121 ShouldConvert1
6122 ? Method1->getRefQualifier() == RQ_RValue
6123 : Proto1->param_type_begin()[0]->isRValueReferenceType();
6124 // Compare 'this' from Method2 against first parameter from Method1.
6125 Obj2Ty = GetImplicitObjectParameterType(this->Context, Method2,
6126 RawObj2Ty, IsRValRef1);
6127 Args2.push_back(Obj2Ty);
6128 Args2Offset = true;
6129 }
6130 } else {
6131 if (NonStaticMethod1 && Method1->hasCXXExplicitFunctionObjectParameter())
6132 Params1Begin += 1;
6133 if (NonStaticMethod2 && Method2->hasCXXExplicitFunctionObjectParameter())
6134 Params2Begin += 1;
6135 }
6136 Args1.insert(Args1.end(), Params1Begin, Proto1->param_type_end());
6137 Args2.insert(Args2.end(), Params2Begin, Proto2->param_type_end());
6138
6139 // C++ [temp.func.order]p5:
6140 // The presence of unused ellipsis and default arguments has no effect on
6141 // the partial ordering of function templates.
6142 Args1.resize(std::min(Args1.size(), NumComparedArguments));
6143 Args2.resize(std::min(Args2.size(), NumComparedArguments));
6144
6145 if (Reversed)
6146 std::reverse(Args2.begin(), Args2.end());
6147 } else {
6148 assert(!Reversed && "Only call context could have reversed arguments");
6149 }
6150 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, Args1,
6151 Args2, Args2Offset);
6152 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, Args2,
6153 Args1, Args1Offset);
6154 // C++ [temp.deduct.partial]p10:
6155 // F is more specialized than G if F is at least as specialized as G and G
6156 // is not at least as specialized as F.
6157 if (Better1 != Better2) // We have a clear winner
6158 return Better1 ? FT1 : FT2;
6159
6160 if (!Better1 && !Better2) // Neither is better than the other
6161 return nullptr;
6162
6163 // C++ [temp.deduct.partial]p11:
6164 // ... and if G has a trailing function parameter pack for which F does not
6165 // have a corresponding parameter, and if F does not have a trailing
6166 // function parameter pack, then F is more specialized than G.
6167
6168 SmallVector<QualType> Param1;
6169 Param1.reserve(FD1->param_size() + ShouldConvert1);
6170 if (ShouldConvert1)
6171 Param1.push_back(Obj1Ty);
6172 for (const auto &P : FD1->parameters())
6173 Param1.push_back(P->getType());
6174
6175 SmallVector<QualType> Param2;
6176 Param2.reserve(FD2->param_size() + ShouldConvert2);
6177 if (ShouldConvert2)
6178 Param2.push_back(Obj2Ty);
6179 for (const auto &P : FD2->parameters())
6180 Param2.push_back(P->getType());
6181
6182 unsigned NumParams1 = Param1.size();
6183 unsigned NumParams2 = Param2.size();
6184
6185 bool Variadic1 =
6186 FD1->param_size() && FD1->parameters().back()->isParameterPack();
6187 bool Variadic2 =
6188 FD2->param_size() && FD2->parameters().back()->isParameterPack();
6189 if (Variadic1 != Variadic2) {
6190 if (Variadic1 && NumParams1 > NumParams2)
6191 return FT2;
6192 if (Variadic2 && NumParams2 > NumParams1)
6193 return FT1;
6194 }
6195
6196 // Skip this tie breaker if we are performing overload resolution with partial
6197 // arguments, as this breaks some assumptions about how closely related the
6198 // candidates are.
6199 for (int i = 0, e = std::min(NumParams1, NumParams2);
6200 !PartialOverloading && i < e; ++i) {
6201 QualType T1 = Param1[i].getCanonicalType();
6202 QualType T2 = Param2[i].getCanonicalType();
6203 auto *TST1 = dyn_cast<TemplateSpecializationType>(T1);
6204 auto *TST2 = dyn_cast<TemplateSpecializationType>(T2);
6205 if (!TST1 || !TST2)
6206 continue;
6207 switch (getMoreSpecializedTrailingPackTieBreaker(TST1, TST2)) {
6209 return FT1;
6211 return FT2;
6213 continue;
6214 }
6215 llvm_unreachable(
6216 "unknown MoreSpecializedTrailingPackTieBreakerResult value");
6217 }
6218
6219 if (!Context.getLangOpts().CPlusPlus20)
6220 return nullptr;
6221
6222 // Match GCC on not implementing [temp.func.order]p6.2.1.
6223
6224 // C++20 [temp.func.order]p6:
6225 // If deduction against the other template succeeds for both transformed
6226 // templates, constraints can be considered as follows:
6227
6228 // C++20 [temp.func.order]p6.1:
6229 // If their template-parameter-lists (possibly including template-parameters
6230 // invented for an abbreviated function template ([dcl.fct])) or function
6231 // parameter lists differ in length, neither template is more specialized
6232 // than the other.
6235 if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
6236 return nullptr;
6237
6238 // C++20 [temp.func.order]p6.2.2:
6239 // Otherwise, if the corresponding template-parameters of the
6240 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6241 // function parameters that positionally correspond between the two
6242 // templates are not of the same type, neither template is more specialized
6243 // than the other.
6244 if (!TemplateParameterListsAreEqual(TPL1, TPL2, false,
6246 return nullptr;
6247
6248 // [dcl.fct]p5:
6249 // Any top-level cv-qualifiers modifying a parameter type are deleted when
6250 // forming the function type.
6251 for (unsigned i = 0; i < NumParams1; ++i)
6252 if (!Context.hasSameUnqualifiedType(Param1[i], Param2[i]))
6253 return nullptr;
6254
6255 // C++20 [temp.func.order]p6.3:
6256 // Otherwise, if the context in which the partial ordering is done is
6257 // that of a call to a conversion function and the return types of the
6258 // templates are not the same, then neither template is more specialized
6259 // than the other.
6260 if (TPOC == TPOC_Conversion &&
6261 !Context.hasSameType(FD1->getReturnType(), FD2->getReturnType()))
6262 return nullptr;
6263
6265 FT1->getAssociatedConstraints(AC1);
6266 FT2->getAssociatedConstraints(AC2);
6267 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6268 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
6269 return nullptr;
6270 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
6271 return nullptr;
6272 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6273 return nullptr;
6274 return AtLeastAsConstrained1 ? FT1 : FT2;
6275}
6276
6279 TemplateSpecCandidateSet &FailedCandidates,
6280 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
6281 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
6282 bool Complain, QualType TargetType) {
6283 if (SpecBegin == SpecEnd) {
6284 if (Complain) {
6285 Diag(Loc, NoneDiag);
6286 FailedCandidates.NoteCandidates(*this, Loc);
6287 }
6288 return SpecEnd;
6289 }
6290
6291 if (SpecBegin + 1 == SpecEnd)
6292 return SpecBegin;
6293
6294 // Find the function template that is better than all of the templates it
6295 // has been compared to.
6296 UnresolvedSetIterator Best = SpecBegin;
6297 FunctionTemplateDecl *BestTemplate
6298 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
6299 assert(BestTemplate && "Not a function template specialization?");
6300 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
6301 FunctionTemplateDecl *Challenger
6302 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6303 assert(Challenger && "Not a function template specialization?");
6304 if (declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6305 Loc, TPOC_Other, 0),
6306 Challenger)) {
6307 Best = I;
6308 BestTemplate = Challenger;
6309 }
6310 }
6311
6312 // Make sure that the "best" function template is more specialized than all
6313 // of the others.
6314 bool Ambiguous = false;
6315 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6316 FunctionTemplateDecl *Challenger
6317 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6318 if (I != Best &&
6319 !declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6320 Loc, TPOC_Other, 0),
6321 BestTemplate)) {
6322 Ambiguous = true;
6323 break;
6324 }
6325 }
6326
6327 if (!Ambiguous) {
6328 // We found an answer. Return it.
6329 return Best;
6330 }
6331
6332 // Diagnose the ambiguity.
6333 if (Complain) {
6334 Diag(Loc, AmbigDiag);
6335
6336 // FIXME: Can we order the candidates in some sane way?
6337 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6338 PartialDiagnostic PD = CandidateDiag;
6339 const auto *FD = cast<FunctionDecl>(*I);
6341 FD->getPrimaryTemplate()->getTemplateParameters(),
6342 *FD->getTemplateSpecializationArgs());
6343 if (!TargetType.isNull())
6344 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
6345 Diag((*I)->getLocation(), PD);
6346 }
6347 }
6348
6349 return SpecEnd;
6350}
6351
6353 FunctionDecl *FD2) {
6354 assert(!FD1->getDescribedTemplate() && !FD2->getDescribedTemplate() &&
6355 "not for function templates");
6356 assert(!FD1->isFunctionTemplateSpecialization() ||
6358 assert(!FD2->isFunctionTemplateSpecialization() ||
6360
6361 FunctionDecl *F1 = FD1;
6362 if (FunctionDecl *P = FD1->getTemplateInstantiationPattern(false))
6363 F1 = P;
6364
6365 FunctionDecl *F2 = FD2;
6366 if (FunctionDecl *P = FD2->getTemplateInstantiationPattern(false))
6367 F2 = P;
6368
6370 F1->getAssociatedConstraints(AC1);
6371 F2->getAssociatedConstraints(AC2);
6372 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6373 if (IsAtLeastAsConstrained(F1, AC1, F2, AC2, AtLeastAsConstrained1))
6374 return nullptr;
6375 if (IsAtLeastAsConstrained(F2, AC2, F1, AC1, AtLeastAsConstrained2))
6376 return nullptr;
6377 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6378 return nullptr;
6379 return AtLeastAsConstrained1 ? FD1 : FD2;
6380}
6381
6382/// Determine whether one template specialization, P1, is at least as
6383/// specialized than another, P2.
6384///
6385/// \tparam TemplateLikeDecl The kind of P2, which must be a
6386/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
6387/// \param T1 The injected-class-name of P1 (faked for a variable template).
6388/// \param T2 The injected-class-name of P2 (faked for a variable template).
6389/// \param Template The primary template of P2, in case it is a partial
6390/// specialization, the same as P2 otherwise.
6391template <typename TemplateLikeDecl>
6393 TemplateLikeDecl *P2,
6395 TemplateDeductionInfo &Info) {
6396 // C++ [temp.class.order]p1:
6397 // For two class template partial specializations, the first is at least as
6398 // specialized as the second if, given the following rewrite to two
6399 // function templates, the first function template is at least as
6400 // specialized as the second according to the ordering rules for function
6401 // templates (14.6.6.2):
6402 // - the first function template has the same template parameters as the
6403 // first partial specialization and has a single function parameter
6404 // whose type is a class template specialization with the template
6405 // arguments of the first partial specialization, and
6406 // - the second function template has the same template parameters as the
6407 // second partial specialization and has a single function parameter
6408 // whose type is a class template specialization with the template
6409 // arguments of the second partial specialization.
6410 //
6411 // Rather than synthesize function templates, we merely perform the
6412 // equivalent partial ordering by performing deduction directly on
6413 // the template arguments of the class template partial
6414 // specializations. This computation is slightly simpler than the
6415 // general problem of function template partial ordering, because
6416 // class template partial specializations are more constrained. We
6417 // know that every template parameter is deducible from the class
6418 // template partial specialization's template arguments, for
6419 // example.
6421
6422 // Determine whether P1 is at least as specialized as P2.
6423 Deduced.resize(P2->getTemplateParameters()->size());
6425 S, P2->getTemplateParameters(), T2, T1, Info, Deduced, TDF_None,
6426 PartialOrderingKind::Call, /*DeducedFromArrayBound=*/false,
6427 /*HasDeducedAnyParam=*/nullptr) != TemplateDeductionResult::Success)
6428 return false;
6429
6430 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
6433 Sema::SFINAETrap Trap(S, Info);
6434 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs);
6435 if (Inst.isInvalid())
6436 return false;
6437
6439 Ps = cast<TemplateSpecializationType>(T2)->template_arguments(),
6440 As = cast<TemplateSpecializationType>(T1)->template_arguments();
6441
6444 Result = ::FinishTemplateArgumentDeduction(
6445 S, P2, P2->getTemplateParameters(), Template,
6446 /*IsPartialOrdering=*/true, Ps, As, Deduced, Info,
6447 /*CopyDeducedArgs=*/false);
6448 });
6450}
6451
6452namespace {
6453// A dummy class to return nullptr instead of P2 when performing "more
6454// specialized than primary" check.
6455struct GetP2 {
6456 template <typename T1, typename T2,
6457 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6458 T2 *operator()(T1 *, T2 *P2) {
6459 return P2;
6460 }
6461 template <typename T1, typename T2,
6462 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6463 T1 *operator()(T1 *, T2 *) {
6464 return nullptr;
6465 }
6466};
6467
6468// The assumption is that two template argument lists have the same size.
6469struct TemplateArgumentListAreEqual {
6470 ASTContext &Ctx;
6471 TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
6472
6473 template <typename T1, typename T2,
6474 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6475 bool operator()(T1 *PS1, T2 *PS2) {
6476 ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
6477 Args2 = PS2->getTemplateArgs().asArray();
6478
6479 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6480 // We use profile, instead of structural comparison of the arguments,
6481 // because canonicalization can't do the right thing for dependent
6482 // expressions.
6483 llvm::FoldingSetNodeID IDA, IDB;
6484 Args1[I].Profile(IDA, Ctx);
6485 Args2[I].Profile(IDB, Ctx);
6486 if (IDA != IDB)
6487 return false;
6488 }
6489 return true;
6490 }
6491
6492 template <typename T1, typename T2,
6493 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6494 bool operator()(T1 *Spec, T2 *Primary) {
6495 ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
6496 Args2 = Primary->getInjectedTemplateArgs(Ctx);
6497
6498 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6499 // We use profile, instead of structural comparison of the arguments,
6500 // because canonicalization can't do the right thing for dependent
6501 // expressions.
6502 llvm::FoldingSetNodeID IDA, IDB;
6503 Args1[I].Profile(IDA, Ctx);
6504 // Unlike the specialization arguments, the injected arguments are not
6505 // always canonical.
6506 Ctx.getCanonicalTemplateArgument(Args2[I]).Profile(IDB, Ctx);
6507 if (IDA != IDB)
6508 return false;
6509 }
6510 return true;
6511 }
6512};
6513} // namespace
6514
6515/// Returns the more specialized template specialization between T1/P1 and
6516/// T2/P2.
6517/// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
6518/// specialization and T2/P2 is the primary template.
6519/// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
6520///
6521/// \param T1 the type of the first template partial specialization
6522///
6523/// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
6524/// template partial specialization; otherwise, the type of the
6525/// primary template.
6526///
6527/// \param P1 the first template partial specialization
6528///
6529/// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
6530/// partial specialization; otherwise, the primary template.
6531///
6532/// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
6533/// more specialized, returns nullptr if P1 is not more specialized.
6534/// - otherwise, returns the more specialized template partial
6535/// specialization. If neither partial specialization is more
6536/// specialized, returns NULL.
6537template <typename TemplateLikeDecl, typename PrimaryDel>
6538static TemplateLikeDecl *
6539getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
6540 PrimaryDel *P2, TemplateDeductionInfo &Info) {
6541 constexpr bool IsMoreSpecialThanPrimaryCheck =
6542 !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
6543
6544 TemplateDecl *P2T;
6545 if constexpr (IsMoreSpecialThanPrimaryCheck)
6546 P2T = P2;
6547 else
6548 P2T = P2->getSpecializedTemplate();
6549
6550 bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, P2T, Info);
6551 if (IsMoreSpecialThanPrimaryCheck && !Better1)
6552 return nullptr;
6553
6554 bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1,
6555 P1->getSpecializedTemplate(), Info);
6556 if (IsMoreSpecialThanPrimaryCheck && !Better2)
6557 return P1;
6558
6559 // C++ [temp.deduct.partial]p10:
6560 // F is more specialized than G if F is at least as specialized as G and G
6561 // is not at least as specialized as F.
6562 if (Better1 != Better2) // We have a clear winner
6563 return Better1 ? P1 : GetP2()(P1, P2);
6564
6565 if (!Better1 && !Better2)
6566 return nullptr;
6567
6572 return P1;
6574 return GetP2()(P1, P2);
6576 break;
6577 }
6578
6579 if (!S.Context.getLangOpts().CPlusPlus20)
6580 return nullptr;
6581
6582 // Match GCC on not implementing [temp.func.order]p6.2.1.
6583
6584 // C++20 [temp.func.order]p6:
6585 // If deduction against the other template succeeds for both transformed
6586 // templates, constraints can be considered as follows:
6587
6588 TemplateParameterList *TPL1 = P1->getTemplateParameters();
6589 TemplateParameterList *TPL2 = P2->getTemplateParameters();
6590 if (TPL1->size() != TPL2->size())
6591 return nullptr;
6592
6593 // C++20 [temp.func.order]p6.2.2:
6594 // Otherwise, if the corresponding template-parameters of the
6595 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6596 // function parameters that positionally correspond between the two
6597 // templates are not of the same type, neither template is more specialized
6598 // than the other.
6599 if (!S.TemplateParameterListsAreEqual(TPL1, TPL2, false,
6601 return nullptr;
6602
6603 if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
6604 return nullptr;
6605
6607 P1->getAssociatedConstraints(AC1);
6608 P2->getAssociatedConstraints(AC2);
6609 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6610 if (S.IsAtLeastAsConstrained(P1, AC1, P2, AC2, AtLeastAsConstrained1) ||
6611 (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
6612 return nullptr;
6613 if (S.IsAtLeastAsConstrained(P2, AC2, P1, AC1, AtLeastAsConstrained2))
6614 return nullptr;
6615 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6616 return nullptr;
6617 return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
6618}
6619
6631
6634 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
6637
6639 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6640 if (MaybeSpec)
6641 Info.clearSFINAEDiagnostic();
6642 return MaybeSpec;
6643}
6644
6649 // Pretend the variable template specializations are class template
6650 // specializations and form a fake injected class name type for comparison.
6651 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
6652 "the partial specializations being compared should specialize"
6653 " the same template.");
6655 QualType PT1 = Context.getCanonicalTemplateSpecializationType(
6657 QualType PT2 = Context.getCanonicalTemplateSpecializationType(
6659
6660 TemplateDeductionInfo Info(Loc);
6661 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6662}
6663
6666 VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
6667 TemplateName Name(Primary->getCanonicalDecl());
6668
6669 SmallVector<TemplateArgument, 8> PrimaryCanonArgs(
6671 Context.canonicalizeTemplateArguments(PrimaryCanonArgs);
6672
6673 QualType PrimaryT = Context.getCanonicalTemplateSpecializationType(
6674 ElaboratedTypeKeyword::None, Name, PrimaryCanonArgs);
6675 QualType PartialT = Context.getCanonicalTemplateSpecializationType(
6677
6679 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6680 if (MaybeSpec)
6681 Info.clearSFINAEDiagnostic();
6682 return MaybeSpec;
6683}
6684
6687 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
6688 bool PartialOrdering, bool *StrictPackMatch) {
6689 // C++1z [temp.arg.template]p4: (DR 150)
6690 // A template template-parameter P is at least as specialized as a
6691 // template template-argument A if, given the following rewrite to two
6692 // function templates...
6693
6694 // Rather than synthesize function templates, we merely perform the
6695 // equivalent partial ordering by performing deduction directly on
6696 // the template parameter lists of the template template parameters.
6697 //
6699
6703 if (Inst.isInvalid())
6704 return false;
6705
6707
6708 // Given an invented class template X with the template parameter list of
6709 // A (including default arguments):
6710 // - Each function template has a single function parameter whose type is
6711 // a specialization of X with template arguments corresponding to the
6712 // template parameters from the respective function template
6714
6715 // Check P's arguments against A's parameter list. This will fill in default
6716 // template arguments as needed. AArgs are already correct by construction.
6717 // We can't just use CheckTemplateIdType because that will expand alias
6718 // templates.
6720 {
6722 P->getRAngleLoc());
6723 for (unsigned I = 0, N = P->size(); I != N; ++I) {
6724 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
6725 // expansions, to form an "as written" argument list.
6726 TemplateArgument Arg = PArgs[I];
6727 if (Arg.getKind() == TemplateArgument::Pack) {
6728 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
6729 Arg = *Arg.pack_begin();
6730 }
6732 Arg, QualType(), P->getParam(I)->getLocation()));
6733 }
6734 PArgs.clear();
6735
6736 // C++1z [temp.arg.template]p3:
6737 // If the rewrite produces an invalid type, then P is not at least as
6738 // specialized as A.
6740 /*PartialOrdering=*/false, /*MatchingTTP=*/true);
6741 CTAI.SugaredConverted = std::move(PArgs);
6742 if (CheckTemplateArgumentList(AArg, ArgLoc, PArgList, DefaultArgs,
6743 /*PartialTemplateArgs=*/false, CTAI,
6744 /*UpdateArgsWithConversions=*/true,
6745 /*ConstraintsNotSatisfied=*/nullptr))
6746 return false;
6747 PArgs = std::move(CTAI.SugaredConverted);
6748 if (StrictPackMatch)
6749 *StrictPackMatch |= CTAI.StrictPackMatch;
6750 }
6751
6752 // Determine whether P1 is at least as specialized as P2.
6753 TemplateDeductionInfo Info(ArgLoc, A->getDepth());
6755 Deduced.resize(A->size());
6756
6757 // ... the function template corresponding to P is at least as specialized
6758 // as the function template corresponding to A according to the partial
6759 // ordering rules for function templates.
6760
6761 // Provisional resolution for CWG2398: Regarding temp.arg.template]p4, when
6762 // applying the partial ordering rules for function templates on
6763 // the rewritten template template parameters:
6764 // - In a deduced context, the matching of packs versus fixed-size needs to
6765 // be inverted between Ps and As. On non-deduced context, matching needs to
6766 // happen both ways, according to [temp.arg.template]p3, but this is
6767 // currently implemented as a special case elsewhere.
6769 *this, A, AArgs, PArgs, Info, Deduced,
6770 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/true,
6772 /*HasDeducedAnyParam=*/nullptr)) {
6774 if (StrictPackMatch && Info.hasStrictPackMatch())
6775 *StrictPackMatch = true;
6776 break;
6777
6779 Diag(AArg->getLocation(), diag::err_template_param_list_different_arity)
6780 << (A->size() > P->size()) << /*isTemplateTemplateParameter=*/true
6782 return false;
6784 Diag(AArg->getLocation(), diag::err_non_deduced_mismatch)
6785 << Info.FirstArg << Info.SecondArg;
6786 return false;
6789 diag::err_inconsistent_deduction)
6790 << Info.FirstArg << Info.SecondArg;
6791 return false;
6793 return false;
6794
6795 // None of these should happen for a plain deduction.
6810 llvm_unreachable("Unexpected Result");
6811 }
6812
6815 TDK = ::FinishTemplateArgumentDeduction(
6816 *this, AArg, AArg->getTemplateParameters(), AArg, PartialOrdering,
6817 AArgs, PArgs, Deduced, Info, /*CopyDeducedArgs=*/false);
6818 });
6819 switch (TDK) {
6821 return true;
6822
6823 // It doesn't seem possible to get a non-deduced mismatch when partial
6824 // ordering TTPs, except with an invalid template parameter list which has
6825 // a parameter after a pack.
6827 assert(PArg->isInvalidDecl() && "Unexpected NonDeducedMismatch");
6828 return false;
6829
6830 // Substitution failures should have already been diagnosed.
6834 return false;
6835
6836 // None of these should happen when just converting deduced arguments.
6851 llvm_unreachable("Unexpected Result");
6852 }
6853 llvm_unreachable("Unexpected TDK");
6854}
6855
6856namespace {
6857struct MarkUsedTemplateParameterVisitor : DynamicRecursiveASTVisitor {
6858 llvm::SmallBitVector &Used;
6859 unsigned Depth;
6860 bool VisitDeclRefTypes = true;
6861
6862 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used, unsigned Depth,
6863 bool VisitDeclRefTypes = true)
6864 : Used(Used), Depth(Depth), VisitDeclRefTypes(VisitDeclRefTypes) {}
6865
6866 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
6867 if (T->getDepth() == Depth)
6868 Used[T->getIndex()] = true;
6869 return true;
6870 }
6871
6872 bool TraverseTemplateName(TemplateName Template,
6873 bool TraverseQualifier) override {
6874 if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
6875 Template.getAsTemplateDecl()))
6876 if (TTP->getDepth() == Depth)
6877 Used[TTP->getIndex()] = true;
6879 TraverseQualifier);
6880 return true;
6881 }
6882
6883 bool VisitDeclRefExpr(DeclRefExpr *E) override {
6884 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
6885 if (NTTP->getDepth() == Depth)
6886 Used[NTTP->getIndex()] = true;
6887 if (VisitDeclRefTypes)
6889 return true;
6890 }
6891
6892 bool VisitDependentTemplateIdExpr(DependentTemplateIdExpr *E) override {
6893 TemplateTemplateParmDecl *TTP = E->getParameter();
6894 if (TTP->getDepth() == Depth)
6895 Used[TTP->getIndex()] = true;
6896 return true;
6897 }
6898
6899 bool TraverseSizeOfPackExpr(SizeOfPackExpr *SOPE) override {
6900 return TraverseDecl(SOPE->getPack());
6901 }
6902};
6903}
6904
6905/// Mark the template parameters that are used by the given
6906/// expression.
6907static void
6909 const Expr *E,
6910 bool OnlyDeduced,
6911 unsigned Depth,
6912 llvm::SmallBitVector &Used) {
6913 if (!OnlyDeduced) {
6914 MarkUsedTemplateParameterVisitor(Used, Depth)
6915 .TraverseStmt(const_cast<Expr *>(E));
6916 return;
6917 }
6918
6919 // We can deduce from a pack expansion.
6920 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
6921 E = Expansion->getPattern();
6922
6924
6925 if (const auto *DTI = dyn_cast<DependentTemplateIdExpr>(E)) {
6926 Used[DTI->getParameter()->getIndex()] = true;
6927 for (const auto &TLoc : DTI->template_arguments())
6928 MarkUsedTemplateParameters(Ctx, TLoc.getArgument(), OnlyDeduced, Depth,
6929 Used);
6930 return;
6931 }
6932
6933 const NonTypeOrVarTemplateParmDecl NTTP =
6935 if (!NTTP)
6936 return;
6937 if (NTTP.getDepth() == Depth)
6938 Used[NTTP.getIndex()] = true;
6939
6940 // In C++17 mode, additional arguments may be deduced from the type of a
6941 // non-type argument.
6942 if (Ctx.getLangOpts().CPlusPlus17)
6943 MarkUsedTemplateParameters(Ctx, NTTP.getType(), OnlyDeduced, Depth, Used);
6944}
6945
6946/// Mark the template parameters that are used by the given
6947/// nested name specifier.
6949 bool OnlyDeduced, unsigned Depth,
6950 llvm::SmallBitVector &Used) {
6952 return;
6953 MarkUsedTemplateParameters(Ctx, QualType(NNS.getAsType(), 0), OnlyDeduced,
6954 Depth, Used);
6955}
6956
6957/// Mark the template parameters that are used by the given
6958/// template name.
6959static void
6961 TemplateName Name,
6962 bool OnlyDeduced,
6963 unsigned Depth,
6964 llvm::SmallBitVector &Used) {
6965 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
6967 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
6968 if (TTP->getDepth() == Depth)
6969 Used[TTP->getIndex()] = true;
6970 }
6971 return;
6972 }
6973
6975 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
6976 Depth, Used);
6978 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
6979 Depth, Used);
6980}
6981
6982/// Mark the template parameters that are used by the given
6983/// type.
6984static void
6986 bool OnlyDeduced,
6987 unsigned Depth,
6988 llvm::SmallBitVector &Used) {
6989 if (T.isNull())
6990 return;
6991
6992 // Non-dependent types have nothing deducible
6993 if (!T->isDependentType())
6994 return;
6995
6996 T = Ctx.getCanonicalType(T);
6997 switch (T->getTypeClass()) {
6998 case Type::Pointer:
7001 OnlyDeduced,
7002 Depth,
7003 Used);
7004 break;
7005
7006 case Type::BlockPointer:
7009 OnlyDeduced,
7010 Depth,
7011 Used);
7012 break;
7013
7014 case Type::LValueReference:
7015 case Type::RValueReference:
7018 OnlyDeduced,
7019 Depth,
7020 Used);
7021 break;
7022
7023 case Type::MemberPointer: {
7024 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
7025 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
7026 Depth, Used);
7028 QualType(MemPtr->getQualifier().getAsType(), 0),
7029 OnlyDeduced, Depth, Used);
7030 break;
7031 }
7032
7033 case Type::DependentSizedArray:
7035 cast<DependentSizedArrayType>(T)->getSizeExpr(),
7036 OnlyDeduced, Depth, Used);
7037 // Fall through to check the element type
7038 [[fallthrough]];
7039
7040 case Type::ConstantArray:
7041 case Type::IncompleteArray:
7042 case Type::ArrayParameter:
7044 cast<ArrayType>(T)->getElementType(),
7045 OnlyDeduced, Depth, Used);
7046 break;
7047 case Type::Vector:
7048 case Type::ExtVector:
7050 cast<VectorType>(T)->getElementType(),
7051 OnlyDeduced, Depth, Used);
7052 break;
7053
7054 case Type::DependentVector: {
7055 const auto *VecType = cast<DependentVectorType>(T);
7056 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
7057 Depth, Used);
7058 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
7059 Used);
7060 break;
7061 }
7062 case Type::DependentSizedExtVector: {
7063 const DependentSizedExtVectorType *VecType
7065 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
7066 Depth, Used);
7067 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
7068 Depth, Used);
7069 break;
7070 }
7071
7072 case Type::DependentAddressSpace: {
7073 const DependentAddressSpaceType *DependentASType =
7075 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
7076 OnlyDeduced, Depth, Used);
7078 DependentASType->getAddrSpaceExpr(),
7079 OnlyDeduced, Depth, Used);
7080 break;
7081 }
7082
7083 case Type::ConstantMatrix: {
7085 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
7086 Depth, Used);
7087 break;
7088 }
7089
7090 case Type::DependentSizedMatrix: {
7092 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
7093 Depth, Used);
7094 MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
7095 Used);
7096 MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
7097 Depth, Used);
7098 break;
7099 }
7100
7101 case Type::FunctionProto: {
7103 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
7104 Used);
7105 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
7106 // C++17 [temp.deduct.type]p5:
7107 // The non-deduced contexts are: [...]
7108 // -- A function parameter pack that does not occur at the end of the
7109 // parameter-declaration-list.
7110 if (!OnlyDeduced || I + 1 == N ||
7111 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
7112 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
7113 Depth, Used);
7114 } else {
7115 // FIXME: C++17 [temp.deduct.call]p1:
7116 // When a function parameter pack appears in a non-deduced context,
7117 // the type of that pack is never deduced.
7118 //
7119 // We should also track a set of "never deduced" parameters, and
7120 // subtract that from the list of deduced parameters after marking.
7121 }
7122 }
7123 if (auto *E = Proto->getNoexceptExpr())
7124 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
7125 break;
7126 }
7127
7128 case Type::TemplateTypeParm: {
7129 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
7130 if (TTP->getDepth() == Depth)
7131 Used[TTP->getIndex()] = true;
7132 break;
7133 }
7134
7135 case Type::SubstTemplateTypeParmPack: {
7136 const SubstTemplateTypeParmPackType *Subst
7138 if (Subst->getReplacedParameter()->getDepth() == Depth)
7139 Used[Subst->getIndex()] = true;
7140 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(), OnlyDeduced,
7141 Depth, Used);
7142 break;
7143 }
7144 case Type::SubstBuiltinTemplatePack: {
7145 MarkUsedTemplateParameters(Ctx, cast<SubstPackType>(T)->getArgumentPack(),
7146 OnlyDeduced, Depth, Used);
7147 break;
7148 }
7149
7150 case Type::InjectedClassName:
7152 ->getDecl()
7153 ->getCanonicalTemplateSpecializationType(Ctx);
7154 [[fallthrough]];
7155
7156 case Type::TemplateSpecialization: {
7157 const TemplateSpecializationType *Spec
7159
7160 TemplateName Name = Spec->getTemplateName();
7161 if (OnlyDeduced && Name.getAsDependentTemplateName())
7162 break;
7163
7164 MarkUsedTemplateParameters(Ctx, Name, OnlyDeduced, Depth, Used);
7165
7166 // C++0x [temp.deduct.type]p9:
7167 // If the template argument list of P contains a pack expansion that is
7168 // not the last template argument, the entire template argument list is a
7169 // non-deduced context.
7170 if (OnlyDeduced &&
7171 hasPackExpansionBeforeEnd(Spec->template_arguments()))
7172 break;
7173
7174 for (const auto &Arg : Spec->template_arguments())
7175 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
7176 break;
7177 }
7178
7179 case Type::Complex:
7180 if (!OnlyDeduced)
7182 cast<ComplexType>(T)->getElementType(),
7183 OnlyDeduced, Depth, Used);
7184 break;
7185
7186 case Type::Atomic:
7187 if (!OnlyDeduced)
7189 cast<AtomicType>(T)->getValueType(),
7190 OnlyDeduced, Depth, Used);
7191 break;
7192
7193 case Type::DependentName:
7194 if (!OnlyDeduced)
7196 cast<DependentNameType>(T)->getQualifier(),
7197 OnlyDeduced, Depth, Used);
7198 break;
7199
7200 case Type::TypeOf:
7201 if (!OnlyDeduced)
7202 MarkUsedTemplateParameters(Ctx, cast<TypeOfType>(T)->getUnmodifiedType(),
7203 OnlyDeduced, Depth, Used);
7204 break;
7205
7206 case Type::TypeOfExpr:
7207 if (!OnlyDeduced)
7209 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
7210 OnlyDeduced, Depth, Used);
7211 break;
7212
7213 case Type::Decltype:
7214 if (!OnlyDeduced)
7216 cast<DecltypeType>(T)->getUnderlyingExpr(),
7217 OnlyDeduced, Depth, Used);
7218 break;
7219
7220 case Type::PackIndexing:
7221 if (!OnlyDeduced) {
7223 OnlyDeduced, Depth, Used);
7225 OnlyDeduced, Depth, Used);
7226 }
7227 break;
7228
7229 case Type::UnaryTransform:
7230 if (!OnlyDeduced) {
7231 auto *UTT = cast<UnaryTransformType>(T);
7232 auto Next = UTT->getUnderlyingType();
7233 if (Next.isNull())
7234 Next = UTT->getBaseType();
7235 MarkUsedTemplateParameters(Ctx, Next, OnlyDeduced, Depth, Used);
7236 }
7237 break;
7238
7239 case Type::PackExpansion:
7241 cast<PackExpansionType>(T)->getPattern(),
7242 OnlyDeduced, Depth, Used);
7243 break;
7244
7245 case Type::Auto:
7246 case Type::DeducedTemplateSpecialization:
7248 cast<DeducedType>(T)->getDeducedType(),
7249 OnlyDeduced, Depth, Used);
7250 break;
7251 case Type::DependentBitInt:
7253 cast<DependentBitIntType>(T)->getNumBitsExpr(),
7254 OnlyDeduced, Depth, Used);
7255 break;
7256
7257 case Type::HLSLAttributedResource:
7259 Ctx, cast<HLSLAttributedResourceType>(T)->getWrappedType(), OnlyDeduced,
7260 Depth, Used);
7261 if (cast<HLSLAttributedResourceType>(T)->hasContainedType())
7263 Ctx, cast<HLSLAttributedResourceType>(T)->getContainedType(),
7264 OnlyDeduced, Depth, Used);
7265 break;
7266
7267 // None of these types have any template parameters in them.
7268 case Type::Builtin:
7269 case Type::VariableArray:
7270 case Type::FunctionNoProto:
7271 case Type::Record:
7272 case Type::Enum:
7273 case Type::ObjCInterface:
7274 case Type::ObjCObject:
7275 case Type::ObjCObjectPointer:
7276 case Type::UnresolvedUsing:
7277 case Type::Pipe:
7278 case Type::BitInt:
7279 case Type::HLSLInlineSpirv:
7280 case Type::OverflowBehavior:
7281#define TYPE(Class, Base)
7282#define ABSTRACT_TYPE(Class, Base)
7283#define DEPENDENT_TYPE(Class, Base)
7284#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7285#include "clang/AST/TypeNodes.inc"
7286 break;
7287 }
7288}
7289
7290/// Mark the template parameters that are used by this
7291/// template argument.
7292static void
7295 bool OnlyDeduced,
7296 unsigned Depth,
7297 llvm::SmallBitVector &Used) {
7298 switch (TemplateArg.getKind()) {
7304 break;
7305
7307 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
7308 Depth, Used);
7309 break;
7310
7314 TemplateArg.getAsTemplateOrTemplatePattern(),
7315 OnlyDeduced, Depth, Used);
7316 break;
7317
7319 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
7320 Depth, Used);
7321 break;
7322
7324 for (const auto &P : TemplateArg.pack_elements())
7325 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
7326 break;
7327 }
7328}
7329
7330void
7331Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
7332 unsigned Depth,
7333 llvm::SmallBitVector &Used) {
7334 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
7335}
7336
7338 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used) {
7339 MarkUsedTemplateParameterVisitor(Used, Depth, /*VisitDeclRefTypes=*/false)
7340 .TraverseStmt(const_cast<Expr *>(E));
7341}
7342
7343void
7345 bool OnlyDeduced, unsigned Depth,
7346 llvm::SmallBitVector &Used) {
7347 // C++0x [temp.deduct.type]p9:
7348 // If the template argument list of P contains a pack expansion that is not
7349 // the last template argument, the entire template argument list is a
7350 // non-deduced context.
7351 if (OnlyDeduced &&
7352 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
7353 return;
7354
7355 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7356 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
7357 Depth, Used);
7358}
7359
7361 bool OnlyDeduced, unsigned Depth,
7362 llvm::SmallBitVector &Used) {
7363 if (OnlyDeduced && hasPackExpansionBeforeEnd(TemplateArgs))
7364 return;
7365
7366 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7367 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced, Depth,
7368 Used);
7369}
7370
7372 ArrayRef<TemplateArgumentLoc> TemplateArgs, unsigned Depth,
7373 llvm::SmallBitVector &Used) {
7374 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7376 /*OnlyDeduced=*/false, Depth, Used);
7377}
7378
7381 llvm::SmallBitVector &Deduced) {
7382 TemplateParameterList *TemplateParams
7383 = FunctionTemplate->getTemplateParameters();
7384 Deduced.clear();
7385 Deduced.resize(TemplateParams->size());
7386
7387 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
7388 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
7389 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
7390 true, TemplateParams->getDepth(), Deduced);
7391}
7392
7395 QualType T) {
7396 if (!T->isDependentType())
7397 return false;
7398
7399 TemplateParameterList *TemplateParams
7400 = FunctionTemplate->getTemplateParameters();
7401 llvm::SmallBitVector Deduced(TemplateParams->size());
7402 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
7403 Deduced);
7404
7405 return Deduced.any();
7406}
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 NonTypeOrVarTemplateParmDecl getDeducedNTTParameterFromExpr(const Expr *E, unsigned Depth)
If the given expression is of a form that permits the deduction of a non-type template parameter,...
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....
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.
Allows QualTypes to be sorted and hence used in maps and sets.
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:239
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:2692
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8303
Pointer to a block type.
Definition TypeBase.h:3652
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2977
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3013
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
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:2343
bool isStatic() const
Definition DeclCXX.cpp:2417
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
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:3361
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:4489
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4511
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4508
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
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:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
ValueDecl * getDecl()
Definition Expr.h:1358
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:596
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
Kind getKind() const
Definition DeclBase.h:450
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:2540
NestedNameSpecifierLoc getQualifierLoc() const
Definition TypeLoc.h:2552
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4158
QualType getPointeeType() const
Definition TypeBase.h:4170
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4198
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4581
TemplateTemplateParmDecl * getParameter() const
Definition ExprCXX.h:3509
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4324
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:340
bool isLValue() const
Definition Expr.h:391
This represents one expression.
Definition Expr.h:113
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
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:145
ExtVectorType - Extended vector type.
Definition TypeBase.h:4364
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:2059
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4244
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4232
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3907
QualType getReturnType() const
Definition Decl.h:2976
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
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:4303
void getAssociatedConstraints(SmallVectorImpl< AssociatedConstraint > &ACs) const
Get the associated-constraints of this function declaration.
Definition Decl.h:2883
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4368
bool isImmediateEscalating() const
Definition Decl.cpp:3353
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4169
size_t param_size() const
Definition Decl.h:2921
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5415
param_type_iterator param_type_begin() const
Definition TypeBase.h:5859
const ExtParameterInfo * getExtParameterInfosOrNull() const
Return a pointer to the beginning of the array of extra parameter information, if present,...
Definition TypeBase.h:5897
unsigned getNumParams() const
Definition TypeBase.h:5693
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition TypeBase.h:5835
Qualifiers getMethodQuals() const
Definition TypeBase.h:5841
QualType getParamType(unsigned i) const
Definition TypeBase.h:5695
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5728
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5819
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5704
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition TypeBase.h:5780
param_type_iterator param_type_end() const
Definition TypeBase.h:5863
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5700
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition TypeBase.h:5849
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:4611
QualType getReturnType() const
Definition TypeBase.h:4951
Describes an C or C++ initializer list.
Definition Expr.h:5352
unsigned getNumInits() const
Definition Expr.h:5385
unsigned getNumInitsWithEmbedExpanded() const
getNumInits but if the list has an EmbedExpr inside includes full length of embedded data.
Definition Expr.h:5389
ArrayRef< Expr * > inits() const
Definition Expr.h:5405
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3714
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:565
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4434
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4453
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3750
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3782
QualType getPointeeType() const
Definition TypeBase.h:3768
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:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
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.
Represents a pointer to an Objective C object.
Definition TypeBase.h:8086
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition ExprCXX.h:3142
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3294
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3203
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3255
decls_iterator decls_begin() const
Definition ExprCXX.h:3235
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3324
decls_iterator decls_end() const
Definition ExprCXX.h:3238
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4416
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3402
QualType getPointeeType() const
Definition TypeBase.h:3412
A (possibly-)qualified type.
Definition TypeBase.h:938
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8534
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:8445
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8571
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8485
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:8630
QualType getCanonicalType() const
Definition TypeBase.h:8497
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8539
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1839
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8491
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:3732
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:3677
QualType getPointeeType() const
Definition TypeBase.h:3699
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:13806
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8521
A RAII object to temporarily push a declaration context.
Definition Sema.h:3556
A helper class for building up ExtParameterInfos.
Definition Sema.h:13175
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:13194
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12595
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12629
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:13204
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:1471
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:6993
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:12117
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12109
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12113
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition Sema.h:1304
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:777
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:1208
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:12313
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...
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl * > Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl * > *OutParams, ExtParameterInfoBuilder &ParamInfos)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
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:1444
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:12666
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:8254
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)
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:13844
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15645
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:6804
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6773
QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, CallingConv CC)
Get the return type to use for a lambda's conversion function(s) to function pointer type,...
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:646
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:6481
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:13047
NamedDecl * getPack() const
Retrieve the parameter pack.
Definition ExprCXX.h:4562
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:3673
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:8416
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8427
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:9067
const TemplateSpecializationType * getAsNonAliasTemplateSpecializationType() const
Look through sugar for an instance of TemplateSpecializationType which is not a type alias,...
Definition Type.cpp:2090
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:9043
bool isRValueReferenceType() const
Definition TypeBase.h:8714
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:8781
bool isFunctionPointerType() const
Definition TypeBase.h:8749
bool isPointerType() const
Definition TypeBase.h:8682
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9361
bool isReferenceType() const
Definition TypeBase.h:8706
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:883
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2979
bool isLValueReferenceType() const
Definition TypeBase.h:8710
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2862
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3199
bool isMemberPointerType() const
Definition TypeBase.h:8763
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5618
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9210
bool isFunctionType() const
Definition TypeBase.h:8678
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8767
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3001
bool isAnyPointerType() const
Definition TypeBase.h:8690
TypeClass getTypeClass() const
Definition TypeBase.h:2449
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9294
bool isRecordType() const
Definition TypeBase.h:8809
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:713
QualType getType() const
Definition Decl.h:724
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:933
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1603
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:4272
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
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
const FunctionProtoType * T
@ 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:1305
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
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
@ 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:6034
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...
#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:5474
Extra information about a function prototype.
Definition TypeBase.h:5500
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5505
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:12144
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12140
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12133
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12130
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12130
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition Sema.h:13276
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13283
A stack object to be created when performing template instantiation.
Definition Sema.h:13449
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13602
brief A function argument from which we performed template argument
Definition Sema.h:12765
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)