Thanks to visit codestin.com
Credit goes to clang.llvm.org

clang 22.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,
125 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
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 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E);
251 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
252 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
253
254 if (TTP->getDepth() == Depth)
255 return TTP;
256 }
257 }
258 return nullptr;
259}
260
265
266/// Determine whether two declaration pointers refer to the same
267/// declaration.
268static bool isSameDeclaration(Decl *X, Decl *Y) {
269 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
270 X = NX->getUnderlyingDecl();
271 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
272 Y = NY->getUnderlyingDecl();
273
274 return X->getCanonicalDecl() == Y->getCanonicalDecl();
275}
276
277/// Verify that the given, deduced template arguments are compatible.
278///
279/// \returns The deduced template argument, or a NULL template argument if
280/// the deduced template arguments were incompatible.
285 bool AggregateCandidateDeduction = false) {
286 // We have no deduction for one or both of the arguments; they're compatible.
287 if (X.isNull())
288 return Y;
289 if (Y.isNull())
290 return X;
291
292 // If we have two non-type template argument values deduced for the same
293 // parameter, they must both match the type of the parameter, and thus must
294 // match each other's type. As we're only keeping one of them, we must check
295 // for that now. The exception is that if either was deduced from an array
296 // bound, the type is permitted to differ.
297 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
298 QualType XType = X.getNonTypeTemplateArgumentType();
299 if (!XType.isNull()) {
301 if (YType.isNull() || !Context.hasSameType(XType, YType))
303 }
304 }
305
306 switch (X.getKind()) {
308 llvm_unreachable("Non-deduced template arguments handled above");
309
311 // If two template type arguments have the same type, they're compatible.
312 QualType TX = X.getAsType(), TY = Y.getAsType();
313 if (Y.getKind() == TemplateArgument::Type && Context.hasSameType(TX, TY))
314 return DeducedTemplateArgument(Context.getCommonSugaredType(TX, TY),
315 X.wasDeducedFromArrayBound() ||
317
318 // If one of the two arguments was deduced from an array bound, the other
319 // supersedes it.
320 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
321 return X.wasDeducedFromArrayBound() ? Y : X;
322
323 // The arguments are not compatible.
325 }
326
328 // If we deduced a constant in one case and either a dependent expression or
329 // declaration in another case, keep the integral constant.
330 // If both are integral constants with the same value, keep that value.
334 llvm::APSInt::isSameValue(X.getAsIntegral(), Y.getAsIntegral())))
335 return X.wasDeducedFromArrayBound() ? Y : X;
336
337 // All other combinations are incompatible.
339
341 // If we deduced a value and a dependent expression, keep the value.
344 X.structurallyEquals(Y)))
345 return X;
346
347 // All other combinations are incompatible.
349
352 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
353 return X;
354
355 // All other combinations are incompatible.
357
360 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
362 return X;
363
364 // All other combinations are incompatible.
366
369 return checkDeducedTemplateArguments(Context, Y, X);
370
371 // Compare the expressions for equality
372 llvm::FoldingSetNodeID ID1, ID2;
373 X.getAsExpr()->Profile(ID1, Context, true);
374 Y.getAsExpr()->Profile(ID2, Context, true);
375 if (ID1 == ID2)
376 return X.wasDeducedFromArrayBound() ? Y : X;
377
378 // Differing dependent expressions are incompatible.
380 }
381
383 assert(!X.wasDeducedFromArrayBound());
384
385 // If we deduced a declaration and a dependent expression, keep the
386 // declaration.
388 return X;
389
390 // If we deduced a declaration and an integral constant, keep the
391 // integral constant and whichever type did not come from an array
392 // bound.
395 return TemplateArgument(Context, Y.getAsIntegral(),
396 X.getParamTypeForDecl());
397 return Y;
398 }
399
400 // If we deduced two declarations, make sure that they refer to the
401 // same declaration.
403 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
404 return X;
405
406 // All other combinations are incompatible.
408
410 // If we deduced a null pointer and a dependent expression, keep the
411 // null pointer.
413 return TemplateArgument(Context.getCommonSugaredType(
414 X.getNullPtrType(), Y.getAsExpr()->getType()),
415 true);
416
417 // If we deduced a null pointer and an integral constant, keep the
418 // integral constant.
420 return Y;
421
422 // If we deduced two null pointers, they are the same.
424 return TemplateArgument(
425 Context.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
426 true);
427
428 // All other combinations are incompatible.
430
432 if (Y.getKind() != TemplateArgument::Pack ||
433 (!AggregateCandidateDeduction && X.pack_size() != Y.pack_size()))
435
438 XA = X.pack_begin(),
439 XAEnd = X.pack_end(), YA = Y.pack_begin(), YAEnd = Y.pack_end();
440 XA != XAEnd; ++XA) {
441 if (YA != YAEnd) {
443 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
445 if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
447 NewPack.push_back(Merged);
448 ++YA;
449 } else {
450 NewPack.push_back(*XA);
451 }
452 }
453
455 TemplateArgument::CreatePackCopy(Context, NewPack),
456 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
457 }
458 }
459
460 llvm_unreachable("Invalid TemplateArgument Kind!");
461}
462
463/// Deduce the value of the given non-type template parameter
464/// as the given deduced template argument. All non-type template parameter
465/// deduction is funneled through here.
469 const DeducedTemplateArgument &NewDeduced,
470 QualType ValueType, TemplateDeductionInfo &Info,
471 bool PartialOrdering,
473 bool *HasDeducedAnyParam) {
474 assert(NTTP.getDepth() == Info.getDeducedDepth() &&
475 "deducing non-type template argument with wrong depth");
476
478 S.Context, Deduced[NTTP.getIndex()], NewDeduced);
479 if (Result.isNull()) {
480 Info.Param = NTTP.asTemplateParam();
481 Info.FirstArg = Deduced[NTTP.getIndex()];
482 Info.SecondArg = NewDeduced;
484 }
485 Deduced[NTTP.getIndex()] = Result;
486 if (!S.getLangOpts().CPlusPlus17 && !PartialOrdering)
488
489 if (NTTP.isExpandedParameterPack())
490 // FIXME: We may still need to deduce parts of the type here! But we
491 // don't have any way to find which slice of the type to use, and the
492 // type stored on the NTTP itself is nonsense. Perhaps the type of an
493 // expanded NTTP should be a pack expansion type?
495
496 // Get the type of the parameter for deduction. If it's a (dependent) array
497 // or function type, we will not have decayed it yet, so do that now.
498 QualType ParamType = S.Context.getAdjustedParameterType(NTTP.getType());
499 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
500 ParamType = Expansion->getPattern();
501
502 // FIXME: It's not clear how deduction of a parameter of reference
503 // type from an argument (of non-reference type) should be performed.
504 // For now, we just make the argument have same reference type as the
505 // parameter.
506 if (ParamType->isReferenceType() && !ValueType->isReferenceType()) {
507 if (ParamType->isRValueReferenceType())
508 ValueType = S.Context.getRValueReferenceType(ValueType);
509 else
510 ValueType = S.Context.getLValueReferenceType(ValueType);
511 }
512
514 S, TemplateParams, ParamType, ValueType, Info, Deduced,
518 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound(), HasDeducedAnyParam);
519}
520
521/// Deduce the value of the given non-type template parameter
522/// from the given integral constant.
524 Sema &S, TemplateParameterList *TemplateParams,
525 NonTypeOrVarTemplateParmDecl NTTP, const llvm::APSInt &Value,
526 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
528 bool *HasDeducedAnyParam) {
530 S, TemplateParams, NTTP,
532 DeducedFromArrayBound),
533 ValueType, Info, PartialOrdering, Deduced, HasDeducedAnyParam);
534}
535
536/// Deduce the value of the given non-type template parameter
537/// from the given null pointer template argument type.
541 QualType NullPtrType, TemplateDeductionInfo &Info,
542 bool PartialOrdering,
544 bool *HasDeducedAnyParam) {
547 NTTP.getLocation()),
548 NullPtrType,
549 NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer
550 : CK_NullToPointer)
551 .get();
553 S, TemplateParams, NTTP, TemplateArgument(Value, /*IsCanonical=*/false),
554 Value->getType(), Info, PartialOrdering, Deduced, HasDeducedAnyParam);
555}
556
557/// Deduce the value of the given non-type template parameter
558/// from the given type- or value-dependent expression.
559///
560/// \returns true if deduction succeeded, false otherwise.
566 bool *HasDeducedAnyParam) {
568 S, TemplateParams, NTTP, TemplateArgument(Value, /*IsCanonical=*/false),
569 Value->getType(), Info, PartialOrdering, Deduced, HasDeducedAnyParam);
570}
571
572/// Deduce the value of the given non-type template parameter
573/// from the given declaration.
574///
575/// \returns true if deduction succeeded, false otherwise.
580 bool PartialOrdering,
582 bool *HasDeducedAnyParam) {
585 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info,
586 PartialOrdering, Deduced, HasDeducedAnyParam);
587}
588
590 Sema &S, TemplateParameterList *TemplateParams, TemplateName Param,
594 bool *HasDeducedAnyParam) {
595 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
596 if (!ParamDecl) {
597 // The parameter type is dependent and is not a template template parameter,
598 // so there is nothing that we can deduce.
600 }
601
602 if (auto *TempParam = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
603 // If we're not deducing at this depth, there's nothing to deduce.
604 if (TempParam->getDepth() != Info.getDeducedDepth())
606
607 ArrayRef<NamedDecl *> Params =
608 ParamDecl->getTemplateParameters()->asArray();
609 unsigned StartPos = 0;
610 for (unsigned I = 0, E = std::min(Params.size(), DefaultArguments.size());
611 I < E; ++I) {
612 if (Params[I]->isParameterPack()) {
613 StartPos = DefaultArguments.size();
614 break;
615 }
616 StartPos = I + 1;
617 }
618
619 // Provisional resolution for CWG2398: If Arg names a template
620 // specialization, then we deduce a synthesized template name
621 // based on A, but using the TS's extra arguments, relative to P, as
622 // defaults.
623 DeducedTemplateArgument NewDeduced =
626 Arg, {StartPos, DefaultArguments.drop_front(StartPos)}))
627 : Arg;
628
630 S.Context, Deduced[TempParam->getIndex()], NewDeduced);
631 if (Result.isNull()) {
632 Info.Param = TempParam;
633 Info.FirstArg = Deduced[TempParam->getIndex()];
634 Info.SecondArg = NewDeduced;
636 }
637
638 Deduced[TempParam->getIndex()] = Result;
639 if (HasDeducedAnyParam)
640 *HasDeducedAnyParam = true;
642 }
643
644 // Verify that the two template names are equivalent.
646 Param, Arg, /*IgnoreDeduced=*/DefaultArguments.size() != 0))
648
649 // Mismatch of non-dependent template parameter to argument.
650 Info.FirstArg = TemplateArgument(Param);
651 Info.SecondArg = TemplateArgument(Arg);
653}
654
655/// Deduce the template arguments by comparing the template parameter
656/// type (which is a template-id) with the template argument type.
657///
658/// \param S the Sema
659///
660/// \param TemplateParams the template parameters that we are deducing
661///
662/// \param P the parameter type
663///
664/// \param A the argument type
665///
666/// \param Info information about the template argument deduction itself
667///
668/// \param Deduced the deduced template arguments
669///
670/// \returns the result of template argument deduction so far. Note that a
671/// "success" result means that template argument deduction has not yet failed,
672/// but it may still fail, later, for other reasons.
673
674static const TemplateSpecializationType *getLastTemplateSpecType(QualType QT) {
675 const TemplateSpecializationType *LastTST = nullptr;
676 for (const Type *T = QT.getTypePtr(); /**/; /**/) {
677 const TemplateSpecializationType *TST =
678 T->getAs<TemplateSpecializationType>();
679 if (!TST)
680 return LastTST;
681 if (!TST->isSugared())
682 return TST;
683 LastTST = TST;
684 T = TST->desugar().getTypePtr();
685 }
686}
687
690 const QualType P, QualType A,
693 bool *HasDeducedAnyParam) {
694 TemplateName TNP;
697 const TemplateSpecializationType *TP = ::getLastTemplateSpecType(P);
698 TNP = TP->getTemplateName();
699
700 // No deduction for specializations of dependent template names.
703
704 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
705 // arguments.
706 PResolved =
707 TP->castAsCanonical<TemplateSpecializationType>()->template_arguments();
708 } else {
709 const auto *TT = P->castAs<InjectedClassNameType>();
710 TNP = TT->getTemplateName(S.Context);
711 PResolved = TT->getTemplateArgs(S.Context);
712 }
713
714 // If the parameter is an alias template, there is nothing to deduce.
715 if (const auto *TD = TNP.getAsTemplateDecl(); TD && TD->isTypeAlias())
717 // Pack-producing templates can only be matched after substitution.
720
721 // Check whether the template argument is a dependent template-id.
723 const TemplateSpecializationType *SA = ::getLastTemplateSpecType(A);
724 TemplateName TNA = SA->getTemplateName();
725
726 // If the argument is an alias template, there is nothing to deduce.
727 if (const auto *TD = TNA.getAsTemplateDecl(); TD && TD->isTypeAlias())
729
730 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
731 // arguments.
733 SA->getCanonicalTypeInternal()
734 ->castAs<TemplateSpecializationType>()
735 ->template_arguments();
736
737 // Perform template argument deduction for the template name.
738 if (auto Result = DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
739 /*DefaultArguments=*/AResolved,
740 PartialOrdering, Deduced,
741 HasDeducedAnyParam);
743 return Result;
744
745 // Perform template argument deduction on each template
746 // argument. Ignore any missing/extra arguments, since they could be
747 // filled in by default arguments.
749 S, TemplateParams, PResolved, AResolved, Info, Deduced,
750 /*NumberOfArgumentsMustMatch=*/false, PartialOrdering,
751 PackFold::ParameterToArgument, HasDeducedAnyParam);
752 }
753
754 // If the argument type is a class template specialization, we
755 // perform template argument deduction using its template
756 // arguments.
757 const auto *TA = A->getAs<TagType>();
758 TemplateName TNA;
759 if (TA) {
760 // FIXME: Can't use the template arguments from this TST, as they are not
761 // resolved.
762 if (const auto *TST = A->getAsNonAliasTemplateSpecializationType())
763 TNA = TST->getTemplateName();
764 else
765 TNA = TA->getTemplateName(S.Context);
766 }
767 if (TNA.isNull()) {
768 Info.FirstArg = TemplateArgument(P);
769 Info.SecondArg = TemplateArgument(A);
771 }
772
773 ArrayRef<TemplateArgument> AResolved = TA->getTemplateArgs(S.Context);
774 // Perform template argument deduction for the template name.
775 if (auto Result =
776 DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
777 /*DefaultArguments=*/AResolved,
778 PartialOrdering, Deduced, HasDeducedAnyParam);
780 return Result;
781
782 // Perform template argument deduction for the template arguments.
784 S, TemplateParams, PResolved, AResolved, Info, Deduced,
785 /*NumberOfArgumentsMustMatch=*/true, PartialOrdering,
786 PackFold::ParameterToArgument, HasDeducedAnyParam);
787}
788
790 assert(T->isCanonicalUnqualified());
791
792 switch (T->getTypeClass()) {
793 case Type::TypeOfExpr:
794 case Type::TypeOf:
795 case Type::DependentName:
796 case Type::Decltype:
797 case Type::PackIndexing:
798 case Type::UnresolvedUsing:
799 case Type::TemplateTypeParm:
800 case Type::Auto:
801 return true;
802
803 case Type::ConstantArray:
804 case Type::IncompleteArray:
805 case Type::VariableArray:
806 case Type::DependentSizedArray:
808 cast<ArrayType>(T)->getElementType().getTypePtr());
809
810 default:
811 return false;
812 }
813}
814
815/// Determines whether the given type is an opaque type that
816/// might be more qualified when instantiated.
819 T->getCanonicalTypeInternal().getTypePtr());
820}
821
822/// Helper function to build a TemplateParameter when we don't
823/// know its type statically.
825 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
826 return TemplateParameter(TTP);
827 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
828 return TemplateParameter(NTTP);
829
831}
832
833/// A pack that we're currently deducing.
835 // The index of the pack.
836 unsigned Index;
837
838 // The old value of the pack before we started deducing it.
840
841 // A deferred value of this pack from an inner deduction, that couldn't be
842 // deduced because this deduction hadn't happened yet.
844
845 // The new value of the pack.
847
848 // The outer deduction for this pack, if any.
849 DeducedPack *Outer = nullptr;
850
851 DeducedPack(unsigned Index) : Index(Index) {}
852};
853
854namespace {
855
856/// A scope in which we're performing pack deduction.
857class PackDeductionScope {
858public:
859 /// Prepare to deduce the packs named within Pattern.
860 /// \param FinishingDeduction Don't attempt to deduce the pack. Useful when
861 /// just checking a previous deduction of the pack.
862 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
865 bool DeducePackIfNotAlreadyDeduced = false,
866 bool FinishingDeduction = false)
867 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info),
868 DeducePackIfNotAlreadyDeduced(DeducePackIfNotAlreadyDeduced),
869 FinishingDeduction(FinishingDeduction) {
870 unsigned NumNamedPacks = addPacks(Pattern);
871 finishConstruction(NumNamedPacks);
872 }
873
874 /// Prepare to directly deduce arguments of the parameter with index \p Index.
875 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
876 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
877 TemplateDeductionInfo &Info, unsigned Index)
878 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
879 addPack(Index);
880 finishConstruction(1);
881 }
882
883private:
884 void addPack(unsigned Index) {
885 // Save the deduced template argument for the parameter pack expanded
886 // by this pack expansion, then clear out the deduction.
887 DeducedFromEarlierParameter = !Deduced[Index].isNull();
888 DeducedPack Pack(Index);
889 if (!FinishingDeduction) {
890 Pack.Saved = Deduced[Index];
891 Deduced[Index] = TemplateArgument();
892 }
893
894 // FIXME: What if we encounter multiple packs with different numbers of
895 // pre-expanded expansions? (This should already have been diagnosed
896 // during substitution.)
897 if (UnsignedOrNone ExpandedPackExpansions =
898 getExpandedPackSize(TemplateParams->getParam(Index)))
899 FixedNumExpansions = ExpandedPackExpansions;
900
901 Packs.push_back(Pack);
902 }
903
904 unsigned addPacks(TemplateArgument Pattern) {
905 // Compute the set of template parameter indices that correspond to
906 // parameter packs expanded by the pack expansion.
907 llvm::SmallBitVector SawIndices(TemplateParams->size());
908 llvm::SmallVector<TemplateArgument, 4> ExtraDeductions;
909
910 auto AddPack = [&](unsigned Index) {
911 if (SawIndices[Index])
912 return;
913 SawIndices[Index] = true;
914 addPack(Index);
915
916 // Deducing a parameter pack that is a pack expansion also constrains the
917 // packs appearing in that parameter to have the same deduced arity. Also,
918 // in C++17 onwards, deducing a non-type template parameter deduces its
919 // type, so we need to collect the pending deduced values for those packs.
920 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
921 TemplateParams->getParam(Index))) {
922 if (!NTTP->isExpandedParameterPack())
923 // FIXME: CWG2982 suggests a type-constraint forms a non-deduced
924 // context, however it is not yet resolved.
925 if (auto *Expansion = dyn_cast<PackExpansionType>(
926 S.Context.getUnconstrainedType(NTTP->getType())))
927 ExtraDeductions.push_back(Expansion->getPattern());
928 }
929 // FIXME: Also collect the unexpanded packs in any type and template
930 // parameter packs that are pack expansions.
931 };
932
933 auto Collect = [&](TemplateArgument Pattern) {
934 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
935 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
936 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
937 unsigned Depth, Index;
938 if (auto DI = getDepthAndIndex(Unexpanded[I]))
939 std::tie(Depth, Index) = *DI;
940 else
941 continue;
942
943 if (Depth == Info.getDeducedDepth())
944 AddPack(Index);
945 }
946 };
947
948 // Look for unexpanded packs in the pattern.
949 Collect(Pattern);
950
951 unsigned NumNamedPacks = Packs.size();
952
953 // Also look for unexpanded packs that are indirectly deduced by deducing
954 // the sizes of the packs in this pattern.
955 while (!ExtraDeductions.empty())
956 Collect(ExtraDeductions.pop_back_val());
957
958 return NumNamedPacks;
959 }
960
961 void finishConstruction(unsigned NumNamedPacks) {
962 // Dig out the partially-substituted pack, if there is one.
963 const TemplateArgument *PartialPackArgs = nullptr;
964 unsigned NumPartialPackArgs = 0;
965 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
966 if (auto *Scope = S.CurrentInstantiationScope)
967 if (auto *Partial = Scope->getPartiallySubstitutedPack(
968 &PartialPackArgs, &NumPartialPackArgs))
969 PartialPackDepthIndex = getDepthAndIndex(Partial);
970
971 // This pack expansion will have been partially or fully expanded if
972 // it only names explicitly-specified parameter packs (including the
973 // partially-substituted one, if any).
974 bool IsExpanded = true;
975 for (unsigned I = 0; I != NumNamedPacks; ++I) {
976 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
977 IsExpanded = false;
978 IsPartiallyExpanded = false;
979 break;
980 }
981 if (PartialPackDepthIndex ==
982 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
983 IsPartiallyExpanded = true;
984 }
985 }
986
987 // Skip over the pack elements that were expanded into separate arguments.
988 // If we partially expanded, this is the number of partial arguments.
989 // FIXME: `&& FixedNumExpansions` is a workaround for UB described in
990 // https://github.com/llvm/llvm-project/issues/100095
991 if (IsPartiallyExpanded)
992 PackElements += NumPartialPackArgs;
993 else if (IsExpanded && FixedNumExpansions)
994 PackElements += *FixedNumExpansions;
995
996 for (auto &Pack : Packs) {
997 if (Info.PendingDeducedPacks.size() > Pack.Index)
998 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
999 else
1000 Info.PendingDeducedPacks.resize(Pack.Index + 1);
1001 Info.PendingDeducedPacks[Pack.Index] = &Pack;
1002
1003 if (PartialPackDepthIndex ==
1004 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
1005 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
1006 // We pre-populate the deduced value of the partially-substituted
1007 // pack with the specified value. This is not entirely correct: the
1008 // value is supposed to have been substituted, not deduced, but the
1009 // cases where this is observable require an exact type match anyway.
1010 //
1011 // FIXME: If we could represent a "depth i, index j, pack elem k"
1012 // parameter, we could substitute the partially-substituted pack
1013 // everywhere and avoid this.
1014 if (!FinishingDeduction && !IsPartiallyExpanded)
1015 Deduced[Pack.Index] = Pack.New[PackElements];
1016 }
1017 }
1018 }
1019
1020public:
1021 ~PackDeductionScope() {
1022 for (auto &Pack : Packs)
1023 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
1024 }
1025
1026 // Return the size of the saved packs if all of them has the same size.
1027 UnsignedOrNone getSavedPackSizeIfAllEqual() const {
1028 unsigned PackSize = Packs[0].Saved.pack_size();
1029
1030 if (std::all_of(Packs.begin() + 1, Packs.end(), [&PackSize](const auto &P) {
1031 return P.Saved.pack_size() == PackSize;
1032 }))
1033 return PackSize;
1034 return std::nullopt;
1035 }
1036
1037 /// Determine whether this pack has already been deduced from a previous
1038 /// argument.
1039 bool isDeducedFromEarlierParameter() const {
1040 return DeducedFromEarlierParameter;
1041 }
1042
1043 /// Determine whether this pack has already been partially expanded into a
1044 /// sequence of (prior) function parameters / template arguments.
1045 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
1046
1047 /// Determine whether this pack expansion scope has a known, fixed arity.
1048 /// This happens if it involves a pack from an outer template that has
1049 /// (notionally) already been expanded.
1050 bool hasFixedArity() { return static_cast<bool>(FixedNumExpansions); }
1051
1052 /// Determine whether the next element of the argument is still part of this
1053 /// pack. This is the case unless the pack is already expanded to a fixed
1054 /// length.
1055 bool hasNextElement() {
1056 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
1057 }
1058
1059 /// Move to deducing the next element in each pack that is being deduced.
1060 void nextPackElement() {
1061 // Capture the deduced template arguments for each parameter pack expanded
1062 // by this pack expansion, add them to the list of arguments we've deduced
1063 // for that pack, then clear out the deduced argument.
1064 if (!FinishingDeduction) {
1065 for (auto &Pack : Packs) {
1066 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
1067 if (!Pack.New.empty() || !DeducedArg.isNull()) {
1068 while (Pack.New.size() < PackElements)
1069 Pack.New.push_back(DeducedTemplateArgument());
1070 if (Pack.New.size() == PackElements)
1071 Pack.New.push_back(DeducedArg);
1072 else
1073 Pack.New[PackElements] = DeducedArg;
1074 DeducedArg = Pack.New.size() > PackElements + 1
1075 ? Pack.New[PackElements + 1]
1076 : DeducedTemplateArgument();
1077 }
1078 }
1079 }
1080 ++PackElements;
1081 }
1082
1083 /// Finish template argument deduction for a set of argument packs,
1084 /// producing the argument packs and checking for consistency with prior
1085 /// deductions.
1086 TemplateDeductionResult finish() {
1087 if (FinishingDeduction)
1088 return TemplateDeductionResult::Success;
1089 // Build argument packs for each of the parameter packs expanded by this
1090 // pack expansion.
1091 for (auto &Pack : Packs) {
1092 // Put back the old value for this pack.
1093 if (!FinishingDeduction)
1094 Deduced[Pack.Index] = Pack.Saved;
1095
1096 // Always make sure the size of this pack is correct, even if we didn't
1097 // deduce any values for it.
1098 //
1099 // FIXME: This isn't required by the normative wording, but substitution
1100 // and post-substitution checking will always fail if the arity of any
1101 // pack is not equal to the number of elements we processed. (Either that
1102 // or something else has gone *very* wrong.) We're permitted to skip any
1103 // hard errors from those follow-on steps by the intent (but not the
1104 // wording) of C++ [temp.inst]p8:
1105 //
1106 // If the function selected by overload resolution can be determined
1107 // without instantiating a class template definition, it is unspecified
1108 // whether that instantiation actually takes place
1109 Pack.New.resize(PackElements);
1110
1111 // Build or find a new value for this pack.
1112 DeducedTemplateArgument NewPack;
1113 if (Pack.New.empty()) {
1114 // If we deduced an empty argument pack, create it now.
1115 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
1116 } else {
1117 TemplateArgument *ArgumentPack =
1118 new (S.Context) TemplateArgument[Pack.New.size()];
1119 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
1120 NewPack = DeducedTemplateArgument(
1121 TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())),
1122 // FIXME: This is wrong, it's possible that some pack elements are
1123 // deduced from an array bound and others are not:
1124 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
1125 // g({1, 2, 3}, {{}, {}});
1126 // ... should deduce T = {int, size_t (from array bound)}.
1127 Pack.New[0].wasDeducedFromArrayBound());
1128 }
1129
1130 // Pick where we're going to put the merged pack.
1131 DeducedTemplateArgument *Loc;
1132 if (Pack.Outer) {
1133 if (Pack.Outer->DeferredDeduction.isNull()) {
1134 // Defer checking this pack until we have a complete pack to compare
1135 // it against.
1136 Pack.Outer->DeferredDeduction = NewPack;
1137 continue;
1138 }
1139 Loc = &Pack.Outer->DeferredDeduction;
1140 } else {
1141 Loc = &Deduced[Pack.Index];
1142 }
1143
1144 // Check the new pack matches any previous value.
1145 DeducedTemplateArgument OldPack = *Loc;
1146 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
1147 S.Context, OldPack, NewPack, DeducePackIfNotAlreadyDeduced);
1148
1149 Info.AggregateDeductionCandidateHasMismatchedArity =
1150 OldPack.getKind() == TemplateArgument::Pack &&
1151 NewPack.getKind() == TemplateArgument::Pack &&
1152 OldPack.pack_size() != NewPack.pack_size() && !Result.isNull();
1153
1154 // If we deferred a deduction of this pack, check that one now too.
1155 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
1156 OldPack = Result;
1157 NewPack = Pack.DeferredDeduction;
1158 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
1159 }
1160
1161 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
1162 if (Result.isNull()) {
1163 Info.Param = makeTemplateParameter(Param);
1164 Info.FirstArg = OldPack;
1165 Info.SecondArg = NewPack;
1166 return TemplateDeductionResult::Inconsistent;
1167 }
1168
1169 // If we have a pre-expanded pack and we didn't deduce enough elements
1170 // for it, fail deduction.
1171 if (UnsignedOrNone Expansions = getExpandedPackSize(Param)) {
1172 if (*Expansions != PackElements) {
1173 Info.Param = makeTemplateParameter(Param);
1174 Info.FirstArg = Result;
1175 return TemplateDeductionResult::IncompletePack;
1176 }
1177 }
1178
1179 *Loc = Result;
1180 }
1181
1182 return TemplateDeductionResult::Success;
1183 }
1184
1185private:
1186 Sema &S;
1187 TemplateParameterList *TemplateParams;
1188 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
1189 TemplateDeductionInfo &Info;
1190 unsigned PackElements = 0;
1191 bool IsPartiallyExpanded = false;
1192 bool DeducePackIfNotAlreadyDeduced = false;
1193 bool DeducedFromEarlierParameter = false;
1194 bool FinishingDeduction = false;
1195 /// The number of expansions, if we have a fully-expanded pack in this scope.
1196 UnsignedOrNone FixedNumExpansions = std::nullopt;
1197
1198 SmallVector<DeducedPack, 2> Packs;
1199};
1200
1201} // namespace
1202
1203template <class T>
1205 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1208 bool FinishingDeduction, T &&DeductFunc) {
1209 // C++0x [temp.deduct.type]p10:
1210 // Similarly, if P has a form that contains (T), then each parameter type
1211 // Pi of the respective parameter-type- list of P is compared with the
1212 // corresponding parameter type Ai of the corresponding parameter-type-list
1213 // of A. [...]
1214 unsigned ArgIdx = 0, ParamIdx = 0;
1215 for (; ParamIdx != Params.size(); ++ParamIdx) {
1216 // Check argument types.
1217 const PackExpansionType *Expansion
1218 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1219 if (!Expansion) {
1220 // Simple case: compare the parameter and argument types at this point.
1221
1222 // Make sure we have an argument.
1223 if (ArgIdx >= Args.size())
1225
1226 if (isa<PackExpansionType>(Args[ArgIdx])) {
1227 // C++0x [temp.deduct.type]p22:
1228 // If the original function parameter associated with A is a function
1229 // parameter pack and the function parameter associated with P is not
1230 // a function parameter pack, then template argument deduction fails.
1232 }
1233
1234 if (TemplateDeductionResult Result =
1235 DeductFunc(S, TemplateParams, ParamIdx, ArgIdx,
1236 Params[ParamIdx].getUnqualifiedType(),
1237 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, POK);
1239 return Result;
1240
1241 ++ArgIdx;
1242 continue;
1243 }
1244
1245 // C++0x [temp.deduct.type]p10:
1246 // If the parameter-declaration corresponding to Pi is a function
1247 // parameter pack, then the type of its declarator- id is compared with
1248 // each remaining parameter type in the parameter-type-list of A. Each
1249 // comparison deduces template arguments for subsequent positions in the
1250 // template parameter packs expanded by the function parameter pack.
1251
1252 QualType Pattern = Expansion->getPattern();
1253 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern,
1254 /*DeducePackIfNotAlreadyDeduced=*/false,
1255 FinishingDeduction);
1256
1257 // A pack scope with fixed arity is not really a pack any more, so is not
1258 // a non-deduced context.
1259 if (ParamIdx + 1 == Params.size() || PackScope.hasFixedArity()) {
1260 for (; ArgIdx < Args.size() && PackScope.hasNextElement(); ++ArgIdx) {
1261 // Deduce template arguments from the pattern.
1262 if (TemplateDeductionResult Result = DeductFunc(
1263 S, TemplateParams, ParamIdx, ArgIdx,
1264 Pattern.getUnqualifiedType(), Args[ArgIdx].getUnqualifiedType(),
1265 Info, Deduced, POK);
1267 return Result;
1268 PackScope.nextPackElement();
1269 }
1270 } else {
1271 // C++0x [temp.deduct.type]p5:
1272 // The non-deduced contexts are:
1273 // - A function parameter pack that does not occur at the end of the
1274 // parameter-declaration-clause.
1275 //
1276 // FIXME: There is no wording to say what we should do in this case. We
1277 // choose to resolve this by applying the same rule that is applied for a
1278 // function call: that is, deduce all contained packs to their
1279 // explicitly-specified values (or to <> if there is no such value).
1280 //
1281 // This is seemingly-arbitrarily different from the case of a template-id
1282 // with a non-trailing pack-expansion in its arguments, which renders the
1283 // entire template-argument-list a non-deduced context.
1284
1285 // If the parameter type contains an explicitly-specified pack that we
1286 // could not expand, skip the number of parameters notionally created
1287 // by the expansion.
1288 UnsignedOrNone NumExpansions = Expansion->getNumExpansions();
1289 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1290 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
1291 ++I, ++ArgIdx)
1292 PackScope.nextPackElement();
1293 }
1294 }
1295
1296 // Build argument packs for each of the parameter packs expanded by this
1297 // pack expansion.
1298 if (auto Result = PackScope.finish();
1300 return Result;
1301 }
1302
1303 // DR692, DR1395
1304 // C++0x [temp.deduct.type]p10:
1305 // If the parameter-declaration corresponding to P_i ...
1306 // During partial ordering, if Ai was originally a function parameter pack:
1307 // - if P does not contain a function parameter type corresponding to Ai then
1308 // Ai is ignored;
1309 if (POK == PartialOrderingKind::Call && ArgIdx + 1 == Args.size() &&
1310 isa<PackExpansionType>(Args[ArgIdx]))
1312
1313 // Make sure we don't have any extra arguments.
1314 if (ArgIdx < Args.size())
1316
1318}
1319
1320/// Deduce the template arguments by comparing the list of parameter
1321/// types to the list of argument types, as in the parameter-type-lists of
1322/// function types (C++ [temp.deduct.type]p10).
1323///
1324/// \param S The semantic analysis object within which we are deducing
1325///
1326/// \param TemplateParams The template parameters that we are deducing
1327///
1328/// \param Params The list of parameter types
1329///
1330/// \param Args The list of argument types
1331///
1332/// \param Info information about the template argument deduction itself
1333///
1334/// \param Deduced the deduced template arguments
1335///
1336/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1337/// how template argument deduction is performed.
1338///
1339/// \param PartialOrdering If true, we are performing template argument
1340/// deduction for during partial ordering for a call
1341/// (C++0x [temp.deduct.partial]).
1342///
1343/// \param HasDeducedAnyParam If set, the object pointed at will indicate
1344/// whether any template parameter was deduced.
1345///
1346/// \param HasDeducedParam If set, the bit vector will be used to represent
1347/// which template parameters were deduced, in order.
1348///
1349/// \returns the result of template argument deduction so far. Note that a
1350/// "success" result means that template argument deduction has not yet failed,
1351/// but it may still fail, later, for other reasons.
1353 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1355 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1356 PartialOrderingKind POK, bool *HasDeducedAnyParam,
1357 llvm::SmallBitVector *HasDeducedParam) {
1358 return ::DeduceForEachType(
1359 S, TemplateParams, Params, Args, Info, Deduced, POK,
1360 /*FinishingDeduction=*/false,
1361 [&](Sema &S, TemplateParameterList *TemplateParams, int ParamIdx,
1362 int ArgIdx, QualType P, QualType A, TemplateDeductionInfo &Info,
1364 PartialOrderingKind POK) {
1365 bool HasDeducedAnyParamCopy = false;
1367 S, TemplateParams, P, A, Info, Deduced, TDF, POK,
1368 /*DeducedFromArrayBound=*/false, &HasDeducedAnyParamCopy);
1369 if (HasDeducedAnyParam && HasDeducedAnyParamCopy)
1370 *HasDeducedAnyParam = true;
1371 if (HasDeducedParam && HasDeducedAnyParamCopy)
1372 (*HasDeducedParam)[ParamIdx] = true;
1373 return TDR;
1374 });
1375}
1376
1377/// Determine whether the parameter has qualifiers that the argument
1378/// lacks. Put another way, determine whether there is no way to add
1379/// a deduced set of qualifiers to the ParamType that would result in
1380/// its qualifiers matching those of the ArgType.
1382 QualType ArgType) {
1383 Qualifiers ParamQs = ParamType.getQualifiers();
1384 Qualifiers ArgQs = ArgType.getQualifiers();
1385
1386 if (ParamQs == ArgQs)
1387 return false;
1388
1389 // Mismatched (but not missing) Objective-C GC attributes.
1390 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1391 ParamQs.hasObjCGCAttr())
1392 return true;
1393
1394 // Mismatched (but not missing) address spaces.
1395 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1396 ParamQs.hasAddressSpace())
1397 return true;
1398
1399 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1400 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1401 ParamQs.hasObjCLifetime())
1402 return true;
1403
1404 // CVR qualifiers inconsistent or a superset.
1405 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1406}
1407
1409 const FunctionType *PF = P->getAs<FunctionType>(),
1410 *AF = A->getAs<FunctionType>();
1411
1412 // Just compare if not functions.
1413 if (!PF || !AF)
1414 return Context.hasSameType(P, A);
1415
1416 // Noreturn and noexcept adjustment.
1417 if (QualType AdjustedParam; TryFunctionConversion(P, A, AdjustedParam))
1418 P = AdjustedParam;
1419
1420 // FIXME: Compatible calling conventions.
1421 return Context.hasSameFunctionTypeIgnoringExceptionSpec(P, A);
1422}
1423
1424/// Get the index of the first template parameter that was originally from the
1425/// innermost template-parameter-list. This is 0 except when we concatenate
1426/// the template parameter lists of a class template and a constructor template
1427/// when forming an implicit deduction guide.
1429 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1430 if (!Guide || !Guide->isImplicit())
1431 return 0;
1432 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1433}
1434
1435/// Determine whether a type denotes a forwarding reference.
1436static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1437 // C++1z [temp.deduct.call]p3:
1438 // A forwarding reference is an rvalue reference to a cv-unqualified
1439 // template parameter that does not represent a template parameter of a
1440 // class template.
1441 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1442 if (ParamRef->getPointeeType().getQualifiers())
1443 return false;
1444 auto *TypeParm =
1445 ParamRef->getPointeeType()->getAsCanonical<TemplateTypeParmType>();
1446 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1447 }
1448 return false;
1449}
1450
1451/// Attempt to deduce the template arguments by checking the base types
1452/// according to (C++20 [temp.deduct.call] p4b3.
1453///
1454/// \param S the semantic analysis object within which we are deducing.
1455///
1456/// \param RD the top level record object we are deducing against.
1457///
1458/// \param TemplateParams the template parameters that we are deducing.
1459///
1460/// \param P the template specialization parameter type.
1461///
1462/// \param Info information about the template argument deduction itself.
1463///
1464/// \param Deduced the deduced template arguments.
1465///
1466/// \returns the result of template argument deduction with the bases. "invalid"
1467/// means no matches, "success" found a single item, and the
1468/// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
1471 TemplateParameterList *TemplateParams, QualType P,
1474 bool *HasDeducedAnyParam) {
1475 // C++14 [temp.deduct.call] p4b3:
1476 // If P is a class and P has the form simple-template-id, then the
1477 // transformed A can be a derived class of the deduced A. Likewise if
1478 // P is a pointer to a class of the form simple-template-id, the
1479 // transformed A can be a pointer to a derived class pointed to by the
1480 // deduced A. However, if there is a class C that is a (direct or
1481 // indirect) base class of D and derived (directly or indirectly) from a
1482 // class B and that would be a valid deduced A, the deduced A cannot be
1483 // B or pointer to B, respectively.
1484 //
1485 // These alternatives are considered only if type deduction would
1486 // otherwise fail. If they yield more than one possible deduced A, the
1487 // type deduction fails.
1488
1489 // Use a breadth-first search through the bases to collect the set of
1490 // successful matches. Visited contains the set of nodes we have already
1491 // visited, while ToVisit is our stack of records that we still need to
1492 // visit. Matches contains a list of matches that have yet to be
1493 // disqualified.
1496 // We iterate over this later, so we have to use MapVector to ensure
1497 // determinism.
1498 struct MatchValue {
1500 bool HasDeducedAnyParam;
1501 };
1502 llvm::MapVector<const CXXRecordDecl *, MatchValue> Matches;
1503
1504 auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
1505 for (const auto &Base : RD->bases()) {
1506 QualType T = Base.getType();
1507 assert(T->isRecordType() && "Base class that isn't a record?");
1508 if (Visited.insert(T->getAsCXXRecordDecl()).second)
1509 ToVisit.push_back(T);
1510 }
1511 };
1512
1513 // Set up the loop by adding all the bases.
1514 AddBases(RD);
1515
1516 // Search each path of bases until we either run into a successful match
1517 // (where all bases of it are invalid), or we run out of bases.
1518 while (!ToVisit.empty()) {
1519 QualType NextT = ToVisit.pop_back_val();
1520
1521 SmallVector<DeducedTemplateArgument, 8> DeducedCopy(Deduced.begin(),
1522 Deduced.end());
1524 bool HasDeducedAnyParamCopy = false;
1526 S, TemplateParams, P, NextT, BaseInfo, PartialOrdering, DeducedCopy,
1527 &HasDeducedAnyParamCopy);
1528
1529 // If this was a successful deduction, add it to the list of matches,
1530 // otherwise we need to continue searching its bases.
1531 const CXXRecordDecl *RD = NextT->getAsCXXRecordDecl();
1533 Matches.insert({RD, {DeducedCopy, HasDeducedAnyParamCopy}});
1534 else
1535 AddBases(RD);
1536 }
1537
1538 // At this point, 'Matches' contains a list of seemingly valid bases, however
1539 // in the event that we have more than 1 match, it is possible that the base
1540 // of one of the matches might be disqualified for being a base of another
1541 // valid match. We can count on cyclical instantiations being invalid to
1542 // simplify the disqualifications. That is, if A & B are both matches, and B
1543 // inherits from A (disqualifying A), we know that A cannot inherit from B.
1544 if (Matches.size() > 1) {
1545 Visited.clear();
1546 for (const auto &Match : Matches)
1547 AddBases(Match.first);
1548
1549 // We can give up once we have a single item (or have run out of things to
1550 // search) since cyclical inheritance isn't valid.
1551 while (Matches.size() > 1 && !ToVisit.empty()) {
1552 const CXXRecordDecl *RD = ToVisit.pop_back_val()->getAsCXXRecordDecl();
1553 Matches.erase(RD);
1554
1555 // Always add all bases, since the inheritance tree can contain
1556 // disqualifications for multiple matches.
1557 AddBases(RD);
1558 }
1559 }
1560
1561 if (Matches.empty())
1563 if (Matches.size() > 1)
1565
1566 std::swap(Matches.front().second.Deduced, Deduced);
1567 if (bool HasDeducedAnyParamCopy = Matches.front().second.HasDeducedAnyParam;
1568 HasDeducedAnyParamCopy && HasDeducedAnyParam)
1569 *HasDeducedAnyParam = HasDeducedAnyParamCopy;
1571}
1572
1573/// When propagating a partial ordering kind into a NonCall context,
1574/// this is used to downgrade a 'Call' into a 'NonCall', so that
1575/// the kind still reflects whether we are in a partial ordering context.
1580
1581/// Deduce the template arguments by comparing the parameter type and
1582/// the argument type (C++ [temp.deduct.type]).
1583///
1584/// \param S the semantic analysis object within which we are deducing
1585///
1586/// \param TemplateParams the template parameters that we are deducing
1587///
1588/// \param P the parameter type
1589///
1590/// \param A the argument type
1591///
1592/// \param Info information about the template argument deduction itself
1593///
1594/// \param Deduced the deduced template arguments
1595///
1596/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1597/// how template argument deduction is performed.
1598///
1599/// \param PartialOrdering Whether we're performing template argument deduction
1600/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1601///
1602/// \returns the result of template argument deduction so far. Note that a
1603/// "success" result means that template argument deduction has not yet failed,
1604/// but it may still fail, later, for other reasons.
1606 Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
1608 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1609 PartialOrderingKind POK, bool DeducedFromArrayBound,
1610 bool *HasDeducedAnyParam) {
1611
1612 // If the argument type is a pack expansion, look at its pattern.
1613 // This isn't explicitly called out
1614 if (const auto *AExp = dyn_cast<PackExpansionType>(A))
1615 A = AExp->getPattern();
1617
1618 if (POK == PartialOrderingKind::Call) {
1619 // C++11 [temp.deduct.partial]p5:
1620 // Before the partial ordering is done, certain transformations are
1621 // performed on the types used for partial ordering:
1622 // - If P is a reference type, P is replaced by the type referred to.
1623 const ReferenceType *PRef = P->getAs<ReferenceType>();
1624 if (PRef)
1625 P = PRef->getPointeeType();
1626
1627 // - If A is a reference type, A is replaced by the type referred to.
1628 const ReferenceType *ARef = A->getAs<ReferenceType>();
1629 if (ARef)
1630 A = A->getPointeeType();
1631
1632 if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
1633 // C++11 [temp.deduct.partial]p9:
1634 // If, for a given type, deduction succeeds in both directions (i.e.,
1635 // the types are identical after the transformations above) and both
1636 // P and A were reference types [...]:
1637 // - if [one type] was an lvalue reference and [the other type] was
1638 // not, [the other type] is not considered to be at least as
1639 // specialized as [the first type]
1640 // - if [one type] is more cv-qualified than [the other type],
1641 // [the other type] is not considered to be at least as specialized
1642 // as [the first type]
1643 // Objective-C ARC adds:
1644 // - [one type] has non-trivial lifetime, [the other type] has
1645 // __unsafe_unretained lifetime, and the types are otherwise
1646 // identical
1647 //
1648 // A is "considered to be at least as specialized" as P iff deduction
1649 // succeeds, so we model this as a deduction failure. Note that
1650 // [the first type] is P and [the other type] is A here; the standard
1651 // gets this backwards.
1652 Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
1653 if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
1654 PQuals.isStrictSupersetOf(AQuals) ||
1655 (PQuals.hasNonTrivialObjCLifetime() &&
1656 AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1657 PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
1658 Info.FirstArg = TemplateArgument(P);
1659 Info.SecondArg = TemplateArgument(A);
1661 }
1662 }
1663 Qualifiers DiscardedQuals;
1664 // C++11 [temp.deduct.partial]p7:
1665 // Remove any top-level cv-qualifiers:
1666 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1667 // version of P.
1668 P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
1669 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1670 // version of A.
1671 A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
1672 } else {
1673 // C++0x [temp.deduct.call]p4 bullet 1:
1674 // - If the original P is a reference type, the deduced A (i.e., the type
1675 // referred to by the reference) can be more cv-qualified than the
1676 // transformed A.
1677 if (TDF & TDF_ParamWithReferenceType) {
1678 Qualifiers Quals;
1679 QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
1681 P = S.Context.getQualifiedType(UnqualP, Quals);
1682 }
1683
1684 if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
1685 // C++0x [temp.deduct.type]p10:
1686 // If P and A are function types that originated from deduction when
1687 // taking the address of a function template (14.8.2.2) or when deducing
1688 // template arguments from a function declaration (14.8.2.6) and Pi and
1689 // Ai are parameters of the top-level parameter-type-list of P and A,
1690 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1691 // is an lvalue reference, in
1692 // which case the type of Pi is changed to be the template parameter
1693 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1694 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1695 // deduced as X&. - end note ]
1697 if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
1699 P = P->getPointeeType();
1700 }
1701 }
1702
1703 // C++ [temp.deduct.type]p9:
1704 // A template type argument T, a template template argument TT or a
1705 // template non-type argument i can be deduced if P and A have one of
1706 // the following forms:
1707 //
1708 // T
1709 // cv-list T
1710 if (const auto *TTP = P->getAsCanonical<TemplateTypeParmType>()) {
1711 // Just skip any attempts to deduce from a placeholder type or a parameter
1712 // at a different depth.
1713 if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
1715
1716 unsigned Index = TTP->getIndex();
1717
1718 // If the argument type is an array type, move the qualifiers up to the
1719 // top level, so they can be matched with the qualifiers on the parameter.
1720 if (A->isArrayType()) {
1721 Qualifiers Quals;
1722 A = S.Context.getUnqualifiedArrayType(A, Quals);
1723 if (Quals)
1724 A = S.Context.getQualifiedType(A, Quals);
1725 }
1726
1727 // The argument type can not be less qualified than the parameter
1728 // type.
1729 if (!(TDF & TDF_IgnoreQualifiers) &&
1731 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1732 Info.FirstArg = TemplateArgument(P);
1733 Info.SecondArg = TemplateArgument(A);
1735 }
1736
1737 // Do not match a function type with a cv-qualified type.
1738 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1739 if (A->isFunctionType() && P.hasQualifiers())
1741
1742 assert(TTP->getDepth() == Info.getDeducedDepth() &&
1743 "saw template type parameter with wrong depth");
1744 assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&
1745 "Unresolved overloaded function");
1746 QualType DeducedType = A;
1747
1748 // Remove any qualifiers on the parameter from the deduced type.
1749 // We checked the qualifiers for consistency above.
1750 Qualifiers DeducedQs = DeducedType.getQualifiers();
1751 Qualifiers ParamQs = P.getQualifiers();
1752 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1753 if (ParamQs.hasObjCGCAttr())
1754 DeducedQs.removeObjCGCAttr();
1755 if (ParamQs.hasAddressSpace())
1756 DeducedQs.removeAddressSpace();
1757 if (ParamQs.hasObjCLifetime())
1758 DeducedQs.removeObjCLifetime();
1759
1760 // Objective-C ARC:
1761 // If template deduction would produce a lifetime qualifier on a type
1762 // that is not a lifetime type, template argument deduction fails.
1763 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1764 !DeducedType->isDependentType()) {
1765 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1766 Info.FirstArg = TemplateArgument(P);
1767 Info.SecondArg = TemplateArgument(A);
1769 }
1770
1771 // Objective-C ARC:
1772 // If template deduction would produce an argument type with lifetime type
1773 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1774 if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
1775 !DeducedQs.hasObjCLifetime())
1777
1778 DeducedType =
1779 S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
1780
1781 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1783 checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
1784 if (Result.isNull()) {
1785 // We can also get inconsistencies when matching NTTP type.
1786 switch (NamedDecl *Param = TemplateParams->getParam(Index);
1787 Param->getKind()) {
1788 case Decl::TemplateTypeParm:
1789 Info.Param = cast<TemplateTypeParmDecl>(Param);
1790 break;
1791 case Decl::NonTypeTemplateParm:
1793 break;
1794 case Decl::TemplateTemplateParm:
1796 break;
1797 default:
1798 llvm_unreachable("unexpected kind");
1799 }
1800 Info.FirstArg = Deduced[Index];
1801 Info.SecondArg = NewDeduced;
1803 }
1804
1805 Deduced[Index] = Result;
1806 if (HasDeducedAnyParam)
1807 *HasDeducedAnyParam = true;
1809 }
1810
1811 // Set up the template argument deduction information for a failure.
1812 Info.FirstArg = TemplateArgument(P);
1813 Info.SecondArg = TemplateArgument(A);
1814
1815 // If the parameter is an already-substituted template parameter
1816 // pack, do nothing: we don't know which of its arguments to look
1817 // at, so we have to wait until all of the parameter packs in this
1818 // expansion have arguments.
1819 if (P->getAs<SubstTemplateTypeParmPackType>())
1821
1822 // Check the cv-qualifiers on the parameter and argument types.
1823 if (!(TDF & TDF_IgnoreQualifiers)) {
1824 if (TDF & TDF_ParamWithReferenceType) {
1827 } else if (TDF & TDF_ArgWithReferenceType) {
1828 // C++ [temp.deduct.conv]p4:
1829 // If the original A is a reference type, A can be more cv-qualified
1830 // than the deduced A
1832 S.getASTContext()))
1834
1835 // Strip out all extra qualifiers from the argument to figure out the
1836 // type we're converting to, prior to the qualification conversion.
1837 Qualifiers Quals;
1838 A = S.Context.getUnqualifiedArrayType(A, Quals);
1840 } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
1841 if (P.getCVRQualifiers() != A.getCVRQualifiers())
1843 }
1844 }
1845
1846 // If the parameter type is not dependent, there is nothing to deduce.
1847 if (!P->isDependentType()) {
1848 if (TDF & TDF_SkipNonDependent)
1851 : S.Context.hasSameType(P, A))
1856 if (!(TDF & TDF_IgnoreQualifiers))
1858 // Otherwise, when ignoring qualifiers, the types not having the same
1859 // unqualified type does not mean they do not match, so in this case we
1860 // must keep going and analyze with a non-dependent parameter type.
1861 }
1862
1863 switch (P.getCanonicalType()->getTypeClass()) {
1864 // Non-canonical types cannot appear here.
1865#define NON_CANONICAL_TYPE(Class, Base) \
1866 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1867#define TYPE(Class, Base)
1868#include "clang/AST/TypeNodes.inc"
1869
1870 case Type::TemplateTypeParm:
1871 case Type::SubstTemplateTypeParmPack:
1872 case Type::SubstBuiltinTemplatePack:
1873 llvm_unreachable("Type nodes handled above");
1874
1875 case Type::Auto:
1876 // C++23 [temp.deduct.funcaddr]/3:
1877 // A placeholder type in the return type of a function template is a
1878 // non-deduced context.
1879 // There's no corresponding wording for [temp.deduct.decl], but we treat
1880 // it the same to match other compilers.
1881 if (P->isDependentType())
1883 [[fallthrough]];
1884 case Type::Builtin:
1885 case Type::VariableArray:
1886 case Type::Vector:
1887 case Type::FunctionNoProto:
1888 case Type::Record:
1889 case Type::Enum:
1890 case Type::ObjCObject:
1891 case Type::ObjCInterface:
1892 case Type::ObjCObjectPointer:
1893 case Type::BitInt:
1894 return (TDF & TDF_SkipNonDependent) ||
1895 ((TDF & TDF_IgnoreQualifiers)
1897 : S.Context.hasSameType(P, A))
1900
1901 // _Complex T [placeholder extension]
1902 case Type::Complex: {
1903 const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
1904 if (!CA)
1907 S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
1908 Deduced, TDF, degradeCallPartialOrderingKind(POK),
1909 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1910 }
1911
1912 // _Atomic T [extension]
1913 case Type::Atomic: {
1914 const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
1915 if (!AA)
1918 S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
1919 Deduced, TDF, degradeCallPartialOrderingKind(POK),
1920 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1921 }
1922
1923 // T *
1924 case Type::Pointer: {
1925 QualType PointeeType;
1926 if (const auto *PA = A->getAs<PointerType>()) {
1927 PointeeType = PA->getPointeeType();
1928 } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
1929 PointeeType = PA->getPointeeType();
1930 } else {
1932 }
1934 S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
1935 PointeeType, Info, Deduced,
1938 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1939 }
1940
1941 // T &
1942 case Type::LValueReference: {
1943 const auto *RP = P->castAs<LValueReferenceType>(),
1944 *RA = A->getAs<LValueReferenceType>();
1945 if (!RA)
1947
1949 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1950 Deduced, 0, degradeCallPartialOrderingKind(POK),
1951 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1952 }
1953
1954 // T && [C++0x]
1955 case Type::RValueReference: {
1956 const auto *RP = P->castAs<RValueReferenceType>(),
1957 *RA = A->getAs<RValueReferenceType>();
1958 if (!RA)
1960
1962 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1963 Deduced, 0, degradeCallPartialOrderingKind(POK),
1964 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1965 }
1966
1967 // T [] (implied, but not stated explicitly)
1968 case Type::IncompleteArray: {
1969 const auto *IAA = S.Context.getAsIncompleteArrayType(A);
1970 if (!IAA)
1972
1973 const auto *IAP = S.Context.getAsIncompleteArrayType(P);
1974 assert(IAP && "Template parameter not of incomplete array type");
1975
1977 S, TemplateParams, IAP->getElementType(), IAA->getElementType(), Info,
1978 Deduced, TDF & TDF_IgnoreQualifiers,
1980 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1981 }
1982
1983 // T [integer-constant]
1984 case Type::ConstantArray: {
1985 const auto *CAA = S.Context.getAsConstantArrayType(A),
1986 *CAP = S.Context.getAsConstantArrayType(P);
1987 assert(CAP);
1988 if (!CAA || CAA->getSize() != CAP->getSize())
1990
1992 S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
1993 Deduced, TDF & TDF_IgnoreQualifiers,
1995 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1996 }
1997
1998 // type [i]
1999 case Type::DependentSizedArray: {
2000 const auto *AA = S.Context.getAsArrayType(A);
2001 if (!AA)
2003
2004 // Check the element type of the arrays
2005 const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
2006 assert(DAP);
2007 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2008 S, TemplateParams, DAP->getElementType(), AA->getElementType(),
2009 Info, Deduced, TDF & TDF_IgnoreQualifiers,
2011 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2013 return Result;
2014
2015 // Determine the array bound is something we can deduce.
2017 getDeducedNTTParameterFromExpr(Info, DAP->getSizeExpr());
2018 if (!NTTP)
2020
2021 // We can perform template argument deduction for the given non-type
2022 // template parameter.
2023 assert(NTTP.getDepth() == Info.getDeducedDepth() &&
2024 "saw non-type template parameter with wrong depth");
2025 if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
2026 llvm::APSInt Size(CAA->getSize());
2028 S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
2029 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
2030 Deduced, HasDeducedAnyParam);
2031 }
2032 if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
2033 if (DAA->getSizeExpr())
2035 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info,
2036 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2037
2038 // Incomplete type does not match a dependently-sized array type
2040 }
2041
2042 // type(*)(T)
2043 // T(*)()
2044 // T(*)(T)
2045 case Type::FunctionProto: {
2046 const auto *FPP = P->castAs<FunctionProtoType>(),
2047 *FPA = A->getAs<FunctionProtoType>();
2048 if (!FPA)
2050
2051 if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
2052 FPP->getRefQualifier() != FPA->getRefQualifier() ||
2053 FPP->isVariadic() != FPA->isVariadic())
2055
2056 // Check return types.
2057 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2058 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
2059 Info, Deduced, 0, degradeCallPartialOrderingKind(POK),
2060 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2062 return Result;
2063
2064 // Check parameter types.
2065 if (auto Result = DeduceTemplateArguments(
2066 S, TemplateParams, FPP->param_types(), FPA->param_types(), Info,
2067 Deduced, TDF & TDF_TopLevelParameterTypeList, POK,
2068 HasDeducedAnyParam,
2069 /*HasDeducedParam=*/nullptr);
2071 return Result;
2072
2075
2076 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
2077 // deducing through the noexcept-specifier if it's part of the canonical
2078 // type. libstdc++ relies on this.
2079 Expr *NoexceptExpr = FPP->getNoexceptExpr();
2081 NoexceptExpr ? getDeducedNTTParameterFromExpr(Info, NoexceptExpr)
2082 : nullptr) {
2083 assert(NTTP.getDepth() == Info.getDeducedDepth() &&
2084 "saw non-type template parameter with wrong depth");
2085
2086 llvm::APSInt Noexcept(1);
2087 switch (FPA->canThrow()) {
2088 case CT_Cannot:
2089 Noexcept = 1;
2090 [[fallthrough]];
2091
2092 case CT_Can:
2093 // We give E in noexcept(E) the "deduced from array bound" treatment.
2094 // FIXME: Should we?
2096 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
2097 /*DeducedFromArrayBound=*/true, Info,
2098 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2099
2100 case CT_Dependent:
2101 if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
2103 S, TemplateParams, NTTP, ArgNoexceptExpr, Info,
2104 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2105 // Can't deduce anything from throw(T...).
2106 break;
2107 }
2108 }
2109 // FIXME: Detect non-deduced exception specification mismatches?
2110 //
2111 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
2112 // top-level differences in noexcept-specifications.
2113
2115 }
2116
2117 case Type::InjectedClassName:
2118 // Treat a template's injected-class-name as if the template
2119 // specialization type had been used.
2120
2121 // template-name<T> (where template-name refers to a class template)
2122 // template-name<i>
2123 // TT<T>
2124 // TT<i>
2125 // TT<>
2126 case Type::TemplateSpecialization: {
2127 // When Arg cannot be a derived class, we can just try to deduce template
2128 // arguments from the template-id.
2129 if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
2130 return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
2132 Deduced, HasDeducedAnyParam);
2133
2134 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
2135 Deduced.end());
2136
2137 auto Result = DeduceTemplateSpecArguments(
2138 S, TemplateParams, P, A, Info, POK != PartialOrderingKind::None,
2139 Deduced, HasDeducedAnyParam);
2141 return Result;
2142
2143 // We cannot inspect base classes as part of deduction when the type
2144 // is incomplete, so either instantiate any templates necessary to
2145 // complete the type, or skip over it if it cannot be completed.
2146 if (!S.isCompleteType(Info.getLocation(), A))
2147 return Result;
2148
2149 const CXXRecordDecl *RD = A->getAsCXXRecordDecl();
2150 if (RD->isInvalidDecl())
2151 return Result;
2152
2153 // Reset the incorrectly deduced argument from above.
2154 Deduced = DeducedOrig;
2155
2156 // Check bases according to C++14 [temp.deduct.call] p4b3:
2157 auto BaseResult = DeduceTemplateBases(S, RD, TemplateParams, P, Info,
2159 Deduced, HasDeducedAnyParam);
2161 : Result;
2162 }
2163
2164 // T type::*
2165 // T T::*
2166 // T (type::*)()
2167 // type (T::*)()
2168 // type (type::*)(T)
2169 // type (T::*)(T)
2170 // T (type::*)(T)
2171 // T (T::*)()
2172 // T (T::*)(T)
2173 case Type::MemberPointer: {
2174 const auto *MPP = P->castAs<MemberPointerType>(),
2175 *MPA = A->getAs<MemberPointerType>();
2176 if (!MPA)
2178
2179 QualType PPT = MPP->getPointeeType();
2180 if (PPT->isFunctionType())
2181 S.adjustMemberFunctionCC(PPT, /*HasThisPointer=*/false,
2182 /*IsCtorOrDtor=*/false, Info.getLocation());
2183 QualType APT = MPA->getPointeeType();
2184 if (APT->isFunctionType())
2185 S.adjustMemberFunctionCC(APT, /*HasThisPointer=*/false,
2186 /*IsCtorOrDtor=*/false, Info.getLocation());
2187
2188 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
2189 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2190 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF,
2192 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2194 return Result;
2195
2196 QualType TP =
2197 MPP->isSugared()
2198 ? S.Context.getCanonicalTagType(MPP->getMostRecentCXXRecordDecl())
2199 : QualType(MPP->getQualifier().getAsType(), 0);
2200 assert(!TP.isNull() && "member pointer with non-type class");
2201
2202 QualType TA =
2203 MPA->isSugared()
2204 ? S.Context.getCanonicalTagType(MPA->getMostRecentCXXRecordDecl())
2205 : QualType(MPA->getQualifier().getAsType(), 0)
2207 assert(!TA.isNull() && "member pointer with non-type class");
2208
2210 S, TemplateParams, TP, TA, Info, Deduced, SubTDF,
2212 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2213 }
2214
2215 // (clang extension)
2216 //
2217 // type(^)(T)
2218 // T(^)()
2219 // T(^)(T)
2220 case Type::BlockPointer: {
2221 const auto *BPP = P->castAs<BlockPointerType>(),
2222 *BPA = A->getAs<BlockPointerType>();
2223 if (!BPA)
2226 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
2227 Deduced, 0, degradeCallPartialOrderingKind(POK),
2228 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2229 }
2230
2231 // (clang extension)
2232 //
2233 // T __attribute__(((ext_vector_type(<integral constant>))))
2234 case Type::ExtVector: {
2235 const auto *VP = P->castAs<ExtVectorType>();
2236 QualType ElementType;
2237 if (const auto *VA = A->getAs<ExtVectorType>()) {
2238 // Make sure that the vectors have the same number of elements.
2239 if (VP->getNumElements() != VA->getNumElements())
2241 ElementType = VA->getElementType();
2242 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2243 // We can't check the number of elements, since the argument has a
2244 // dependent number of elements. This can only occur during partial
2245 // ordering.
2246 ElementType = VA->getElementType();
2247 } else {
2249 }
2250 // Perform deduction on the element types.
2252 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
2254 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2255 }
2256
2257 case Type::DependentVector: {
2258 const auto *VP = P->castAs<DependentVectorType>();
2259
2260 if (const auto *VA = A->getAs<VectorType>()) {
2261 // Perform deduction on the element types.
2262 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2263 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2264 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2265 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2267 return Result;
2268
2269 // Perform deduction on the vector size, if we can.
2271 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2272 if (!NTTP)
2274
2275 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2276 ArgSize = VA->getNumElements();
2277 // Note that we use the "array bound" rules here; just like in that
2278 // case, we don't have any particular type for the vector size, but
2279 // we can provide one if necessary.
2281 S, TemplateParams, NTTP, ArgSize, S.Context.UnsignedIntTy, true,
2282 Info, POK != PartialOrderingKind::None, Deduced,
2283 HasDeducedAnyParam);
2284 }
2285
2286 if (const auto *VA = A->getAs<DependentVectorType>()) {
2287 // Perform deduction on the element types.
2288 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2289 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2290 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2291 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2293 return Result;
2294
2295 // Perform deduction on the vector size, if we can.
2297 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2298 if (!NTTP)
2300
2302 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2303 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2304 }
2305
2307 }
2308
2309 // (clang extension)
2310 //
2311 // T __attribute__(((ext_vector_type(N))))
2312 case Type::DependentSizedExtVector: {
2313 const auto *VP = P->castAs<DependentSizedExtVectorType>();
2314
2315 if (const auto *VA = A->getAs<ExtVectorType>()) {
2316 // Perform deduction on the element types.
2317 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2318 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2319 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2320 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2322 return Result;
2323
2324 // Perform deduction on the vector size, if we can.
2326 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2327 if (!NTTP)
2329
2330 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2331 ArgSize = VA->getNumElements();
2332 // Note that we use the "array bound" rules here; just like in that
2333 // case, we don't have any particular type for the vector size, but
2334 // we can provide one if necessary.
2336 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2337 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2338 }
2339
2340 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2341 // Perform deduction on the element types.
2342 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2343 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2344 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2345 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2347 return Result;
2348
2349 // Perform deduction on the vector size, if we can.
2351 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2352 if (!NTTP)
2354
2356 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2357 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2358 }
2359
2361 }
2362
2363 // (clang extension)
2364 //
2365 // T __attribute__((matrix_type(<integral constant>,
2366 // <integral constant>)))
2367 case Type::ConstantMatrix: {
2368 const auto *MP = P->castAs<ConstantMatrixType>(),
2369 *MA = A->getAs<ConstantMatrixType>();
2370 if (!MA)
2372
2373 // Check that the dimensions are the same
2374 if (MP->getNumRows() != MA->getNumRows() ||
2375 MP->getNumColumns() != MA->getNumColumns()) {
2377 }
2378 // Perform deduction on element types.
2380 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2381 Deduced, TDF, degradeCallPartialOrderingKind(POK),
2382 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2383 }
2384
2385 case Type::DependentSizedMatrix: {
2386 const auto *MP = P->castAs<DependentSizedMatrixType>();
2387 const auto *MA = A->getAs<MatrixType>();
2388 if (!MA)
2390
2391 // Check the element type of the matrixes.
2392 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2393 S, TemplateParams, MP->getElementType(), MA->getElementType(),
2394 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2395 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2397 return Result;
2398
2399 // Try to deduce a matrix dimension.
2400 auto DeduceMatrixArg =
2401 [&S, &Info, &Deduced, &TemplateParams, &HasDeducedAnyParam, POK](
2402 Expr *ParamExpr, const MatrixType *A,
2403 unsigned (ConstantMatrixType::*GetArgDimension)() const,
2404 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2405 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2406 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
2407 if (!ParamExpr->isValueDependent()) {
2408 std::optional<llvm::APSInt> ParamConst =
2409 ParamExpr->getIntegerConstantExpr(S.Context);
2410 if (!ParamConst)
2412
2413 if (ACM) {
2414 if ((ACM->*GetArgDimension)() == *ParamConst)
2417 }
2418
2419 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2420 if (std::optional<llvm::APSInt> ArgConst =
2421 ArgExpr->getIntegerConstantExpr(S.Context))
2422 if (*ArgConst == *ParamConst)
2425 }
2426
2428 getDeducedNTTParameterFromExpr(Info, ParamExpr);
2429 if (!NTTP)
2431
2432 if (ACM) {
2433 llvm::APSInt ArgConst(
2435 ArgConst = (ACM->*GetArgDimension)();
2437 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
2438 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
2439 Deduced, HasDeducedAnyParam);
2440 }
2441
2443 S, TemplateParams, NTTP, (ADM->*GetArgDimensionExpr)(), Info,
2444 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2445 };
2446
2447 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
2451 return Result;
2452
2453 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2456 }
2457
2458 // (clang extension)
2459 //
2460 // T __attribute__(((address_space(N))))
2461 case Type::DependentAddressSpace: {
2462 const auto *ASP = P->castAs<DependentAddressSpaceType>();
2463
2464 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
2465 // Perform deduction on the pointer type.
2466 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2467 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2468 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2469 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2471 return Result;
2472
2473 // Perform deduction on the address space, if we can.
2475 getDeducedNTTParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2476 if (!NTTP)
2478
2480 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info,
2481 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2482 }
2483
2485 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2486 false);
2487 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
2488
2489 // Perform deduction on the pointer types.
2490 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2491 S, TemplateParams, ASP->getPointeeType(),
2492 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF,
2494 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2496 return Result;
2497
2498 // Perform deduction on the address space, if we can.
2500 getDeducedNTTParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2501 if (!NTTP)
2503
2505 S, TemplateParams, NTTP, ArgAddressSpace, S.Context.IntTy, true,
2506 Info, POK != PartialOrderingKind::None, Deduced,
2507 HasDeducedAnyParam);
2508 }
2509
2511 }
2512 case Type::DependentBitInt: {
2513 const auto *IP = P->castAs<DependentBitIntType>();
2514
2515 if (const auto *IA = A->getAs<BitIntType>()) {
2516 if (IP->isUnsigned() != IA->isUnsigned())
2518
2520 getDeducedNTTParameterFromExpr(Info, IP->getNumBitsExpr());
2521 if (!NTTP)
2523
2524 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2525 ArgSize = IA->getNumBits();
2526
2528 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2529 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2530 }
2531
2532 if (const auto *IA = A->getAs<DependentBitIntType>()) {
2533 if (IP->isUnsigned() != IA->isUnsigned())
2536 }
2537
2539 }
2540
2541 case Type::TypeOfExpr:
2542 case Type::TypeOf:
2543 case Type::DependentName:
2544 case Type::UnresolvedUsing:
2545 case Type::Decltype:
2546 case Type::UnaryTransform:
2547 case Type::DeducedTemplateSpecialization:
2548 case Type::PackExpansion:
2549 case Type::Pipe:
2550 case Type::ArrayParameter:
2551 case Type::HLSLAttributedResource:
2552 case Type::HLSLInlineSpirv:
2553 // No template argument deduction for these types
2555
2556 case Type::PackIndexing: {
2557 const PackIndexingType *PIT = P->getAs<PackIndexingType>();
2558 if (PIT->hasSelectedType()) {
2560 S, TemplateParams, PIT->getSelectedType(), A, Info, Deduced, TDF,
2562 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2563 }
2565 }
2566 }
2567
2568 llvm_unreachable("Invalid Type Class!");
2569}
2570
2576 bool *HasDeducedAnyParam) {
2577 // If the template argument is a pack expansion, perform template argument
2578 // deduction against the pattern of that expansion. This only occurs during
2579 // partial ordering.
2580 if (A.isPackExpansion())
2582
2583 switch (P.getKind()) {
2585 llvm_unreachable("Null template argument in parameter list");
2586
2590 S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0,
2593 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2594 Info.FirstArg = P;
2595 Info.SecondArg = A;
2597
2599 // PartialOrdering does not matter here, since template specializations are
2600 // not being deduced.
2603 S, TemplateParams, P.getAsTemplate(), A.getAsTemplate(), Info,
2604 /*DefaultArguments=*/{}, /*PartialOrdering=*/false, Deduced,
2605 HasDeducedAnyParam);
2606 Info.FirstArg = P;
2607 Info.SecondArg = A;
2609
2611 llvm_unreachable("caller should handle pack expansions");
2612
2617
2618 Info.FirstArg = P;
2619 Info.SecondArg = A;
2621
2623 // 'nullptr' has only one possible value, so it always matches.
2626 Info.FirstArg = P;
2627 Info.SecondArg = A;
2629
2632 if (llvm::APSInt::isSameValue(P.getAsIntegral(), A.getAsIntegral()))
2634 }
2635 Info.FirstArg = P;
2636 Info.SecondArg = A;
2638
2640 // FIXME: structural equality will also compare types,
2641 // but they should match iff they have the same value.
2643 A.structurallyEquals(P))
2645
2646 Info.FirstArg = P;
2647 Info.SecondArg = A;
2649
2653 switch (A.getKind()) {
2655 // The type of the value is the type of the expression as written.
2657 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2659 PartialOrdering, Deduced, HasDeducedAnyParam);
2660 }
2664 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2666 HasDeducedAnyParam);
2667
2670 S, TemplateParams, NTTP, A.getNullPtrType(), Info, PartialOrdering,
2671 Deduced, HasDeducedAnyParam);
2672
2675 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
2676 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
2677
2683 Info.FirstArg = P;
2684 Info.SecondArg = A;
2686 }
2687 llvm_unreachable("Unknown template argument kind");
2688 }
2689 // Can't deduce anything, but that's okay.
2692 llvm_unreachable("Argument packs should be expanded by the caller!");
2693 }
2694
2695 llvm_unreachable("Invalid TemplateArgument Kind!");
2696}
2697
2698/// Determine whether there is a template argument to be used for
2699/// deduction.
2700///
2701/// This routine "expands" argument packs in-place, overriding its input
2702/// parameters so that \c Args[ArgIdx] will be the available template argument.
2703///
2704/// \returns true if there is another template argument (which will be at
2705/// \c Args[ArgIdx]), false otherwise.
2707 unsigned &ArgIdx) {
2708 if (ArgIdx == Args.size())
2709 return false;
2710
2711 const TemplateArgument &Arg = Args[ArgIdx];
2712 if (Arg.getKind() != TemplateArgument::Pack)
2713 return true;
2714
2715 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2716 Args = Arg.pack_elements();
2717 ArgIdx = 0;
2718 return ArgIdx < Args.size();
2719}
2720
2721/// Determine whether the given set of template arguments has a pack
2722/// expansion that is not the last template argument.
2724 bool FoundPackExpansion = false;
2725 for (const auto &A : Args) {
2726 if (FoundPackExpansion)
2727 return true;
2728
2729 if (A.getKind() == TemplateArgument::Pack)
2730 return hasPackExpansionBeforeEnd(A.pack_elements());
2731
2732 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2733 // templates, it should not be treated as a pack expansion.
2734 if (A.isPackExpansion())
2735 FoundPackExpansion = true;
2736 }
2737
2738 return false;
2739}
2740
2747 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
2748 PackFold PackFold, bool *HasDeducedAnyParam) {
2749 bool FoldPackParameter = PackFold == PackFold::ParameterToArgument ||
2751 FoldPackArgument = PackFold == PackFold::ArgumentToParameter ||
2753
2754 // C++0x [temp.deduct.type]p9:
2755 // If the template argument list of P contains a pack expansion that is not
2756 // the last template argument, the entire template argument list is a
2757 // non-deduced context.
2758 if (FoldPackParameter && hasPackExpansionBeforeEnd(Ps))
2760
2761 // C++0x [temp.deduct.type]p9:
2762 // If P has a form that contains <T> or <i>, then each argument Pi of the
2763 // respective template argument list P is compared with the corresponding
2764 // argument Ai of the corresponding template argument list of A.
2765 for (unsigned ArgIdx = 0, ParamIdx = 0; /**/; /**/) {
2767 return !FoldPackParameter && hasTemplateArgumentForDeduction(As, ArgIdx)
2770
2771 if (!Ps[ParamIdx].isPackExpansion()) {
2772 // The simple case: deduce template arguments by matching Pi and Ai.
2773
2774 // Check whether we have enough arguments.
2775 if (!hasTemplateArgumentForDeduction(As, ArgIdx))
2776 return !FoldPackArgument && NumberOfArgumentsMustMatch
2779
2780 if (As[ArgIdx].isPackExpansion()) {
2781 // C++1z [temp.deduct.type]p9:
2782 // During partial ordering, if Ai was originally a pack expansion
2783 // [and] Pi is not a pack expansion, template argument deduction
2784 // fails.
2785 if (!FoldPackArgument)
2787
2788 TemplateArgument Pattern = As[ArgIdx].getPackExpansionPattern();
2789 for (;;) {
2790 // Deduce template parameters from the pattern.
2791 if (auto Result = DeduceTemplateArguments(
2792 S, TemplateParams, Ps[ParamIdx], Pattern, Info,
2793 PartialOrdering, Deduced, HasDeducedAnyParam);
2795 return Result;
2796
2797 ++ParamIdx;
2800 if (Ps[ParamIdx].isPackExpansion())
2801 break;
2802 }
2803 } else {
2804 // Perform deduction for this Pi/Ai pair.
2805 if (auto Result = DeduceTemplateArguments(
2806 S, TemplateParams, Ps[ParamIdx], As[ArgIdx], Info,
2807 PartialOrdering, Deduced, HasDeducedAnyParam);
2809 return Result;
2810
2811 ++ArgIdx;
2812 ++ParamIdx;
2813 continue;
2814 }
2815 }
2816
2817 // The parameter is a pack expansion.
2818
2819 // C++0x [temp.deduct.type]p9:
2820 // If Pi is a pack expansion, then the pattern of Pi is compared with
2821 // each remaining argument in the template argument list of A. Each
2822 // comparison deduces template arguments for subsequent positions in the
2823 // template parameter packs expanded by Pi.
2824 TemplateArgument Pattern = Ps[ParamIdx].getPackExpansionPattern();
2825
2826 // Prepare to deduce the packs within the pattern.
2827 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2828
2829 // Keep track of the deduced template arguments for each parameter pack
2830 // expanded by this pack expansion (the outer index) and for each
2831 // template argument (the inner SmallVectors).
2832 for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
2833 PackScope.hasNextElement();
2834 ++ArgIdx) {
2835 if (!As[ArgIdx].isPackExpansion()) {
2836 if (!FoldPackParameter)
2838 if (FoldPackArgument)
2839 Info.setStrictPackMatch();
2840 }
2841 // Deduce template arguments from the pattern.
2842 if (auto Result = DeduceTemplateArguments(
2843 S, TemplateParams, Pattern, As[ArgIdx], Info, PartialOrdering,
2844 Deduced, HasDeducedAnyParam);
2846 return Result;
2847
2848 PackScope.nextPackElement();
2849 }
2850
2851 // Build argument packs for each of the parameter packs expanded by this
2852 // pack expansion.
2853 return PackScope.finish();
2854 }
2855}
2856
2861 bool NumberOfArgumentsMustMatch) {
2862 return ::DeduceTemplateArguments(
2863 *this, TemplateParams, Ps, As, Info, Deduced, NumberOfArgumentsMustMatch,
2864 /*PartialOrdering=*/false, PackFold::ParameterToArgument,
2865 /*HasDeducedAnyParam=*/nullptr);
2866}
2867
2870 QualType NTTPType, SourceLocation Loc,
2872 switch (Arg.getKind()) {
2874 llvm_unreachable("Can't get a NULL template argument here");
2875
2877 return TemplateArgumentLoc(
2878 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2879
2881 if (NTTPType.isNull())
2882 NTTPType = Arg.getParamTypeForDecl();
2883 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc,
2885 .getAs<Expr>();
2886 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
2887 }
2888
2890 if (NTTPType.isNull())
2891 NTTPType = Arg.getNullPtrType();
2892 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2893 .getAs<Expr>();
2894 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2895 E);
2896 }
2897
2901 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
2902 }
2903
2908 Builder.MakeTrivial(Context, Template.getQualifier(), Loc);
2909 return TemplateArgumentLoc(
2910 Context, Arg, Loc, Builder.getWithLocInContext(Context), Loc,
2911 /*EllipsisLoc=*/Arg.getKind() == TemplateArgument::TemplateExpansion
2912 ? Loc
2913 : SourceLocation());
2914 }
2915
2917 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2918
2921 }
2922
2923 llvm_unreachable("Invalid TemplateArgument Kind!");
2924}
2925
2928 SourceLocation Location) {
2930 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2931}
2932
2933/// Convert the given deduced template argument and add it to the set of
2934/// fully-converted template arguments.
2935static bool
2938 TemplateDeductionInfo &Info, bool IsDeduced,
2940 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2941 unsigned ArgumentPackIndex) {
2942 // Convert the deduced template argument into a template
2943 // argument that we can check, almost as if the user had written
2944 // the template argument explicitly.
2946 Arg, QualType(), Info.getLocation(), Param);
2947
2948 SaveAndRestore _1(CTAI.MatchingTTP, false);
2949 SaveAndRestore _2(CTAI.StrictPackMatch, false);
2950 // Check the template argument, converting it as necessary.
2951 auto Res = S.CheckTemplateArgument(
2952 Param, ArgLoc, Template, Template->getLocation(),
2953 Template->getSourceRange().getEnd(), ArgumentPackIndex, CTAI,
2954 IsDeduced
2958 if (CTAI.StrictPackMatch)
2959 Info.setStrictPackMatch();
2960 return Res;
2961 };
2962
2963 if (Arg.getKind() == TemplateArgument::Pack) {
2964 // This is a template argument pack, so check each of its arguments against
2965 // the template parameter.
2966 SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
2967 CanonicalPackedArgsBuilder;
2968 for (const auto &P : Arg.pack_elements()) {
2969 // When converting the deduced template argument, append it to the
2970 // general output list. We need to do this so that the template argument
2971 // checking logic has all of the prior template arguments available.
2972 DeducedTemplateArgument InnerArg(P);
2974 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2975 "deduced nested pack");
2976 if (P.isNull()) {
2977 // We deduced arguments for some elements of this pack, but not for
2978 // all of them. This happens if we get a conditionally-non-deduced
2979 // context in a pack expansion (such as an overload set in one of the
2980 // arguments).
2981 S.Diag(Param->getLocation(),
2982 diag::err_template_arg_deduced_incomplete_pack)
2983 << Arg << Param;
2984 return true;
2985 }
2986 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
2987 return true;
2988
2989 // Move the converted template argument into our argument pack.
2990 SugaredPackedArgsBuilder.push_back(CTAI.SugaredConverted.pop_back_val());
2991 CanonicalPackedArgsBuilder.push_back(
2992 CTAI.CanonicalConverted.pop_back_val());
2993 }
2994
2995 // If the pack is empty, we still need to substitute into the parameter
2996 // itself, in case that substitution fails.
2997 if (SugaredPackedArgsBuilder.empty()) {
3000 /*Final=*/true);
3001 Sema::ArgPackSubstIndexRAII OnlySubstNonPackExpansion(S, std::nullopt);
3002
3003 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3004 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
3005 NTTP, CTAI.SugaredConverted,
3006 Template->getSourceRange());
3007 if (Inst.isInvalid() ||
3008 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
3009 NTTP->getDeclName()).isNull())
3010 return true;
3011 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3012 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
3013 TTP, CTAI.SugaredConverted,
3014 Template->getSourceRange());
3015 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
3016 return true;
3017 }
3018 // For type parameters, no substitution is ever required.
3019 }
3020
3021 // Create the resulting argument pack.
3022 CTAI.SugaredConverted.push_back(
3023 TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
3025 S.Context, CanonicalPackedArgsBuilder));
3026 return false;
3027 }
3028
3029 return ConvertArg(Arg, 0);
3030}
3031
3032/// \param IsIncomplete When used, we only consider template parameters that
3033/// were deduced, disregarding any default arguments. After the function
3034/// finishes, the object pointed at will contain a value indicating if the
3035/// conversion was actually incomplete.
3037 Sema &S, NamedDecl *Template, TemplateParameterList *TemplateParams,
3038 bool IsDeduced, SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3040 LocalInstantiationScope *CurrentInstantiationScope,
3041 unsigned NumAlreadyConverted, bool *IsIncomplete) {
3042 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3043 NamedDecl *Param = TemplateParams->getParam(I);
3044
3045 // C++0x [temp.arg.explicit]p3:
3046 // A trailing template parameter pack (14.5.3) not otherwise deduced will
3047 // be deduced to an empty sequence of template arguments.
3048 // FIXME: Where did the word "trailing" come from?
3049 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
3050 if (auto Result =
3051 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish();
3053 return Result;
3054 }
3055
3056 if (!Deduced[I].isNull()) {
3057 if (I < NumAlreadyConverted) {
3058 // We may have had explicitly-specified template arguments for a
3059 // template parameter pack (that may or may not have been extended
3060 // via additional deduced arguments).
3061 if (Param->isParameterPack() && CurrentInstantiationScope &&
3062 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
3063 // Forget the partially-substituted pack; its substitution is now
3064 // complete.
3065 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
3066 // We still need to check the argument in case it was extended by
3067 // deduction.
3068 } else {
3069 // We have already fully type-checked and converted this
3070 // argument, because it was explicitly-specified. Just record the
3071 // presence of this argument.
3072 CTAI.SugaredConverted.push_back(Deduced[I]);
3073 CTAI.CanonicalConverted.push_back(
3075 continue;
3076 }
3077 }
3078
3079 // We may have deduced this argument, so it still needs to be
3080 // checked and converted.
3081 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
3082 IsDeduced, CTAI)) {
3083 Info.Param = makeTemplateParameter(Param);
3084 // FIXME: These template arguments are temporary. Free them!
3085 Info.reset(
3088 CTAI.CanonicalConverted));
3090 }
3091
3092 continue;
3093 }
3094
3095 // [C++26][temp.deduct.partial]p12 - When partial ordering, it's ok for
3096 // template parameters to remain not deduced. As a provisional fix for a
3097 // core issue that does not exist yet, which may be related to CWG2160, only
3098 // consider template parameters that were deduced, disregarding any default
3099 // arguments.
3100 if (IsIncomplete) {
3101 *IsIncomplete = true;
3102 CTAI.SugaredConverted.push_back({});
3103 CTAI.CanonicalConverted.push_back({});
3104 continue;
3105 }
3106
3107 // Substitute into the default template argument, if available.
3108 bool HasDefaultArg = false;
3109 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
3110 if (!TD) {
3114 }
3115
3116 TemplateArgumentLoc DefArg;
3117 {
3118 Qualifiers ThisTypeQuals;
3119 CXXRecordDecl *ThisContext = nullptr;
3120 if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
3121 if (Rec->isLambda())
3122 if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
3123 ThisContext = Method->getParent();
3124 ThisTypeQuals = Method->getMethodQualifiers();
3125 }
3126
3127 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
3128 S.getLangOpts().CPlusPlus17);
3129
3131 TD, /*TemplateKWLoc=*/SourceLocation(), TD->getLocation(),
3132 TD->getSourceRange().getEnd(), Param, CTAI.SugaredConverted,
3133 CTAI.CanonicalConverted, HasDefaultArg);
3134 }
3135
3136 // If there was no default argument, deduction is incomplete.
3137 if (DefArg.getArgument().isNull()) {
3138 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3139 Info.reset(
3142
3145 }
3146
3147 SaveAndRestore _1(CTAI.PartialOrdering, false);
3148 SaveAndRestore _2(CTAI.MatchingTTP, false);
3149 SaveAndRestore _3(CTAI.StrictPackMatch, false);
3150 // Check whether we can actually use the default argument.
3152 Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
3153 /*ArgumentPackIndex=*/0, CTAI, Sema::CTAK_Specified)) {
3154 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3155 // FIXME: These template arguments are temporary. Free them!
3156 Info.reset(
3160 }
3161
3162 // If we get here, we successfully used the default template argument.
3163 }
3164
3166}
3167
3169 if (auto *DC = dyn_cast<DeclContext>(D))
3170 return DC;
3171 return D->getDeclContext();
3172}
3173
3174template<typename T> struct IsPartialSpecialization {
3175 static constexpr bool value = false;
3176};
3177template<>
3181template<>
3183 static constexpr bool value = true;
3184};
3185
3188 ArrayRef<TemplateArgument> SugaredDeducedArgs,
3189 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
3190 TemplateDeductionInfo &Info) {
3191 llvm::SmallVector<AssociatedConstraint, 3> AssociatedConstraints;
3192 bool DeducedArgsNeedReplacement = false;
3193 if (auto *TD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Template)) {
3194 TD->getAssociatedConstraints(AssociatedConstraints);
3195 DeducedArgsNeedReplacement = !TD->isClassScopeExplicitSpecialization();
3196 } else if (auto *TD =
3197 dyn_cast<VarTemplatePartialSpecializationDecl>(Template)) {
3198 TD->getAssociatedConstraints(AssociatedConstraints);
3199 DeducedArgsNeedReplacement = !TD->isClassScopeExplicitSpecialization();
3200 } else {
3201 cast<TemplateDecl>(Template)->getAssociatedConstraints(
3202 AssociatedConstraints);
3203 }
3204
3205 std::optional<ArrayRef<TemplateArgument>> Innermost;
3206 // If we don't need to replace the deduced template arguments,
3207 // we can add them immediately as the inner-most argument list.
3208 if (!DeducedArgsNeedReplacement)
3209 Innermost = SugaredDeducedArgs;
3210
3212 Template, Template->getDeclContext(), /*Final=*/false, Innermost,
3213 /*RelativeToPrimary=*/true, /*Pattern=*/
3214 nullptr, /*ForConstraintInstantiation=*/true);
3215
3216 // getTemplateInstantiationArgs picks up the non-deduced version of the
3217 // template args when this is a variable template partial specialization and
3218 // not class-scope explicit specialization, so replace with Deduced Args
3219 // instead of adding to inner-most.
3220 if (!Innermost)
3221 MLTAL.replaceInnermostTemplateArguments(Template, SugaredDeducedArgs);
3222
3223 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
3224 Info.getLocation(),
3227 Info.reset(
3228 TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
3229 TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
3231 }
3233}
3234
3235/// Complete template argument deduction.
3237 Sema &S, NamedDecl *Entity, TemplateParameterList *EntityTPL,
3241 TemplateDeductionInfo &Info, bool CopyDeducedArgs) {
3242 // Unevaluated SFINAE context.
3245
3246 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Entity));
3247
3248 // C++ [temp.deduct.type]p2:
3249 // [...] or if any template argument remains neither deduced nor
3250 // explicitly specified, template argument deduction fails.
3252 if (auto Result = ConvertDeducedTemplateArguments(
3253 S, Entity, EntityTPL, /*IsDeduced=*/PartialOrdering, Deduced, Info,
3254 CTAI,
3255 /*CurrentInstantiationScope=*/nullptr,
3256 /*NumAlreadyConverted=*/0U, /*IsIncomplete=*/nullptr);
3258 return Result;
3259
3260 if (CopyDeducedArgs) {
3261 // Form the template argument list from the deduced template arguments.
3262 TemplateArgumentList *SugaredDeducedArgumentList =
3264 TemplateArgumentList *CanonicalDeducedArgumentList =
3266 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3267 }
3268
3269 TemplateParameterList *TPL = Template->getTemplateParameters();
3270 TemplateArgumentListInfo InstArgs(TPL->getLAngleLoc(), TPL->getRAngleLoc());
3272 /*Final=*/true);
3273 MLTAL.addOuterRetainedLevels(TPL->getDepth());
3274
3275 if (S.SubstTemplateArguments(Ps, MLTAL, InstArgs)) {
3276 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
3277 if (ParamIdx >= TPL->size())
3278 ParamIdx = TPL->size() - 1;
3279
3280 Decl *Param = TPL->getParam(ParamIdx);
3281 Info.Param = makeTemplateParameter(Param);
3282 Info.FirstArg = Ps[ArgIdx].getArgument();
3284 }
3285
3288 if (S.CheckTemplateArgumentList(Template, Template->getLocation(), InstArgs,
3289 /*DefaultArgs=*/{}, false, InstCTAI,
3290 /*UpdateArgsWithConversions=*/true,
3295
3296 // Check that we produced the correct argument list.
3298 AsStack{As};
3299 for (;;) {
3300 auto take = [](SmallVectorImpl<ArrayRef<TemplateArgument>> &Stack)
3302 while (!Stack.empty()) {
3303 auto &Xs = Stack.back();
3304 if (Xs.empty()) {
3305 Stack.pop_back();
3306 continue;
3307 }
3308 auto &X = Xs.front();
3309 if (X.getKind() == TemplateArgument::Pack) {
3310 Stack.emplace_back(X.getPackAsArray());
3311 Xs = Xs.drop_front();
3312 continue;
3313 }
3314 assert(!X.isNull());
3315 return {Xs, X};
3316 }
3317 static constexpr ArrayRef<TemplateArgument> None;
3318 return {const_cast<ArrayRef<TemplateArgument> &>(None),
3320 };
3321 auto [Ps, P] = take(PsStack);
3322 auto [As, A] = take(AsStack);
3323 if (P.isNull() && A.isNull())
3324 break;
3325 TemplateArgument PP = P.isPackExpansion() ? P.getPackExpansionPattern() : P,
3326 PA = A.isPackExpansion() ? A.getPackExpansionPattern() : A;
3327 if (!S.Context.isSameTemplateArgument(PP, PA)) {
3328 if (!P.isPackExpansion() && !A.isPackExpansion()) {
3330 (AsStack.empty() ? As.end() : AsStack.back().begin()) -
3331 As.begin()));
3332 Info.FirstArg = P;
3333 Info.SecondArg = A;
3335 }
3336 if (P.isPackExpansion()) {
3337 Ps = Ps.drop_front();
3338 continue;
3339 }
3340 if (A.isPackExpansion()) {
3341 As = As.drop_front();
3342 continue;
3343 }
3344 }
3345 Ps = Ps.drop_front(P.isPackExpansion() ? 0 : 1);
3346 As = As.drop_front(A.isPackExpansion() && !P.isPackExpansion() ? 0 : 1);
3347 }
3348 assert(PsStack.empty());
3349 assert(AsStack.empty());
3350
3351 if (!PartialOrdering) {
3352 if (auto Result = CheckDeducedArgumentConstraints(
3353 S, Entity, CTAI.SugaredConverted, CTAI.CanonicalConverted, Info);
3355 return Result;
3356 }
3357
3359}
3361 Sema &S, NamedDecl *Entity, TemplateParameterList *EntityTPL,
3365 TemplateDeductionInfo &Info, bool CopyDeducedArgs) {
3366 TemplateParameterList *TPL = Template->getTemplateParameters();
3367 SmallVector<TemplateArgumentLoc, 8> PsLoc(Ps.size());
3368 for (unsigned I = 0, N = Ps.size(); I != N; ++I)
3369 PsLoc[I] = S.getTrivialTemplateArgumentLoc(Ps[I], QualType(),
3370 TPL->getParam(I)->getLocation());
3371 return FinishTemplateArgumentDeduction(S, Entity, EntityTPL, Template,
3372 PartialOrdering, PsLoc, As, Deduced,
3373 Info, CopyDeducedArgs);
3374}
3375
3376/// Complete template argument deduction for DeduceTemplateArgumentsFromType.
3377/// FIXME: this is mostly duplicated with the above two versions. Deduplicate
3378/// the three implementations.
3380 Sema &S, TemplateDecl *TD,
3382 TemplateDeductionInfo &Info) {
3383 // Unevaluated SFINAE context.
3386
3388
3389 // C++ [temp.deduct.type]p2:
3390 // [...] or if any template argument remains neither deduced nor
3391 // explicitly specified, template argument deduction fails.
3393 if (auto Result = ConvertDeducedTemplateArguments(
3394 S, TD, TD->getTemplateParameters(), /*IsDeduced=*/false, Deduced,
3395 Info, CTAI,
3396 /*CurrentInstantiationScope=*/nullptr, /*NumAlreadyConverted=*/0,
3397 /*IsIncomplete=*/nullptr);
3399 return Result;
3400
3401 return ::CheckDeducedArgumentConstraints(S, TD, CTAI.SugaredConverted,
3402 CTAI.CanonicalConverted, Info);
3403}
3404
3405/// Perform template argument deduction to determine whether the given template
3406/// arguments match the given class or variable template partial specialization
3407/// per C++ [temp.class.spec.match].
3408template <typename T>
3409static std::enable_if_t<IsPartialSpecialization<T>::value,
3412 ArrayRef<TemplateArgument> TemplateArgs,
3413 TemplateDeductionInfo &Info) {
3414 if (Partial->isInvalidDecl())
3416
3417 // C++ [temp.class.spec.match]p2:
3418 // A partial specialization matches a given actual template
3419 // argument list if the template arguments of the partial
3420 // specialization can be deduced from the actual template argument
3421 // list (14.8.2).
3422
3423 // Unevaluated SFINAE context.
3426 Sema::SFINAETrap Trap(S);
3427
3428 // This deduction has no relation to any outer instantiation we might be
3429 // performing.
3430 LocalInstantiationScope InstantiationScope(S);
3431
3433 Deduced.resize(Partial->getTemplateParameters()->size());
3435 S, Partial->getTemplateParameters(),
3436 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3437 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/false,
3439 /*HasDeducedAnyParam=*/nullptr);
3441 return Result;
3442
3443 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3444 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs,
3445 Info);
3446 if (Inst.isInvalid())
3448
3451 Result = ::FinishTemplateArgumentDeduction(
3452 S, Partial, Partial->getTemplateParameters(),
3453 Partial->getSpecializedTemplate(),
3454 /*IsPartialOrdering=*/false,
3455 Partial->getTemplateArgsAsWritten()->arguments(), TemplateArgs, Deduced,
3456 Info, /*CopyDeducedArgs=*/true);
3457 });
3458
3460 return Result;
3461
3462 if (Trap.hasErrorOccurred())
3464
3466}
3467
3470 ArrayRef<TemplateArgument> TemplateArgs,
3471 TemplateDeductionInfo &Info) {
3472 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3473}
3476 ArrayRef<TemplateArgument> TemplateArgs,
3477 TemplateDeductionInfo &Info) {
3478 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3479}
3480
3484 if (TD->isInvalidDecl())
3486
3487 QualType PType;
3488 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
3489 // Use the InjectedClassNameType.
3490 PType = Context.getCanonicalTagType(CTD->getTemplatedDecl());
3491 } else if (const auto *AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(TD)) {
3492 PType = AliasTemplate->getTemplatedDecl()->getUnderlyingType();
3493 } else {
3494 assert(false && "Expected a class or alias template");
3495 }
3496
3497 // Unevaluated SFINAE context.
3500 SFINAETrap Trap(*this);
3501
3502 // This deduction has no relation to any outer instantiation we might be
3503 // performing.
3504 LocalInstantiationScope InstantiationScope(*this);
3505
3507 TD->getTemplateParameters()->size());
3510 if (auto DeducedResult = DeduceTemplateArguments(
3511 TD->getTemplateParameters(), PArgs, AArgs, Info, Deduced, false);
3512 DeducedResult != TemplateDeductionResult::Success) {
3513 return DeducedResult;
3514 }
3515
3516 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3517 InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs, Info);
3518 if (Inst.isInvalid())
3520
3523 Result = ::FinishTemplateArgumentDeduction(*this, TD, Deduced, Info);
3524 });
3525
3527 return Result;
3528
3529 if (Trap.hasErrorOccurred())
3531
3533}
3534
3535/// Determine whether the given type T is a simple-template-id type.
3537 if (const TemplateSpecializationType *Spec
3538 = T->getAs<TemplateSpecializationType>())
3539 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
3540
3541 // C++17 [temp.local]p2:
3542 // the injected-class-name [...] is equivalent to the template-name followed
3543 // by the template-arguments of the class template specialization or partial
3544 // specialization enclosed in <>
3545 // ... which means it's equivalent to a simple-template-id.
3546 //
3547 // This only arises during class template argument deduction for a copy
3548 // deduction candidate, where it permits slicing.
3549 if (isa<InjectedClassNameType>(T.getCanonicalType()))
3550 return true;
3551
3552 return false;
3553}
3554
3557 TemplateArgumentListInfo &ExplicitTemplateArgs,
3560 TemplateDeductionInfo &Info) {
3561 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3562 TemplateParameterList *TemplateParams
3563 = FunctionTemplate->getTemplateParameters();
3564
3565 if (ExplicitTemplateArgs.size() == 0) {
3566 // No arguments to substitute; just copy over the parameter types and
3567 // fill in the function type.
3568 for (auto *P : Function->parameters())
3569 ParamTypes.push_back(P->getType());
3570
3571 if (FunctionType)
3572 *FunctionType = Function->getType();
3574 }
3575
3576 // Unevaluated SFINAE context.
3579 SFINAETrap Trap(*this);
3580
3581 // C++ [temp.arg.explicit]p3:
3582 // Template arguments that are present shall be specified in the
3583 // declaration order of their corresponding template-parameters. The
3584 // template argument list shall not specify more template-arguments than
3585 // there are corresponding template-parameters.
3586
3587 // Enter a new template instantiation context where we check the
3588 // explicitly-specified template arguments against this function template,
3589 // and then substitute them into the function parameter types.
3592 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3594 if (Inst.isInvalid())
3596
3599 ExplicitTemplateArgs, /*DefaultArgs=*/{},
3600 /*PartialTemplateArgs=*/true, CTAI,
3601 /*UpdateArgsWithConversions=*/false) ||
3602 Trap.hasErrorOccurred()) {
3603 unsigned Index = CTAI.SugaredConverted.size();
3604 if (Index >= TemplateParams->size())
3606 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3608 }
3609
3610 // Form the template argument list from the explicitly-specified
3611 // template arguments.
3612 TemplateArgumentList *SugaredExplicitArgumentList =
3614 TemplateArgumentList *CanonicalExplicitArgumentList =
3616 Info.setExplicitArgs(SugaredExplicitArgumentList,
3617 CanonicalExplicitArgumentList);
3618
3619 // Template argument deduction and the final substitution should be
3620 // done in the context of the templated declaration. Explicit
3621 // argument substitution, on the other hand, needs to happen in the
3622 // calling context.
3623 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3624
3625 // If we deduced template arguments for a template parameter pack,
3626 // note that the template argument pack is partially substituted and record
3627 // the explicit template arguments. They'll be used as part of deduction
3628 // for this template parameter pack.
3629 unsigned PartiallySubstitutedPackIndex = -1u;
3630 if (!CTAI.SugaredConverted.empty()) {
3631 const TemplateArgument &Arg = CTAI.SugaredConverted.back();
3632 if (Arg.getKind() == TemplateArgument::Pack) {
3633 auto *Param = TemplateParams->getParam(CTAI.SugaredConverted.size() - 1);
3634 // If this is a fully-saturated fixed-size pack, it should be
3635 // fully-substituted, not partially-substituted.
3636 UnsignedOrNone Expansions = getExpandedPackSize(Param);
3637 if (!Expansions || Arg.pack_size() < *Expansions) {
3638 PartiallySubstitutedPackIndex = CTAI.SugaredConverted.size() - 1;
3639 CurrentInstantiationScope->SetPartiallySubstitutedPack(
3640 Param, Arg.pack_begin(), Arg.pack_size());
3641 }
3642 }
3643 }
3644
3645 const FunctionProtoType *Proto
3646 = Function->getType()->getAs<FunctionProtoType>();
3647 assert(Proto && "Function template does not have a prototype?");
3648
3649 // Isolate our substituted parameters from our caller.
3650 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3651
3652 ExtParameterInfoBuilder ExtParamInfos;
3653
3655 SugaredExplicitArgumentList->asArray(),
3656 /*Final=*/true);
3657
3658 // Instantiate the types of each of the function parameters given the
3659 // explicitly-specified template arguments. If the function has a trailing
3660 // return type, substitute it after the arguments to ensure we substitute
3661 // in lexical order.
3662 if (Proto->hasTrailingReturn()) {
3663 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3664 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3665 /*params=*/nullptr, ExtParamInfos))
3667 }
3668
3669 // Instantiate the return type.
3670 QualType ResultType;
3671 {
3672 // C++11 [expr.prim.general]p3:
3673 // If a declaration declares a member function or member function
3674 // template of a class X, the expression this is a prvalue of type
3675 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3676 // and the end of the function-definition, member-declarator, or
3677 // declarator.
3678 Qualifiers ThisTypeQuals;
3679 CXXRecordDecl *ThisContext = nullptr;
3680 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3681 ThisContext = Method->getParent();
3682 ThisTypeQuals = Method->getMethodQualifiers();
3683 }
3684
3685 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3687
3688 ResultType =
3689 SubstType(Proto->getReturnType(), MLTAL,
3690 Function->getTypeSpecStartLoc(), Function->getDeclName());
3691 if (ResultType.isNull() || Trap.hasErrorOccurred())
3693 // CUDA: Kernel function must have 'void' return type.
3694 if (getLangOpts().CUDA)
3695 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3696 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3697 << Function->getType() << Function->getSourceRange();
3699 }
3700 }
3701
3702 // Instantiate the types of each of the function parameters given the
3703 // explicitly-specified template arguments if we didn't do so earlier.
3704 if (!Proto->hasTrailingReturn() &&
3705 SubstParmTypes(Function->getLocation(), Function->parameters(),
3706 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3707 /*params*/ nullptr, ExtParamInfos))
3709
3710 if (FunctionType) {
3711 auto EPI = Proto->getExtProtoInfo();
3712 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3713 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3714 Function->getLocation(),
3715 Function->getDeclName(),
3716 EPI);
3717 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3719 }
3720
3721 // C++ [temp.arg.explicit]p2:
3722 // Trailing template arguments that can be deduced (14.8.2) may be
3723 // omitted from the list of explicit template-arguments. If all of the
3724 // template arguments can be deduced, they may all be omitted; in this
3725 // case, the empty template argument list <> itself may also be omitted.
3726 //
3727 // Take all of the explicitly-specified arguments and put them into
3728 // the set of deduced template arguments. The partially-substituted
3729 // parameter pack, however, will be set to NULL since the deduction
3730 // mechanism handles the partially-substituted argument pack directly.
3731 Deduced.reserve(TemplateParams->size());
3732 for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3733 const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
3734 if (I == PartiallySubstitutedPackIndex)
3735 Deduced.push_back(DeducedTemplateArgument());
3736 else
3737 Deduced.push_back(Arg);
3738 }
3739
3741}
3742
3743/// Check whether the deduced argument type for a call to a function
3744/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3747 Sema::OriginalCallArg OriginalArg,
3748 QualType DeducedA) {
3749 ASTContext &Context = S.Context;
3750
3751 auto Failed = [&]() -> TemplateDeductionResult {
3752 Info.FirstArg = TemplateArgument(DeducedA);
3753 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3754 Info.CallArgIndex = OriginalArg.ArgIdx;
3755 return OriginalArg.DecomposedParam
3758 };
3759
3760 QualType A = OriginalArg.OriginalArgType;
3761 QualType OriginalParamType = OriginalArg.OriginalParamType;
3762
3763 // Check for type equality (top-level cv-qualifiers are ignored).
3764 if (Context.hasSameUnqualifiedType(A, DeducedA))
3766
3767 // Strip off references on the argument types; they aren't needed for
3768 // the following checks.
3769 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3770 DeducedA = DeducedARef->getPointeeType();
3771 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3772 A = ARef->getPointeeType();
3773
3774 // C++ [temp.deduct.call]p4:
3775 // [...] However, there are three cases that allow a difference:
3776 // - If the original P is a reference type, the deduced A (i.e., the
3777 // type referred to by the reference) can be more cv-qualified than
3778 // the transformed A.
3779 if (const ReferenceType *OriginalParamRef
3780 = OriginalParamType->getAs<ReferenceType>()) {
3781 // We don't want to keep the reference around any more.
3782 OriginalParamType = OriginalParamRef->getPointeeType();
3783
3784 // FIXME: Resolve core issue (no number yet): if the original P is a
3785 // reference type and the transformed A is function type "noexcept F",
3786 // the deduced A can be F.
3787 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA))
3789
3790 Qualifiers AQuals = A.getQualifiers();
3791 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3792
3793 // Under Objective-C++ ARC, the deduced type may have implicitly
3794 // been given strong or (when dealing with a const reference)
3795 // unsafe_unretained lifetime. If so, update the original
3796 // qualifiers to include this lifetime.
3797 if (S.getLangOpts().ObjCAutoRefCount &&
3798 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3800 (DeducedAQuals.hasConst() &&
3801 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3802 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3803 }
3804
3805 if (AQuals == DeducedAQuals) {
3806 // Qualifiers match; there's nothing to do.
3807 } else if (!DeducedAQuals.compatiblyIncludes(AQuals, S.getASTContext())) {
3808 return Failed();
3809 } else {
3810 // Qualifiers are compatible, so have the argument type adopt the
3811 // deduced argument type's qualifiers as if we had performed the
3812 // qualification conversion.
3813 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3814 }
3815 }
3816
3817 // - The transformed A can be another pointer or pointer to member
3818 // type that can be converted to the deduced A via a function pointer
3819 // conversion and/or a qualification conversion.
3820 //
3821 // Also allow conversions which merely strip __attribute__((noreturn)) from
3822 // function types (recursively).
3823 bool ObjCLifetimeConversion = false;
3824 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3825 (S.IsQualificationConversion(A, DeducedA, false,
3826 ObjCLifetimeConversion) ||
3827 S.IsFunctionConversion(A, DeducedA)))
3829
3830 // - If P is a class and P has the form simple-template-id, then the
3831 // transformed A can be a derived class of the deduced A. [...]
3832 // [...] Likewise, if P is a pointer to a class of the form
3833 // simple-template-id, the transformed A can be a pointer to a
3834 // derived class pointed to by the deduced A.
3835 if (const PointerType *OriginalParamPtr
3836 = OriginalParamType->getAs<PointerType>()) {
3837 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3838 if (const PointerType *APtr = A->getAs<PointerType>()) {
3839 if (A->getPointeeType()->isRecordType()) {
3840 OriginalParamType = OriginalParamPtr->getPointeeType();
3841 DeducedA = DeducedAPtr->getPointeeType();
3842 A = APtr->getPointeeType();
3843 }
3844 }
3845 }
3846 }
3847
3848 if (Context.hasSameUnqualifiedType(A, DeducedA))
3850
3851 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3852 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3854
3855 return Failed();
3856}
3857
3858/// Find the pack index for a particular parameter index in an instantiation of
3859/// a function template with specific arguments.
3860///
3861/// \return The pack index for whichever pack produced this parameter, or -1
3862/// if this was not produced by a parameter. Intended to be used as the
3863/// ArgumentPackSubstitutionIndex for further substitutions.
3864// FIXME: We should track this in OriginalCallArgs so we don't need to
3865// reconstruct it here.
3866static UnsignedOrNone
3869 unsigned ParamIdx) {
3870 unsigned Idx = 0;
3871 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3872 if (PD->isParameterPack()) {
3873 UnsignedOrNone NumArgs =
3874 S.getNumArgumentsInExpansion(PD->getType(), Args);
3875 unsigned NumExpansions = NumArgs ? *NumArgs : 1;
3876 if (Idx + NumExpansions > ParamIdx)
3877 return ParamIdx - Idx;
3878 Idx += NumExpansions;
3879 } else {
3880 if (Idx == ParamIdx)
3881 return std::nullopt; // Not a pack expansion
3882 ++Idx;
3883 }
3884 }
3885
3886 llvm_unreachable("parameter index would not be produced from template");
3887}
3888
3889// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`,
3890// we'll try to instantiate and update its explicit specifier after constraint
3891// checking.
3894 const MultiLevelTemplateArgumentList &SubstArgs,
3896 ArrayRef<TemplateArgument> DeducedArgs) {
3897 auto GetExplicitSpecifier = [](FunctionDecl *D) {
3898 return isa<CXXConstructorDecl>(D)
3899 ? cast<CXXConstructorDecl>(D)->getExplicitSpecifier()
3900 : cast<CXXConversionDecl>(D)->getExplicitSpecifier();
3901 };
3902 auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) {
3904 ? cast<CXXConstructorDecl>(D)->setExplicitSpecifier(ES)
3905 : cast<CXXConversionDecl>(D)->setExplicitSpecifier(ES);
3906 };
3907
3908 ExplicitSpecifier ES = GetExplicitSpecifier(Specialization);
3909 Expr *ExplicitExpr = ES.getExpr();
3910 if (!ExplicitExpr)
3912 if (!ExplicitExpr->isValueDependent())
3914
3916 S, Info.getLocation(), FunctionTemplate, DeducedArgs,
3918 if (Inst.isInvalid())
3920 Sema::SFINAETrap Trap(S);
3921 const ExplicitSpecifier InstantiatedES =
3922 S.instantiateExplicitSpecifier(SubstArgs, ES);
3923 if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) {
3924 Specialization->setInvalidDecl(true);
3926 }
3927 SetExplicitSpecifier(Specialization, InstantiatedES);
3929}
3930
3934 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3936 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3937 bool PartialOverloading, bool PartialOrdering,
3938 bool ForOverloadSetAddressResolution,
3939 llvm::function_ref<bool(bool)> CheckNonDependent) {
3940 // Unevaluated SFINAE context.
3943 SFINAETrap Trap(*this);
3944
3945 // Enter a new template instantiation context while we instantiate the
3946 // actual function declaration.
3947 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3949 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3951 if (Inst.isInvalid())
3953
3954 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3955
3956 // C++ [temp.deduct.type]p2:
3957 // [...] or if any template argument remains neither deduced nor
3958 // explicitly specified, template argument deduction fails.
3959 bool IsIncomplete = false;
3962 *this, FunctionTemplate, FunctionTemplate->getTemplateParameters(),
3963 /*IsDeduced=*/true, Deduced, Info, CTAI, CurrentInstantiationScope,
3964 NumExplicitlySpecified, PartialOverloading ? &IsIncomplete : nullptr);
3966 return Result;
3967
3968 // Form the template argument list from the deduced template arguments.
3969 TemplateArgumentList *SugaredDeducedArgumentList =
3971 TemplateArgumentList *CanonicalDeducedArgumentList =
3973 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3974
3975 // Substitute the deduced template arguments into the function template
3976 // declaration to produce the function template specialization.
3977 DeclContext *Owner = FunctionTemplate->getDeclContext();
3978 if (FunctionTemplate->getFriendObjectKind())
3979 Owner = FunctionTemplate->getLexicalDeclContext();
3980 FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
3981
3982 if (CheckNonDependent(/*OnlyInitializeNonUserDefinedConversions=*/true))
3984
3985 // C++20 [temp.deduct.general]p5: [CWG2369]
3986 // If the function template has associated constraints, those constraints
3987 // are checked for satisfaction. If the constraints are not satisfied, type
3988 // deduction fails.
3989 //
3990 // FIXME: We haven't implemented CWG2369 for lambdas yet, because we need
3991 // to figure out how to instantiate lambda captures to the scope without
3992 // first instantiating the lambda.
3993 bool IsLambda = isLambdaCallOperator(FD) || isLambdaConversionOperator(FD);
3994 if (!IsLambda && !IsIncomplete) {
3996 Info.getLocation(),
3997 FunctionTemplate->getCanonicalDecl()->getTemplatedDecl(),
4001 Info.reset(
4003 Info.takeCanonical());
4005 }
4006 }
4007 // C++ [temp.deduct.call]p10: [CWG1391]
4008 // If deduction succeeds for all parameters that contain
4009 // template-parameters that participate in template argument deduction,
4010 // and all template arguments are explicitly specified, deduced, or
4011 // obtained from default template arguments, remaining parameters are then
4012 // compared with the corresponding arguments. For each remaining parameter
4013 // P with a type that was non-dependent before substitution of any
4014 // explicitly-specified template arguments, if the corresponding argument
4015 // A cannot be implicitly converted to P, deduction fails.
4016 if (CheckNonDependent(/*OnlyInitializeNonUserDefinedConversions=*/false))
4018
4020 FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
4021 /*Final=*/false);
4022 Specialization = cast_or_null<FunctionDecl>(
4023 SubstDecl(FD, Owner, SubstArgs));
4024 if (!Specialization || Specialization->isInvalidDecl())
4026
4027 assert(isSameDeclaration(Specialization->getPrimaryTemplate(),
4029
4030 // If the template argument list is owned by the function template
4031 // specialization, release it.
4032 if (Specialization->getTemplateSpecializationArgs() ==
4033 CanonicalDeducedArgumentList &&
4034 !Trap.hasErrorOccurred())
4035 Info.takeCanonical();
4036
4037 // There may have been an error that did not prevent us from constructing a
4038 // declaration. Mark the declaration invalid and return with a substitution
4039 // failure.
4040 if (Trap.hasErrorOccurred()) {
4041 Specialization->setInvalidDecl(true);
4043 }
4044
4045 // C++2a [temp.deduct]p5
4046 // [...] When all template arguments have been deduced [...] all uses of
4047 // template parameters [...] are replaced with the corresponding deduced
4048 // or default argument values.
4049 // [...] If the function template has associated constraints
4050 // ([temp.constr.decl]), those constraints are checked for satisfaction
4051 // ([temp.constr.constr]). If the constraints are not satisfied, type
4052 // deduction fails.
4053 if (IsLambda && !IsIncomplete) {
4058
4063 }
4064 }
4065
4066 // We skipped the instantiation of the explicit-specifier during the
4067 // substitution of `FD` before. So, we try to instantiate it back if
4068 // `Specialization` is either a constructor or a conversion function.
4072 Info, FunctionTemplate,
4073 DeducedArgs)) {
4075 }
4076 }
4077
4078 if (OriginalCallArgs) {
4079 // C++ [temp.deduct.call]p4:
4080 // In general, the deduction process attempts to find template argument
4081 // values that will make the deduced A identical to A (after the type A
4082 // is transformed as described above). [...]
4083 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
4084 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
4085 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
4086
4087 auto ParamIdx = OriginalArg.ArgIdx;
4088 unsigned ExplicitOffset =
4089 (Specialization->hasCXXExplicitFunctionObjectParameter() &&
4090 !ForOverloadSetAddressResolution)
4091 ? 1
4092 : 0;
4093 if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset)
4094 // FIXME: This presumably means a pack ended up smaller than we
4095 // expected while deducing. Should this not result in deduction
4096 // failure? Can it even happen?
4097 continue;
4098
4099 QualType DeducedA;
4100 if (!OriginalArg.DecomposedParam) {
4101 // P is one of the function parameters, just look up its substituted
4102 // type.
4103 DeducedA =
4104 Specialization->getParamDecl(ParamIdx + ExplicitOffset)->getType();
4105 } else {
4106 // P is a decomposed element of a parameter corresponding to a
4107 // braced-init-list argument. Substitute back into P to find the
4108 // deduced A.
4109 QualType &CacheEntry =
4110 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
4111 if (CacheEntry.isNull()) {
4112 ArgPackSubstIndexRAII PackIndex(
4113 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
4114 ParamIdx));
4115 CacheEntry =
4116 SubstType(OriginalArg.OriginalParamType, SubstArgs,
4117 Specialization->getTypeSpecStartLoc(),
4118 Specialization->getDeclName());
4119 }
4120 DeducedA = CacheEntry;
4121 }
4122
4123 if (auto TDK =
4124 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
4126 return TDK;
4127 }
4128 }
4129
4130 // If we suppressed any diagnostics while performing template argument
4131 // deduction, and if we haven't already instantiated this declaration,
4132 // keep track of these diagnostics. They'll be emitted if this specialization
4133 // is actually used.
4134 if (Info.diag_begin() != Info.diag_end()) {
4135 auto [Pos, Inserted] =
4136 SuppressedDiagnostics.try_emplace(Specialization->getCanonicalDecl());
4137 if (Inserted)
4138 Pos->second.append(Info.diag_begin(), Info.diag_end());
4139 }
4140
4142}
4143
4144/// Gets the type of a function for template-argument-deducton
4145/// purposes when it's considered as part of an overload set.
4147 FunctionDecl *Fn) {
4148 // We may need to deduce the return type of the function now.
4149 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
4150 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
4151 return {};
4152
4153 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
4154 if (Method->isImplicitObjectMemberFunction()) {
4155 // An instance method that's referenced in a form that doesn't
4156 // look like a member pointer is just invalid.
4158 return {};
4159
4161 Fn->getType(), /*Qualifier=*/std::nullopt, Method->getParent());
4162 }
4163
4164 if (!R.IsAddressOfOperand) return Fn->getType();
4165 return S.Context.getPointerType(Fn->getType());
4166}
4167
4168/// Apply the deduction rules for overload sets.
4169///
4170/// \return the null type if this argument should be treated as an
4171/// undeduced context
4172static QualType
4174 Expr *Arg, QualType ParamType,
4175 bool ParamWasReference,
4176 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4177
4179
4180 OverloadExpr *Ovl = R.Expression;
4181
4182 // C++0x [temp.deduct.call]p4
4183 unsigned TDF = 0;
4184 if (ParamWasReference)
4186 if (R.IsAddressOfOperand)
4187 TDF |= TDF_IgnoreQualifiers;
4188
4189 // C++0x [temp.deduct.call]p6:
4190 // When P is a function type, pointer to function type, or pointer
4191 // to member function type:
4192
4193 if (!ParamType->isFunctionType() &&
4194 !ParamType->isFunctionPointerType() &&
4195 !ParamType->isMemberFunctionPointerType()) {
4196 if (Ovl->hasExplicitTemplateArgs()) {
4197 // But we can still look for an explicit specialization.
4198 if (FunctionDecl *ExplicitSpec =
4200 Ovl, /*Complain=*/false,
4201 /*Found=*/nullptr, FailedTSC,
4202 /*ForTypeDeduction=*/true))
4203 return GetTypeOfFunction(S, R, ExplicitSpec);
4204 }
4205
4206 DeclAccessPair DAP;
4207 if (FunctionDecl *Viable =
4209 return GetTypeOfFunction(S, R, Viable);
4210
4211 return {};
4212 }
4213
4214 // Gather the explicit template arguments, if any.
4215 TemplateArgumentListInfo ExplicitTemplateArgs;
4216 if (Ovl->hasExplicitTemplateArgs())
4217 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4219 for (UnresolvedSetIterator I = Ovl->decls_begin(),
4220 E = Ovl->decls_end(); I != E; ++I) {
4221 NamedDecl *D = (*I)->getUnderlyingDecl();
4222
4223 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
4224 // - If the argument is an overload set containing one or more
4225 // function templates, the parameter is treated as a
4226 // non-deduced context.
4227 if (!Ovl->hasExplicitTemplateArgs())
4228 return {};
4229
4230 // Otherwise, see if we can resolve a function type
4231 FunctionDecl *Specialization = nullptr;
4232 TemplateDeductionInfo Info(Ovl->getNameLoc());
4233 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
4236 continue;
4237
4238 D = Specialization;
4239 }
4240
4242 QualType ArgType = GetTypeOfFunction(S, R, Fn);
4243 if (ArgType.isNull()) continue;
4244
4245 // Function-to-pointer conversion.
4246 if (!ParamWasReference && ParamType->isPointerType() &&
4247 ArgType->isFunctionType())
4248 ArgType = S.Context.getPointerType(ArgType);
4249
4250 // - If the argument is an overload set (not containing function
4251 // templates), trial argument deduction is attempted using each
4252 // of the members of the set. If deduction succeeds for only one
4253 // of the overload set members, that member is used as the
4254 // argument value for the deduction. If deduction succeeds for
4255 // more than one member of the overload set the parameter is
4256 // treated as a non-deduced context.
4257
4258 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
4259 // Type deduction is done independently for each P/A pair, and
4260 // the deduced template argument values are then combined.
4261 // So we do not reject deductions which were made elsewhere.
4263 Deduced(TemplateParams->size());
4264 TemplateDeductionInfo Info(Ovl->getNameLoc());
4266 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4267 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4268 /*HasDeducedAnyParam=*/nullptr);
4270 continue;
4271 // C++ [temp.deduct.call]p6:
4272 // [...] If all successful deductions yield the same deduced A, that
4273 // deduced A is the result of deduction; otherwise, the parameter is
4274 // treated as a non-deduced context. [...]
4275 if (!Match.isNull() && !S.isSameOrCompatibleFunctionType(Match, ArgType))
4276 return {};
4277 Match = ArgType;
4278 }
4279
4280 return Match;
4281}
4282
4283/// Perform the adjustments to the parameter and argument types
4284/// described in C++ [temp.deduct.call].
4285///
4286/// \returns true if the caller should not attempt to perform any template
4287/// argument deduction based on this P/A pair because the argument is an
4288/// overloaded function set that could not be resolved.
4290 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4291 QualType &ParamType, QualType &ArgType,
4292 Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
4293 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4294 // C++0x [temp.deduct.call]p3:
4295 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
4296 // are ignored for type deduction.
4297 if (ParamType.hasQualifiers())
4298 ParamType = ParamType.getUnqualifiedType();
4299
4300 // [...] If P is a reference type, the type referred to by P is
4301 // used for type deduction.
4302 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
4303 if (ParamRefType)
4304 ParamType = ParamRefType->getPointeeType();
4305
4306 // Overload sets usually make this parameter an undeduced context,
4307 // but there are sometimes special circumstances. Typically
4308 // involving a template-id-expr.
4309 if (ArgType == S.Context.OverloadTy) {
4310 assert(Arg && "expected a non-null arg expression");
4311 ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType,
4312 ParamRefType != nullptr, FailedTSC);
4313 if (ArgType.isNull())
4314 return true;
4315 }
4316
4317 if (ParamRefType) {
4318 // If the argument has incomplete array type, try to complete its type.
4319 if (ArgType->isIncompleteArrayType()) {
4320 assert(Arg && "expected a non-null arg expression");
4321 ArgType = S.getCompletedType(Arg);
4322 }
4323
4324 // C++1z [temp.deduct.call]p3:
4325 // If P is a forwarding reference and the argument is an lvalue, the type
4326 // "lvalue reference to A" is used in place of A for type deduction.
4327 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
4328 ArgClassification.isLValue()) {
4329 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
4330 ArgType = S.Context.getAddrSpaceQualType(
4332 ArgType = S.Context.getLValueReferenceType(ArgType);
4333 }
4334 } else {
4335 // C++ [temp.deduct.call]p2:
4336 // If P is not a reference type:
4337 // - If A is an array type, the pointer type produced by the
4338 // array-to-pointer standard conversion (4.2) is used in place of
4339 // A for type deduction; otherwise,
4340 // - If A is a function type, the pointer type produced by the
4341 // function-to-pointer standard conversion (4.3) is used in place
4342 // of A for type deduction; otherwise,
4343 if (ArgType->canDecayToPointerType())
4344 ArgType = S.Context.getDecayedType(ArgType);
4345 else {
4346 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
4347 // type are ignored for type deduction.
4348 ArgType = ArgType.getUnqualifiedType();
4349 }
4350 }
4351
4352 // C++0x [temp.deduct.call]p4:
4353 // In general, the deduction process attempts to find template argument
4354 // values that will make the deduced A identical to A (after the type A
4355 // is transformed as described above). [...]
4357
4358 // - If the original P is a reference type, the deduced A (i.e., the
4359 // type referred to by the reference) can be more cv-qualified than
4360 // the transformed A.
4361 if (ParamRefType)
4363 // - The transformed A can be another pointer or pointer to member
4364 // type that can be converted to the deduced A via a qualification
4365 // conversion (4.4).
4366 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
4367 ArgType->isObjCObjectPointerType())
4368 TDF |= TDF_IgnoreQualifiers;
4369 // - If P is a class and P has the form simple-template-id, then the
4370 // transformed A can be a derived class of the deduced A. Likewise,
4371 // if P is a pointer to a class of the form simple-template-id, the
4372 // transformed A can be a pointer to a derived class pointed to by
4373 // the deduced A.
4374 if (isSimpleTemplateIdType(ParamType) ||
4375 (ParamType->getAs<PointerType>() &&
4377 ParamType->castAs<PointerType>()->getPointeeType())))
4378 TDF |= TDF_DerivedClass;
4379
4380 return false;
4381}
4382
4383static bool
4385 QualType T);
4386
4388 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4389 QualType ParamType, QualType ArgType,
4390 Expr::Classification ArgClassification, Expr *Arg,
4394 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4395 TemplateSpecCandidateSet *FailedTSC = nullptr);
4396
4397/// Attempt template argument deduction from an initializer list
4398/// deemed to be an argument in a function call.
4400 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
4403 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
4404 unsigned TDF) {
4405 // C++ [temp.deduct.call]p1: (CWG 1591)
4406 // If removing references and cv-qualifiers from P gives
4407 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
4408 // a non-empty initializer list, then deduction is performed instead for
4409 // each element of the initializer list, taking P0 as a function template
4410 // parameter type and the initializer element as its argument
4411 //
4412 // We've already removed references and cv-qualifiers here.
4413 if (!ILE->getNumInits())
4415
4416 QualType ElTy;
4417 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
4418 if (ArrTy)
4419 ElTy = ArrTy->getElementType();
4420 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
4421 // Otherwise, an initializer list argument causes the parameter to be
4422 // considered a non-deduced context
4424 }
4425
4426 // Resolving a core issue: a braced-init-list containing any designators is
4427 // a non-deduced context.
4428 for (Expr *E : ILE->inits())
4431
4432 // Deduction only needs to be done for dependent types.
4433 if (ElTy->isDependentType()) {
4434 for (Expr *E : ILE->inits()) {
4436 S, TemplateParams, 0, ElTy, E->getType(),
4437 E->Classify(S.getASTContext()), E, Info, Deduced,
4438 OriginalCallArgs, true, ArgIdx, TDF);
4440 return Result;
4441 }
4442 }
4443
4444 // in the P0[N] case, if N is a non-type template parameter, N is deduced
4445 // from the length of the initializer list.
4446 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
4447 // Determine the array bound is something we can deduce.
4449 Info, DependentArrTy->getSizeExpr())) {
4450 // We can perform template argument deduction for the given non-type
4451 // template parameter.
4452 // C++ [temp.deduct.type]p13:
4453 // The type of N in the type T[N] is std::size_t.
4455 llvm::APInt Size(S.Context.getIntWidth(T),
4457 if (auto Result = DeduceNonTypeTemplateArgument(
4458 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
4459 /*ArrayBound=*/true, Info, /*PartialOrdering=*/false, Deduced,
4460 /*HasDeducedAnyParam=*/nullptr);
4462 return Result;
4463 }
4464 }
4465
4467}
4468
4469/// Perform template argument deduction per [temp.deduct.call] for a
4470/// single parameter / argument pair.
4472 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4473 QualType ParamType, QualType ArgType,
4474 Expr::Classification ArgClassification, Expr *Arg,
4478 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4479 TemplateSpecCandidateSet *FailedTSC) {
4480
4481 QualType OrigParamType = ParamType;
4482
4483 // If P is a reference type [...]
4484 // If P is a cv-qualified type [...]
4486 S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
4487 ArgClassification, Arg, TDF, FailedTSC))
4489
4490 // If [...] the argument is a non-empty initializer list [...]
4491 if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
4492 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
4493 Deduced, OriginalCallArgs, ArgIdx, TDF);
4494
4495 // [...] the deduction process attempts to find template argument values
4496 // that will make the deduced A identical to A
4497 //
4498 // Keep track of the argument type and corresponding parameter index,
4499 // so we can check for compatibility between the deduced A and A.
4500 if (Arg)
4501 OriginalCallArgs.push_back(
4502 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
4504 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4505 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4506 /*HasDeducedAnyParam=*/nullptr);
4507}
4508
4511 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4513 bool PartialOverloading, bool AggregateDeductionCandidate,
4514 bool PartialOrdering, QualType ObjectType,
4515 Expr::Classification ObjectClassification,
4516 bool ForOverloadSetAddressResolution,
4517 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent) {
4518 if (FunctionTemplate->isInvalidDecl())
4520
4521 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4522 unsigned NumParams = Function->getNumParams();
4523 bool HasExplicitObject = false;
4524 int ExplicitObjectOffset = 0;
4525
4526 // [C++26] [over.call.func]p3
4527 // If the primary-expression is the address of an overload set,
4528 // the argument list is the same as the expression-list in the call.
4529 // Otherwise, the argument list is the expression-list in the call augmented
4530 // by the addition of an implied object argument as in a qualified function
4531 // call.
4532 if (!ForOverloadSetAddressResolution &&
4533 Function->hasCXXExplicitFunctionObjectParameter()) {
4534 HasExplicitObject = true;
4535 ExplicitObjectOffset = 1;
4536 }
4537
4538 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
4539
4540 // C++ [temp.deduct.call]p1:
4541 // Template argument deduction is done by comparing each function template
4542 // parameter type (call it P) with the type of the corresponding argument
4543 // of the call (call it A) as described below.
4544 if (Args.size() < Function->getMinRequiredExplicitArguments() &&
4545 !PartialOverloading)
4547 else if (TooManyArguments(NumParams, Args.size() + ExplicitObjectOffset,
4548 PartialOverloading)) {
4549 const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
4550 if (Proto->isTemplateVariadic())
4551 /* Do nothing */;
4552 else if (!Proto->isVariadic())
4554 }
4555
4556 // The types of the parameters from which we will perform template argument
4557 // deduction.
4558 LocalInstantiationScope InstScope(*this);
4559 TemplateParameterList *TemplateParams
4560 = FunctionTemplate->getTemplateParameters();
4562 SmallVector<QualType, 8> ParamTypes;
4563 unsigned NumExplicitlySpecified = 0;
4564 if (ExplicitTemplateArgs) {
4567 Result = SubstituteExplicitTemplateArguments(
4568 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4569 Info);
4570 });
4572 return Result;
4573
4574 NumExplicitlySpecified = Deduced.size();
4575 } else {
4576 // Just fill in the parameter types from the function declaration.
4577 for (unsigned I = 0; I != NumParams; ++I)
4578 ParamTypes.push_back(Function->getParamDecl(I)->getType());
4579 }
4580
4581 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
4582
4583 // Deduce an argument of type ParamType from an expression with index ArgIdx.
4584 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx,
4585 bool ExplicitObjectArgument) {
4586 // C++ [demp.deduct.call]p1: (DR1391)
4587 // Template argument deduction is done by comparing each function template
4588 // parameter that contains template-parameters that participate in
4589 // template argument deduction ...
4590 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4592
4593 if (ExplicitObjectArgument) {
4594 // ... with the type of the corresponding argument
4596 *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
4597 ObjectClassification,
4598 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4599 /*Decomposed*/ false, ArgIdx, /*TDF*/ 0);
4600 }
4601
4602 // ... with the type of the corresponding argument
4604 *this, TemplateParams, FirstInnerIndex, ParamType,
4605 Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()),
4606 Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false,
4607 ArgIdx, /*TDF*/ 0);
4608 };
4609
4610 // Deduce template arguments from the function parameters.
4611 Deduced.resize(TemplateParams->size());
4612 SmallVector<QualType, 8> ParamTypesForArgChecking;
4613 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4614 ParamIdx != NumParamTypes; ++ParamIdx) {
4615 QualType ParamType = ParamTypes[ParamIdx];
4616
4617 const PackExpansionType *ParamExpansion =
4618 dyn_cast<PackExpansionType>(ParamType);
4619 if (!ParamExpansion) {
4620 // Simple case: matching a function parameter to a function argument.
4621 if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0))
4622 break;
4623
4624 ParamTypesForArgChecking.push_back(ParamType);
4625
4626 if (ParamIdx == 0 && HasExplicitObject) {
4627 if (ObjectType.isNull())
4629
4630 if (auto Result = DeduceCallArgument(ParamType, 0,
4631 /*ExplicitObjectArgument=*/true);
4633 return Result;
4634 continue;
4635 }
4636
4637 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4638 /*ExplicitObjectArgument=*/false);
4640 return Result;
4641
4642 continue;
4643 }
4644
4645 bool IsTrailingPack = ParamIdx + 1 == NumParamTypes;
4646
4647 QualType ParamPattern = ParamExpansion->getPattern();
4648 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
4649 ParamPattern,
4650 AggregateDeductionCandidate && IsTrailingPack);
4651
4652 // C++0x [temp.deduct.call]p1:
4653 // For a function parameter pack that occurs at the end of the
4654 // parameter-declaration-list, the type A of each remaining argument of
4655 // the call is compared with the type P of the declarator-id of the
4656 // function parameter pack. Each comparison deduces template arguments
4657 // for subsequent positions in the template parameter packs expanded by
4658 // the function parameter pack. When a function parameter pack appears
4659 // in a non-deduced context [not at the end of the list], the type of
4660 // that parameter pack is never deduced.
4661 //
4662 // FIXME: The above rule allows the size of the parameter pack to change
4663 // after we skip it (in the non-deduced case). That makes no sense, so
4664 // we instead notionally deduce the pack against N arguments, where N is
4665 // the length of the explicitly-specified pack if it's expanded by the
4666 // parameter pack and 0 otherwise, and we treat each deduction as a
4667 // non-deduced context.
4668 if (IsTrailingPack || PackScope.hasFixedArity()) {
4669 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4670 PackScope.nextPackElement(), ++ArgIdx) {
4671 ParamTypesForArgChecking.push_back(ParamPattern);
4672 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4673 /*ExplicitObjectArgument=*/false);
4675 return Result;
4676 }
4677 } else {
4678 // If the parameter type contains an explicitly-specified pack that we
4679 // could not expand, skip the number of parameters notionally created
4680 // by the expansion.
4681 UnsignedOrNone NumExpansions = ParamExpansion->getNumExpansions();
4682 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4683 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4684 ++I, ++ArgIdx) {
4685 ParamTypesForArgChecking.push_back(ParamPattern);
4686 // FIXME: Should we add OriginalCallArgs for these? What if the
4687 // corresponding argument is a list?
4688 PackScope.nextPackElement();
4689 }
4690 } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4691 PackScope.isDeducedFromEarlierParameter()) {
4692 // [temp.deduct.general#3]
4693 // When all template arguments have been deduced
4694 // or obtained from default template arguments, all uses of template
4695 // parameters in the template parameter list of the template are
4696 // replaced with the corresponding deduced or default argument values
4697 //
4698 // If we have a trailing parameter pack, that has been deduced
4699 // previously we substitute the pack here in a similar fashion as
4700 // above with the trailing parameter packs. The main difference here is
4701 // that, in this case we are not processing all of the remaining
4702 // arguments. We are only process as many arguments as we have in
4703 // the already deduced parameter.
4704 UnsignedOrNone ArgPosAfterSubstitution =
4705 PackScope.getSavedPackSizeIfAllEqual();
4706 if (!ArgPosAfterSubstitution)
4707 continue;
4708
4709 unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4710 for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4711 ParamTypesForArgChecking.push_back(ParamPattern);
4712 if (auto Result =
4713 DeduceCallArgument(ParamPattern, ArgIdx,
4714 /*ExplicitObjectArgument=*/false);
4716 return Result;
4717
4718 PackScope.nextPackElement();
4719 }
4720 }
4721 }
4722
4723 // Build argument packs for each of the parameter packs expanded by this
4724 // pack expansion.
4725 if (auto Result = PackScope.finish();
4727 return Result;
4728 }
4729
4730 // Capture the context in which the function call is made. This is the context
4731 // that is needed when the accessibility of template arguments is checked.
4732 DeclContext *CallingCtx = CurContext;
4733
4736 Result = FinishTemplateArgumentDeduction(
4737 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4738 &OriginalCallArgs, PartialOverloading, PartialOrdering,
4739 ForOverloadSetAddressResolution,
4740 [&, CallingCtx](bool OnlyInitializeNonUserDefinedConversions) {
4741 ContextRAII SavedContext(*this, CallingCtx);
4742 return CheckNonDependent(ParamTypesForArgChecking,
4743 OnlyInitializeNonUserDefinedConversions);
4744 });
4745 });
4746 return Result;
4747}
4748
4751 bool AdjustExceptionSpec) {
4752 if (ArgFunctionType.isNull())
4753 return ArgFunctionType;
4754
4755 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4756 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4757 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4758 bool Rebuild = false;
4759
4760 CallingConv CC = FunctionTypeP->getCallConv();
4761 if (EPI.ExtInfo.getCC() != CC) {
4762 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4763 Rebuild = true;
4764 }
4765
4766 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4767 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4768 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4769 Rebuild = true;
4770 }
4771
4772 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4773 ArgFunctionTypeP->hasExceptionSpec())) {
4774 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4775 Rebuild = true;
4776 }
4777
4778 if (!Rebuild)
4779 return ArgFunctionType;
4780
4781 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4782 ArgFunctionTypeP->getParamTypes(), EPI);
4783}
4784
4787 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4789 bool IsAddressOfFunction) {
4790 if (FunctionTemplate->isInvalidDecl())
4792
4793 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4794 TemplateParameterList *TemplateParams
4795 = FunctionTemplate->getTemplateParameters();
4796 QualType FunctionType = Function->getType();
4797
4798 // Substitute any explicit template arguments.
4799 LocalInstantiationScope InstScope(*this);
4801 unsigned NumExplicitlySpecified = 0;
4802 SmallVector<QualType, 4> ParamTypes;
4803 if (ExplicitTemplateArgs) {
4806 Result = SubstituteExplicitTemplateArguments(
4807 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4808 &FunctionType, Info);
4809 });
4811 return Result;
4812
4813 NumExplicitlySpecified = Deduced.size();
4814 }
4815
4816 // When taking the address of a function, we require convertibility of
4817 // the resulting function type. Otherwise, we allow arbitrary mismatches
4818 // of calling convention and noreturn.
4819 if (!IsAddressOfFunction)
4820 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4821 /*AdjustExceptionSpec*/false);
4822
4823 // Unevaluated SFINAE context.
4824 std::optional<EnterExpressionEvaluationContext> Unevaluated(
4826 SFINAETrap Trap(*this);
4827
4828 Deduced.resize(TemplateParams->size());
4829
4830 // If the function has a deduced return type, substitute it for a dependent
4831 // type so that we treat it as a non-deduced context in what follows.
4832 bool HasDeducedReturnType = false;
4833 if (getLangOpts().CPlusPlus14 &&
4834 Function->getReturnType()->getContainedAutoType()) {
4836 HasDeducedReturnType = true;
4837 }
4838
4839 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
4840 unsigned TDF =
4842 // Deduce template arguments from the function type.
4844 *this, TemplateParams, FunctionType, ArgFunctionType, Info, Deduced,
4845 TDF, PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4846 /*HasDeducedAnyParam=*/nullptr);
4848 return Result;
4849 }
4850
4853 Result = FinishTemplateArgumentDeduction(
4854 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4855 /*OriginalCallArgs=*/nullptr, /*PartialOverloading=*/false,
4856 /*PartialOrdering=*/true, IsAddressOfFunction);
4857 });
4859 return Result;
4860
4861 // If the function has a deduced return type, deduce it now, so we can check
4862 // that the deduced function type matches the requested type.
4863 if (HasDeducedReturnType && IsAddressOfFunction &&
4864 Specialization->getReturnType()->isUndeducedType() &&
4867
4868 Unevaluated = std::nullopt;
4869 // [C++26][expr.const]/p17
4870 // An expression or conversion is immediate-escalating if it is not initially
4871 // in an immediate function context and it is [...]
4872 // a potentially-evaluated id-expression that denotes an immediate function.
4873 if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
4874 Specialization->isImmediateEscalating() &&
4875 currentEvaluationContext().isPotentiallyEvaluated() &&
4877 Info.getLocation()))
4879
4880 // Adjust the exception specification of the argument to match the
4881 // substituted and resolved type we just formed. (Calling convention and
4882 // noreturn can't be dependent, so we don't actually need this for them
4883 // right now.)
4884 QualType SpecializationType = Specialization->getType();
4885 if (!IsAddressOfFunction) {
4886 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4887 /*AdjustExceptionSpec*/true);
4888
4889 // Revert placeholder types in the return type back to undeduced types so
4890 // that the comparison below compares the declared return types.
4891 if (HasDeducedReturnType) {
4892 SpecializationType = SubstAutoType(SpecializationType, QualType());
4893 ArgFunctionType = SubstAutoType(ArgFunctionType, QualType());
4894 }
4895 }
4896
4897 // If the requested function type does not match the actual type of the
4898 // specialization with respect to arguments of compatible pointer to function
4899 // types, template argument deduction fails.
4900 if (!ArgFunctionType.isNull()) {
4901 if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
4902 SpecializationType, ArgFunctionType)
4903 : !Context.hasSameFunctionTypeIgnoringExceptionSpec(
4904 SpecializationType, ArgFunctionType)) {
4905 Info.FirstArg = TemplateArgument(SpecializationType);
4906 Info.SecondArg = TemplateArgument(ArgFunctionType);
4908 }
4909 }
4910
4912}
4913
4915 FunctionTemplateDecl *ConversionTemplate, QualType ObjectType,
4916 Expr::Classification ObjectClassification, QualType A,
4918 if (ConversionTemplate->isInvalidDecl())
4920
4921 CXXConversionDecl *ConversionGeneric
4922 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4923
4924 QualType P = ConversionGeneric->getConversionType();
4925 bool IsReferenceP = P->isReferenceType();
4926 bool IsReferenceA = A->isReferenceType();
4927
4928 // C++0x [temp.deduct.conv]p2:
4929 // If P is a reference type, the type referred to by P is used for
4930 // type deduction.
4931 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4932 P = PRef->getPointeeType();
4933
4934 // C++0x [temp.deduct.conv]p4:
4935 // [...] If A is a reference type, the type referred to by A is used
4936 // for type deduction.
4937 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4938 A = ARef->getPointeeType();
4939 // We work around a defect in the standard here: cv-qualifiers are also
4940 // removed from P and A in this case, unless P was a reference type. This
4941 // seems to mostly match what other compilers are doing.
4942 if (!IsReferenceP) {
4943 A = A.getUnqualifiedType();
4944 P = P.getUnqualifiedType();
4945 }
4946
4947 // C++ [temp.deduct.conv]p3:
4948 //
4949 // If A is not a reference type:
4950 } else {
4951 assert(!A->isReferenceType() && "Reference types were handled above");
4952
4953 // - If P is an array type, the pointer type produced by the
4954 // array-to-pointer standard conversion (4.2) is used in place
4955 // of P for type deduction; otherwise,
4956 if (P->isArrayType())
4957 P = Context.getArrayDecayedType(P);
4958 // - If P is a function type, the pointer type produced by the
4959 // function-to-pointer standard conversion (4.3) is used in
4960 // place of P for type deduction; otherwise,
4961 else if (P->isFunctionType())
4962 P = Context.getPointerType(P);
4963 // - If P is a cv-qualified type, the top level cv-qualifiers of
4964 // P's type are ignored for type deduction.
4965 else
4966 P = P.getUnqualifiedType();
4967
4968 // C++0x [temp.deduct.conv]p4:
4969 // If A is a cv-qualified type, the top level cv-qualifiers of A's
4970 // type are ignored for type deduction. If A is a reference type, the type
4971 // referred to by A is used for type deduction.
4972 A = A.getUnqualifiedType();
4973 }
4974
4975 // Unevaluated SFINAE context.
4978 SFINAETrap Trap(*this);
4979
4980 // C++ [temp.deduct.conv]p1:
4981 // Template argument deduction is done by comparing the return
4982 // type of the template conversion function (call it P) with the
4983 // type that is required as the result of the conversion (call it
4984 // A) as described in 14.8.2.4.
4985 TemplateParameterList *TemplateParams
4986 = ConversionTemplate->getTemplateParameters();
4988 Deduced.resize(TemplateParams->size());
4989
4990 // C++0x [temp.deduct.conv]p4:
4991 // In general, the deduction process attempts to find template
4992 // argument values that will make the deduced A identical to
4993 // A. However, there are two cases that allow a difference:
4994 unsigned TDF = 0;
4995 // - If the original A is a reference type, A can be more
4996 // cv-qualified than the deduced A (i.e., the type referred to
4997 // by the reference)
4998 if (IsReferenceA)
5000 // - The deduced A can be another pointer or pointer to member
5001 // type that can be converted to A via a qualification
5002 // conversion.
5003 //
5004 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
5005 // both P and A are pointers or member pointers. In this case, we
5006 // just ignore cv-qualifiers completely).
5007 if ((P->isPointerType() && A->isPointerType()) ||
5009 TDF |= TDF_IgnoreQualifiers;
5010
5012 if (ConversionGeneric->isExplicitObjectMemberFunction()) {
5013 QualType ParamType = ConversionGeneric->getParamDecl(0)->getType();
5016 *this, TemplateParams, getFirstInnerIndex(ConversionTemplate),
5017 ParamType, ObjectType, ObjectClassification,
5018 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
5019 /*Decomposed*/ false, 0, /*TDF*/ 0);
5021 return Result;
5022 }
5023
5025 *this, TemplateParams, P, A, Info, Deduced, TDF,
5026 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
5027 /*HasDeducedAnyParam=*/nullptr);
5029 return Result;
5030
5031 // Create an Instantiation Scope for finalizing the operator.
5032 LocalInstantiationScope InstScope(*this);
5033 // Finish template argument deduction.
5034 FunctionDecl *ConversionSpecialized = nullptr;
5037 Result = FinishTemplateArgumentDeduction(
5038 ConversionTemplate, Deduced, 0, ConversionSpecialized, Info,
5039 &OriginalCallArgs, /*PartialOverloading=*/false,
5040 /*PartialOrdering=*/false, /*ForOverloadSetAddressResolution*/ false);
5041 });
5042 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
5043 return Result;
5044}
5045
5048 TemplateArgumentListInfo *ExplicitTemplateArgs,
5051 bool IsAddressOfFunction) {
5052 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
5053 QualType(), Specialization, Info,
5054 IsAddressOfFunction);
5055}
5056
5057namespace {
5058 struct DependentAuto { bool IsPack; };
5059
5060 /// Substitute the 'auto' specifier or deduced template specialization type
5061 /// specifier within a type for a given replacement type.
5062 class SubstituteDeducedTypeTransform :
5063 public TreeTransform<SubstituteDeducedTypeTransform> {
5064 QualType Replacement;
5065 bool ReplacementIsPack;
5066 bool UseTypeSugar;
5068
5069 public:
5070 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
5071 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5072 ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
5073
5074 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
5075 bool UseTypeSugar = true)
5076 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5077 Replacement(Replacement), ReplacementIsPack(false),
5078 UseTypeSugar(UseTypeSugar) {}
5079
5080 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
5081 assert(isa<TemplateTypeParmType>(Replacement) &&
5082 "unexpected unsugared replacement kind");
5083 QualType Result = Replacement;
5084 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
5085 NewTL.setNameLoc(TL.getNameLoc());
5086 return Result;
5087 }
5088
5089 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
5090 // If we're building the type pattern to deduce against, don't wrap the
5091 // substituted type in an AutoType. Certain template deduction rules
5092 // apply only when a template type parameter appears directly (and not if
5093 // the parameter is found through desugaring). For instance:
5094 // auto &&lref = lvalue;
5095 // must transform into "rvalue reference to T" not "rvalue reference to
5096 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
5097 //
5098 // FIXME: Is this still necessary?
5099 if (!UseTypeSugar)
5100 return TransformDesugared(TLB, TL);
5101
5102 QualType Result = SemaRef.Context.getAutoType(
5103 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
5104 ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(),
5105 TL.getTypePtr()->getTypeConstraintArguments());
5106 auto NewTL = TLB.push<AutoTypeLoc>(Result);
5107 NewTL.copy(TL);
5108 return Result;
5109 }
5110
5111 QualType TransformDeducedTemplateSpecializationType(
5112 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
5113 if (!UseTypeSugar)
5114 return TransformDesugared(TLB, TL);
5115
5116 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
5117 TL.getTypePtr()->getKeyword(), TL.getTypePtr()->getTemplateName(),
5118 Replacement, Replacement.isNull());
5119 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5120 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5121 NewTL.setNameLoc(TL.getNameLoc());
5122 NewTL.setQualifierLoc(TL.getQualifierLoc());
5123 return Result;
5124 }
5125
5126 ExprResult TransformLambdaExpr(LambdaExpr *E) {
5127 // Lambdas never need to be transformed.
5128 return E;
5129 }
5130 bool TransformExceptionSpec(SourceLocation Loc,
5131 FunctionProtoType::ExceptionSpecInfo &ESI,
5132 SmallVectorImpl<QualType> &Exceptions,
5133 bool &Changed) {
5134 if (ESI.Type == EST_Uninstantiated) {
5135 ESI.instantiate();
5136 Changed = true;
5137 }
5138 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
5139 }
5140
5141 QualType Apply(TypeLoc TL) {
5142 // Create some scratch storage for the transformed type locations.
5143 // FIXME: We're just going to throw this information away. Don't build it.
5144 TypeLocBuilder TLB;
5145 TLB.reserve(TL.getFullDataSize());
5146 return TransformType(TLB, TL);
5147 }
5148 };
5149
5150} // namespace
5151
5152static bool CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type,
5154 QualType Deduced) {
5155 ConstraintSatisfaction Satisfaction;
5156 ConceptDecl *Concept = cast<ConceptDecl>(Type.getTypeConstraintConcept());
5157 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
5158 TypeLoc.getRAngleLoc());
5159 TemplateArgs.addArgument(
5162 Deduced, TypeLoc.getNameLoc())));
5163 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
5164 TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
5165
5167 if (S.CheckTemplateArgumentList(Concept, TypeLoc.getNameLoc(), TemplateArgs,
5168 /*DefaultArgs=*/{},
5169 /*PartialTemplateArgs=*/false, CTAI))
5170 return true;
5172 /*Final=*/true);
5173 // Build up an EvaluationContext with an ImplicitConceptSpecializationDecl so
5174 // that the template arguments of the constraint can be preserved. For
5175 // example:
5176 //
5177 // template <class T>
5178 // concept C = []<D U = void>() { return true; }();
5179 //
5180 // We need the argument for T while evaluating type constraint D in
5181 // building the CallExpr to the lambda.
5185 S.getASTContext(), Concept->getDeclContext(), Concept->getLocation(),
5186 CTAI.SugaredConverted));
5188 Concept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
5189 TypeLoc.getLocalSourceRange(), Satisfaction))
5190 return true;
5191 if (!Satisfaction.IsSatisfied) {
5192 std::string Buf;
5193 llvm::raw_string_ostream OS(Buf);
5194 OS << "'" << Concept->getName();
5195 if (TypeLoc.hasExplicitTemplateArgs()) {
5196 printTemplateArgumentList(
5197 OS, Type.getTypeConstraintArguments(), S.getPrintingPolicy(),
5198 Type.getTypeConstraintConcept()->getTemplateParameters());
5199 }
5200 OS << "'";
5201 S.Diag(TypeLoc.getConceptNameLoc(),
5202 diag::err_placeholder_constraints_not_satisfied)
5203 << Deduced << Buf << TypeLoc.getLocalSourceRange();
5204 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
5205 return true;
5206 }
5207 return false;
5208}
5209
5212 TemplateDeductionInfo &Info, bool DependentDeduction,
5213 bool IgnoreConstraints,
5214 TemplateSpecCandidateSet *FailedTSC) {
5215 assert(DependentDeduction || Info.getDeducedDepth() == 0);
5216 if (Init->containsErrors())
5218
5219 const AutoType *AT = Type.getType()->getContainedAutoType();
5220 assert(AT);
5221
5222 if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
5223 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
5224 if (NonPlaceholder.isInvalid())
5226 Init = NonPlaceholder.get();
5227 }
5228
5229 DependentAuto DependentResult = {
5230 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
5231
5232 if (!DependentDeduction &&
5233 (Type.getType()->isDependentType() || Init->isTypeDependent() ||
5234 Init->containsUnexpandedParameterPack())) {
5235 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5236 assert(!Result.isNull() && "substituting DependentTy can't fail");
5238 }
5239
5240 // Make sure that we treat 'char[]' equaly as 'char*' in C23 mode.
5241 auto *String = dyn_cast<StringLiteral>(Init);
5242 if (getLangOpts().C23 && String && Type.getType()->isArrayType()) {
5243 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5244 TypeLoc TL = TypeLoc(Init->getType(), Type.getOpaqueData());
5245 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(TL);
5246 assert(!Result.isNull() && "substituting DependentTy can't fail");
5248 }
5249
5250 // Emit a warning if 'auto*' is used in pedantic and in C23 mode.
5251 if (getLangOpts().C23 && Type.getType()->isPointerType()) {
5252 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5253 }
5254
5255 auto *InitList = dyn_cast<InitListExpr>(Init);
5256 if (!getLangOpts().CPlusPlus && InitList) {
5257 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c)
5258 << (int)AT->getKeyword() << getLangOpts().C23;
5260 }
5261
5262 // Deduce type of TemplParam in Func(Init)
5264 Deduced.resize(1);
5265
5266 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
5267
5268 QualType DeducedType;
5269 // If this is a 'decltype(auto)' specifier, do the decltype dance.
5270 if (AT->isDecltypeAuto()) {
5271 if (InitList) {
5272 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
5274 }
5275
5276 DeducedType = getDecltypeForExpr(Init);
5277 assert(!DeducedType.isNull());
5278 } else {
5279 LocalInstantiationScope InstScope(*this);
5280
5281 // Build template<class TemplParam> void Func(FuncParam);
5282 SourceLocation Loc = Init->getExprLoc();
5284 Context, nullptr, SourceLocation(), Loc, Info.getDeducedDepth(), 0,
5285 nullptr, false, false, false);
5286 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
5287 NamedDecl *TemplParamPtr = TemplParam;
5289 Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
5290
5291 if (InitList) {
5292 // Notionally, we substitute std::initializer_list<T> for 'auto' and
5293 // deduce against that. Such deduction only succeeds if removing
5294 // cv-qualifiers and references results in std::initializer_list<T>.
5295 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
5297
5298 SourceRange DeducedFromInitRange;
5299 for (Expr *Init : InitList->inits()) {
5300 // Resolving a core issue: a braced-init-list containing any designators
5301 // is a non-deduced context.
5305 *this, TemplateParamsSt.get(), 0, TemplArg, Init->getType(),
5306 Init->Classify(getASTContext()), Init, Info, Deduced,
5307 OriginalCallArgs,
5308 /*Decomposed=*/true,
5309 /*ArgIdx=*/0, /*TDF=*/0);
5312 Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction)
5313 << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
5314 << Init->getSourceRange();
5316 }
5317 return TDK;
5318 }
5319
5320 if (DeducedFromInitRange.isInvalid() &&
5321 Deduced[0].getKind() != TemplateArgument::Null)
5322 DeducedFromInitRange = Init->getSourceRange();
5323 }
5324 } else {
5325 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
5326 Diag(Loc, diag::err_auto_bitfield);
5328 }
5329 QualType FuncParam =
5330 SubstituteDeducedTypeTransform(*this, TemplArg).Apply(Type);
5331 assert(!FuncParam.isNull() &&
5332 "substituting template parameter for 'auto' failed");
5334 *this, TemplateParamsSt.get(), 0, FuncParam, Init->getType(),
5335 Init->Classify(getASTContext()), Init, Info, Deduced,
5336 OriginalCallArgs,
5337 /*Decomposed=*/false, /*ArgIdx=*/0, /*TDF=*/0, FailedTSC);
5339 return TDK;
5340 }
5341
5342 // Could be null if somehow 'auto' appears in a non-deduced context.
5343 if (Deduced[0].getKind() != TemplateArgument::Type)
5345 DeducedType = Deduced[0].getAsType();
5346
5347 if (InitList) {
5348 DeducedType = BuildStdInitializerList(DeducedType, Loc);
5349 if (DeducedType.isNull())
5351 }
5352 }
5353
5354 if (!Result.isNull()) {
5355 if (!Context.hasSameType(DeducedType, Result)) {
5356 Info.FirstArg = Result;
5357 Info.SecondArg = DeducedType;
5359 }
5360 DeducedType = Context.getCommonSugaredType(Result, DeducedType);
5361 }
5362
5363 if (AT->isConstrained() && !IgnoreConstraints &&
5365 *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType))
5367
5368 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
5369 if (Result.isNull())
5371
5372 // Check that the deduced argument type is compatible with the original
5373 // argument type per C++ [temp.deduct.call]p4.
5374 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
5375 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
5376 assert((bool)InitList == OriginalArg.DecomposedParam &&
5377 "decomposed non-init-list in auto deduction?");
5378 if (auto TDK =
5379 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
5381 Result = QualType();
5382 return TDK;
5383 }
5384 }
5385
5387}
5388
5390 QualType TypeToReplaceAuto) {
5391 assert(TypeToReplaceAuto != Context.DependentTy);
5392 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5393 .TransformType(TypeWithAuto);
5394}
5395
5397 QualType TypeToReplaceAuto) {
5398 assert(TypeToReplaceAuto != Context.DependentTy);
5399 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5400 .TransformType(TypeWithAuto);
5401}
5402
5404 return SubstituteDeducedTypeTransform(
5405 *this,
5406 DependentAuto{/*IsPack=*/isa<PackExpansionType>(TypeWithAuto)})
5407 .TransformType(TypeWithAuto);
5408}
5409
5412 return SubstituteDeducedTypeTransform(
5413 *this, DependentAuto{/*IsPack=*/isa<PackExpansionType>(
5414 TypeWithAuto->getType())})
5415 .TransformType(TypeWithAuto);
5416}
5417
5419 QualType TypeToReplaceAuto) {
5420 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5421 /*UseTypeSugar*/ false)
5422 .TransformType(TypeWithAuto);
5423}
5424
5426 QualType TypeToReplaceAuto) {
5427 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5428 /*UseTypeSugar*/ false)
5429 .TransformType(TypeWithAuto);
5430}
5431
5433 const Expr *Init) {
5435 Diag(VDecl->getLocation(),
5436 VDecl->isInitCapture()
5437 ? diag::err_init_capture_deduction_failure_from_init_list
5438 : diag::err_auto_var_deduction_failure_from_init_list)
5439 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
5440 else
5441 Diag(VDecl->getLocation(),
5442 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
5443 : diag::err_auto_var_deduction_failure)
5444 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5445 << Init->getSourceRange();
5446}
5447
5449 bool Diagnose) {
5450 assert(FD->getReturnType()->isUndeducedType());
5451
5452 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
5453 // within the return type from the call operator's type.
5455 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5456 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5457
5458 // For a generic lambda, instantiate the call operator if needed.
5459 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5461 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5462 if (!CallOp || CallOp->isInvalidDecl())
5463 return true;
5464
5465 // We might need to deduce the return type by instantiating the definition
5466 // of the operator() function.
5467 if (CallOp->getReturnType()->isUndeducedType()) {
5469 InstantiateFunctionDefinition(Loc, CallOp);
5470 });
5471 }
5472 }
5473
5474 if (CallOp->isInvalidDecl())
5475 return true;
5476 assert(!CallOp->getReturnType()->isUndeducedType() &&
5477 "failed to deduce lambda return type");
5478
5479 // Build the new return type from scratch.
5480 CallingConv RetTyCC = FD->getReturnType()
5481 ->getPointeeType()
5482 ->castAs<FunctionType>()
5483 ->getCallConv();
5485 CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
5486 if (FD->getReturnType()->getAs<PointerType>())
5487 RetType = Context.getPointerType(RetType);
5488 else {
5489 assert(FD->getReturnType()->getAs<BlockPointerType>());
5490 RetType = Context.getBlockPointerType(RetType);
5491 }
5492 Context.adjustDeducedFunctionResultType(FD, RetType);
5493 return false;
5494 }
5495
5499 });
5500 }
5501
5502 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
5503 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
5504 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
5505 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
5506 }
5507
5508 return StillUndeduced;
5509}
5510
5512 SourceLocation Loc) {
5513 assert(FD->isImmediateEscalating());
5514
5516 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5517 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5518
5519 // For a generic lambda, instantiate the call operator if needed.
5520 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5522 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5523 if (!CallOp || CallOp->isInvalidDecl())
5524 return true;
5526 Loc, [&] { InstantiateFunctionDefinition(Loc, CallOp); });
5527 }
5528 return CallOp->isInvalidDecl();
5529 }
5530
5533 Loc, [&] { InstantiateFunctionDefinition(Loc, FD); });
5534 }
5535 return false;
5536}
5537
5539 const CXXMethodDecl *Method,
5540 QualType RawType,
5541 bool IsOtherRvr) {
5542 // C++20 [temp.func.order]p3.1, p3.2:
5543 // - The type X(M) is "rvalue reference to cv A" if the optional
5544 // ref-qualifier of M is && or if M has no ref-qualifier and the
5545 // positionally-corresponding parameter of the other transformed template
5546 // has rvalue reference type; if this determination depends recursively
5547 // upon whether X(M) is an rvalue reference type, it is not considered to
5548 // have rvalue reference type.
5549 //
5550 // - Otherwise, X(M) is "lvalue reference to cv A".
5551 assert(Method && !Method->isExplicitObjectMemberFunction() &&
5552 "expected a member function with no explicit object parameter");
5553
5554 RawType = Context.getQualifiedType(RawType, Method->getMethodQualifiers());
5555 if (Method->getRefQualifier() == RQ_RValue ||
5556 (IsOtherRvr && Method->getRefQualifier() == RQ_None))
5557 return Context.getRValueReferenceType(RawType);
5558 return Context.getLValueReferenceType(RawType);
5559}
5560
5563 QualType A, ArrayRef<TemplateArgument> DeducedArgs, bool CheckConsistency) {
5564 MultiLevelTemplateArgumentList MLTAL(FTD, DeducedArgs,
5565 /*Final=*/true);
5567 S,
5568 ArgIdx ? ::getPackIndexForParam(S, FTD, MLTAL, *ArgIdx) : std::nullopt);
5569 bool IsIncompleteSubstitution = false;
5570 // FIXME: A substitution can be incomplete on a non-structural part of the
5571 // type. Use the canonical type for now, until the TemplateInstantiator can
5572 // deal with that.
5573
5574 // Workaround: Implicit deduction guides use InjectedClassNameTypes, whereas
5575 // the explicit guides don't. The substitution doesn't transform these types,
5576 // so let it transform their specializations instead.
5577 bool IsDeductionGuide = isa<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
5578 if (IsDeductionGuide) {
5579 if (auto *Injected = P->getAsCanonical<InjectedClassNameType>())
5580 P = Injected->getOriginalDecl()->getCanonicalTemplateSpecializationType(
5581 S.Context);
5582 }
5583 QualType InstP = S.SubstType(P.getCanonicalType(), MLTAL, FTD->getLocation(),
5584 FTD->getDeclName(), &IsIncompleteSubstitution);
5585 if (InstP.isNull() && !IsIncompleteSubstitution)
5587 if (!CheckConsistency)
5589 if (IsIncompleteSubstitution)
5591
5592 // [temp.deduct.call]/4 - Check we produced a consistent deduction.
5593 // This handles just the cases that can appear when partial ordering.
5594 if (auto *PA = dyn_cast<PackExpansionType>(A);
5595 PA && !isa<PackExpansionType>(InstP))
5596 A = PA->getPattern();
5599 if (IsDeductionGuide) {
5600 if (auto *Injected = T1->getAsCanonical<InjectedClassNameType>())
5601 T1 = Injected->getOriginalDecl()->getCanonicalTemplateSpecializationType(
5602 S.Context);
5603 if (auto *Injected = T2->getAsCanonical<InjectedClassNameType>())
5604 T2 = Injected->getOriginalDecl()->getCanonicalTemplateSpecializationType(
5605 S.Context);
5606 }
5607 if (!S.Context.hasSameType(T1, T2))
5610}
5611
5612template <class T>
5614 Sema &S, FunctionTemplateDecl *FTD,
5619 Sema::SFINAETrap Trap(S);
5620
5621 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(FTD));
5622
5623 // C++26 [temp.deduct.type]p2:
5624 // [...] or if any template argument remains neither deduced nor
5625 // explicitly specified, template argument deduction fails.
5626 bool IsIncomplete = false;
5627 Sema::CheckTemplateArgumentInfo CTAI(/*PartialOrdering=*/true);
5628 if (auto Result = ConvertDeducedTemplateArguments(
5629 S, FTD, FTD->getTemplateParameters(), /*IsDeduced=*/true, Deduced,
5630 Info, CTAI,
5631 /*CurrentInstantiationScope=*/nullptr,
5632 /*NumAlreadyConverted=*/0, &IsIncomplete);
5634 return Result;
5635
5636 // Form the template argument list from the deduced template arguments.
5637 TemplateArgumentList *SugaredDeducedArgumentList =
5639 TemplateArgumentList *CanonicalDeducedArgumentList =
5641
5642 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
5643
5644 // Substitute the deduced template arguments into the argument
5645 // and verify that the instantiated argument is both valid
5646 // and equivalent to the parameter.
5647 LocalInstantiationScope InstScope(S);
5648
5649 if (auto TDR = CheckDeductionConsistency(S, FTD, CTAI.SugaredConverted);
5651 return TDR;
5652
5655}
5656
5657/// Determine whether the function template \p FT1 is at least as
5658/// specialized as \p FT2.
5662 ArrayRef<QualType> Args1, ArrayRef<QualType> Args2, bool Args1Offset) {
5663 FunctionDecl *FD1 = FT1->getTemplatedDecl();
5664 FunctionDecl *FD2 = FT2->getTemplatedDecl();
5665 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
5666 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
5667 assert(Proto1 && Proto2 && "Function templates must have prototypes");
5668
5669 // C++26 [temp.deduct.partial]p3:
5670 // The types used to determine the ordering depend on the context in which
5671 // the partial ordering is done:
5672 // - In the context of a function call, the types used are those function
5673 // parameter types for which the function call has arguments.
5674 // - In the context of a call to a conversion operator, the return types
5675 // of the conversion function templates are used.
5676 // - In other contexts (14.6.6.2) the function template's function type
5677 // is used.
5678
5679 if (TPOC == TPOC_Other) {
5680 // We wouldn't be partial ordering these candidates if these didn't match.
5681 assert(Proto1->getMethodQuals() == Proto2->getMethodQuals() &&
5682 Proto1->getRefQualifier() == Proto2->getRefQualifier() &&
5683 Proto1->isVariadic() == Proto2->isVariadic() &&
5684 "shouldn't partial order functions with different qualifiers in a "
5685 "context where the function type is used");
5686
5687 assert(Args1.empty() && Args2.empty() &&
5688 "Only call context should have arguments");
5689 Args1 = Proto1->getParamTypes();
5690 Args2 = Proto2->getParamTypes();
5691 }
5692
5693 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
5694 SmallVector<DeducedTemplateArgument, 4> Deduced(TemplateParams->size());
5695 TemplateDeductionInfo Info(Loc);
5696
5697 bool HasDeducedAnyParamFromReturnType = false;
5698 if (TPOC != TPOC_Call) {
5700 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
5701 Info, Deduced, TDF_None, PartialOrderingKind::Call,
5702 /*DeducedFromArrayBound=*/false,
5703 &HasDeducedAnyParamFromReturnType) !=
5705 return false;
5706 }
5707
5708 llvm::SmallBitVector HasDeducedParam;
5709 if (TPOC != TPOC_Conversion) {
5710 HasDeducedParam.resize(Args2.size());
5711 if (DeduceTemplateArguments(S, TemplateParams, Args2, Args1, Info, Deduced,
5713 /*HasDeducedAnyParam=*/nullptr,
5714 &HasDeducedParam) !=
5716 return false;
5717 }
5718
5719 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
5721 S, Info.getLocation(), FT2, DeducedArgs,
5723 if (Inst.isInvalid())
5724 return false;
5725
5726 bool AtLeastAsSpecialized;
5728 AtLeastAsSpecialized =
5729 ::FinishTemplateArgumentDeduction(
5730 S, FT2, Deduced, Info,
5731 [&](Sema &S, FunctionTemplateDecl *FTD,
5732 ArrayRef<TemplateArgument> DeducedArgs) {
5733 // As a provisional fix for a core issue that does not
5734 // exist yet, which may be related to CWG2160, only check the
5735 // consistency of parameters and return types which participated
5736 // in deduction. We will still try to substitute them though.
5737 if (TPOC != TPOC_Call) {
5738 if (auto TDR = ::CheckDeductionConsistency(
5739 S, FTD, /*ArgIdx=*/std::nullopt,
5740 Proto2->getReturnType(), Proto1->getReturnType(),
5741 DeducedArgs,
5742 /*CheckConsistency=*/HasDeducedAnyParamFromReturnType);
5743 TDR != TemplateDeductionResult::Success)
5744 return TDR;
5745 }
5746
5747 if (TPOC == TPOC_Conversion)
5748 return TemplateDeductionResult::Success;
5749
5750 return ::DeduceForEachType(
5751 S, TemplateParams, Args2, Args1, Info, Deduced,
5752 PartialOrderingKind::Call, /*FinishingDeduction=*/true,
5753 [&](Sema &S, TemplateParameterList *, int ParamIdx,
5754 UnsignedOrNone ArgIdx, QualType P, QualType A,
5755 TemplateDeductionInfo &Info,
5756 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5757 PartialOrderingKind) {
5758 if (ArgIdx && *ArgIdx >= static_cast<unsigned>(Args1Offset))
5759 ArgIdx = *ArgIdx - Args1Offset;
5760 else
5761 ArgIdx = std::nullopt;
5762 return ::CheckDeductionConsistency(
5763 S, FTD, ArgIdx, P, A, DeducedArgs,
5764 /*CheckConsistency=*/HasDeducedParam[ParamIdx]);
5765 });
5767 });
5768 if (!AtLeastAsSpecialized)
5769 return false;
5770
5771 // C++0x [temp.deduct.partial]p11:
5772 // In most cases, all template parameters must have values in order for
5773 // deduction to succeed, but for partial ordering purposes a template
5774 // parameter may remain without a value provided it is not used in the
5775 // types being used for partial ordering. [ Note: a template parameter used
5776 // in a non-deduced context is considered used. -end note]
5777 unsigned ArgIdx = 0, NumArgs = Deduced.size();
5778 for (; ArgIdx != NumArgs; ++ArgIdx)
5779 if (Deduced[ArgIdx].isNull())
5780 break;
5781
5782 if (ArgIdx == NumArgs) {
5783 // All template arguments were deduced. FT1 is at least as specialized
5784 // as FT2.
5785 return true;
5786 }
5787
5788 // Figure out which template parameters were used.
5789 llvm::SmallBitVector UsedParameters(TemplateParams->size());
5790 switch (TPOC) {
5791 case TPOC_Call:
5792 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
5793 ::MarkUsedTemplateParameters(S.Context, Args2[I], /*OnlyDeduced=*/false,
5794 TemplateParams->getDepth(), UsedParameters);
5795 break;
5796
5797 case TPOC_Conversion:
5798 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(),
5799 /*OnlyDeduced=*/false,
5800 TemplateParams->getDepth(), UsedParameters);
5801 break;
5802
5803 case TPOC_Other:
5804 // We do not deduce template arguments from the exception specification
5805 // when determining the primary template of a function template
5806 // specialization or when taking the address of a function template.
5807 // Therefore, we do not mark template parameters in the exception
5808 // specification as used during partial ordering to prevent the following
5809 // from being ambiguous:
5810 //
5811 // template<typename T, typename U>
5812 // void f(U) noexcept(noexcept(T())); // #1
5813 //
5814 // template<typename T>
5815 // void f(T*) noexcept; // #2
5816 //
5817 // template<>
5818 // void f<int>(int*) noexcept; // explicit specialization of #2
5819 //
5820 // Although there is no corresponding wording in the standard, this seems
5821 // to be the intended behavior given the definition of
5822 // 'deduction substitution loci' in [temp.deduct].
5824 S.Context,
5825 S.Context.getFunctionTypeWithExceptionSpec(FD2->getType(), EST_None),
5826 /*OnlyDeduced=*/false, TemplateParams->getDepth(), UsedParameters);
5827 break;
5828 }
5829
5830 for (; ArgIdx != NumArgs; ++ArgIdx)
5831 // If this argument had no value deduced but was used in one of the types
5832 // used for partial ordering, then deduction fails.
5833 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
5834 return false;
5835
5836 return true;
5837}
5838
5840
5841// This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
5842// there is no wording or even resolution for this issue.
5845 const TemplateSpecializationType *TST1,
5846 const TemplateSpecializationType *TST2) {
5847 ArrayRef<TemplateArgument> As1 = TST1->template_arguments(),
5848 As2 = TST2->template_arguments();
5849 const TemplateArgument &TA1 = As1.back(), &TA2 = As2.back();
5850 bool IsPack = TA1.getKind() == TemplateArgument::Pack;
5851 assert(IsPack == (TA2.getKind() == TemplateArgument::Pack));
5852 if (!IsPack)
5854 assert(As1.size() == As2.size());
5855
5856 unsigned PackSize1 = TA1.pack_size(), PackSize2 = TA2.pack_size();
5857 bool IsPackExpansion1 =
5858 PackSize1 && TA1.pack_elements().back().isPackExpansion();
5859 bool IsPackExpansion2 =
5860 PackSize2 && TA2.pack_elements().back().isPackExpansion();
5861 if (PackSize1 == PackSize2 && IsPackExpansion1 == IsPackExpansion2)
5863 if (PackSize1 > PackSize2 && IsPackExpansion1)
5865 if (PackSize1 < PackSize2 && IsPackExpansion2)
5868}
5869
5872 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
5873 QualType RawObj1Ty, QualType RawObj2Ty, bool Reversed,
5874 bool PartialOverloading) {
5877 const FunctionDecl *FD1 = FT1->getTemplatedDecl();
5878 const FunctionDecl *FD2 = FT2->getTemplatedDecl();
5879 bool ShouldConvert1 = false;
5880 bool ShouldConvert2 = false;
5881 bool Args1Offset = false;
5882 bool Args2Offset = false;
5883 QualType Obj1Ty;
5884 QualType Obj2Ty;
5885 if (TPOC == TPOC_Call) {
5886 const FunctionProtoType *Proto1 =
5887 FD1->getType()->castAs<FunctionProtoType>();
5888 const FunctionProtoType *Proto2 =
5889 FD2->getType()->castAs<FunctionProtoType>();
5890
5891 // - In the context of a function call, the function parameter types are
5892 // used.
5893 const CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
5894 const CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
5895 // C++20 [temp.func.order]p3
5896 // [...] Each function template M that is a member function is
5897 // considered to have a new first parameter of type
5898 // X(M), described below, inserted in its function parameter list.
5899 //
5900 // Note that we interpret "that is a member function" as
5901 // "that is a member function with no expicit object argument".
5902 // Otherwise the ordering rules for methods with expicit objet arguments
5903 // against anything else make no sense.
5904
5905 bool NonStaticMethod1 = Method1 && !Method1->isStatic(),
5906 NonStaticMethod2 = Method2 && !Method2->isStatic();
5907
5908 auto Params1Begin = Proto1->param_type_begin(),
5909 Params2Begin = Proto2->param_type_begin();
5910
5911 size_t NumComparedArguments = NumCallArguments1;
5912
5913 if (auto OO = FD1->getOverloadedOperator();
5914 (NonStaticMethod1 && NonStaticMethod2) ||
5915 (OO != OO_None && OO != OO_Call && OO != OO_Subscript)) {
5916 ShouldConvert1 =
5917 NonStaticMethod1 && !Method1->hasCXXExplicitFunctionObjectParameter();
5918 ShouldConvert2 =
5919 NonStaticMethod2 && !Method2->hasCXXExplicitFunctionObjectParameter();
5920 NumComparedArguments += 1;
5921
5922 if (ShouldConvert1) {
5923 bool IsRValRef2 =
5924 ShouldConvert2
5925 ? Method2->getRefQualifier() == RQ_RValue
5926 : Proto2->param_type_begin()[0]->isRValueReferenceType();
5927 // Compare 'this' from Method1 against first parameter from Method2.
5928 Obj1Ty = GetImplicitObjectParameterType(this->Context, Method1,
5929 RawObj1Ty, IsRValRef2);
5930 Args1.push_back(Obj1Ty);
5931 Args1Offset = true;
5932 }
5933 if (ShouldConvert2) {
5934 bool IsRValRef1 =
5935 ShouldConvert1
5936 ? Method1->getRefQualifier() == RQ_RValue
5937 : Proto1->param_type_begin()[0]->isRValueReferenceType();
5938 // Compare 'this' from Method2 against first parameter from Method1.
5939 Obj2Ty = GetImplicitObjectParameterType(this->Context, Method2,
5940 RawObj2Ty, IsRValRef1);
5941 Args2.push_back(Obj2Ty);
5942 Args2Offset = true;
5943 }
5944 } else {
5945 if (NonStaticMethod1 && Method1->hasCXXExplicitFunctionObjectParameter())
5946 Params1Begin += 1;
5947 if (NonStaticMethod2 && Method2->hasCXXExplicitFunctionObjectParameter())
5948 Params2Begin += 1;
5949 }
5950 Args1.insert(Args1.end(), Params1Begin, Proto1->param_type_end());
5951 Args2.insert(Args2.end(), Params2Begin, Proto2->param_type_end());
5952
5953 // C++ [temp.func.order]p5:
5954 // The presence of unused ellipsis and default arguments has no effect on
5955 // the partial ordering of function templates.
5956 Args1.resize(std::min(Args1.size(), NumComparedArguments));
5957 Args2.resize(std::min(Args2.size(), NumComparedArguments));
5958
5959 if (Reversed)
5960 std::reverse(Args2.begin(), Args2.end());
5961 } else {
5962 assert(!Reversed && "Only call context could have reversed arguments");
5963 }
5964 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, Args1,
5965 Args2, Args2Offset);
5966 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, Args2,
5967 Args1, Args1Offset);
5968 // C++ [temp.deduct.partial]p10:
5969 // F is more specialized than G if F is at least as specialized as G and G
5970 // is not at least as specialized as F.
5971 if (Better1 != Better2) // We have a clear winner
5972 return Better1 ? FT1 : FT2;
5973
5974 if (!Better1 && !Better2) // Neither is better than the other
5975 return nullptr;
5976
5977 // C++ [temp.deduct.partial]p11:
5978 // ... and if G has a trailing function parameter pack for which F does not
5979 // have a corresponding parameter, and if F does not have a trailing
5980 // function parameter pack, then F is more specialized than G.
5981
5982 SmallVector<QualType> Param1;
5983 Param1.reserve(FD1->param_size() + ShouldConvert1);
5984 if (ShouldConvert1)
5985 Param1.push_back(Obj1Ty);
5986 for (const auto &P : FD1->parameters())
5987 Param1.push_back(P->getType());
5988
5989 SmallVector<QualType> Param2;
5990 Param2.reserve(FD2->param_size() + ShouldConvert2);
5991 if (ShouldConvert2)
5992 Param2.push_back(Obj2Ty);
5993 for (const auto &P : FD2->parameters())
5994 Param2.push_back(P->getType());
5995
5996 unsigned NumParams1 = Param1.size();
5997 unsigned NumParams2 = Param2.size();
5998
5999 bool Variadic1 =
6000 FD1->param_size() && FD1->parameters().back()->isParameterPack();
6001 bool Variadic2 =
6002 FD2->param_size() && FD2->parameters().back()->isParameterPack();
6003 if (Variadic1 != Variadic2) {
6004 if (Variadic1 && NumParams1 > NumParams2)
6005 return FT2;
6006 if (Variadic2 && NumParams2 > NumParams1)
6007 return FT1;
6008 }
6009
6010 // Skip this tie breaker if we are performing overload resolution with partial
6011 // arguments, as this breaks some assumptions about how closely related the
6012 // candidates are.
6013 for (int i = 0, e = std::min(NumParams1, NumParams2);
6014 !PartialOverloading && i < e; ++i) {
6015 QualType T1 = Param1[i].getCanonicalType();
6016 QualType T2 = Param2[i].getCanonicalType();
6017 auto *TST1 = dyn_cast<TemplateSpecializationType>(T1);
6018 auto *TST2 = dyn_cast<TemplateSpecializationType>(T2);
6019 if (!TST1 || !TST2)
6020 continue;
6021 switch (getMoreSpecializedTrailingPackTieBreaker(TST1, TST2)) {
6023 return FT1;
6025 return FT2;
6027 continue;
6028 }
6029 llvm_unreachable(
6030 "unknown MoreSpecializedTrailingPackTieBreakerResult value");
6031 }
6032
6033 if (!Context.getLangOpts().CPlusPlus20)
6034 return nullptr;
6035
6036 // Match GCC on not implementing [temp.func.order]p6.2.1.
6037
6038 // C++20 [temp.func.order]p6:
6039 // If deduction against the other template succeeds for both transformed
6040 // templates, constraints can be considered as follows:
6041
6042 // C++20 [temp.func.order]p6.1:
6043 // If their template-parameter-lists (possibly including template-parameters
6044 // invented for an abbreviated function template ([dcl.fct])) or function
6045 // parameter lists differ in length, neither template is more specialized
6046 // than the other.
6049 if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
6050 return nullptr;
6051
6052 // C++20 [temp.func.order]p6.2.2:
6053 // Otherwise, if the corresponding template-parameters of the
6054 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6055 // function parameters that positionally correspond between the two
6056 // templates are not of the same type, neither template is more specialized
6057 // than the other.
6058 if (!TemplateParameterListsAreEqual(TPL1, TPL2, false,
6060 return nullptr;
6061
6062 // [dcl.fct]p5:
6063 // Any top-level cv-qualifiers modifying a parameter type are deleted when
6064 // forming the function type.
6065 for (unsigned i = 0; i < NumParams1; ++i)
6066 if (!Context.hasSameUnqualifiedType(Param1[i], Param2[i]))
6067 return nullptr;
6068
6069 // C++20 [temp.func.order]p6.3:
6070 // Otherwise, if the context in which the partial ordering is done is
6071 // that of a call to a conversion function and the return types of the
6072 // templates are not the same, then neither template is more specialized
6073 // than the other.
6074 if (TPOC == TPOC_Conversion &&
6075 !Context.hasSameType(FD1->getReturnType(), FD2->getReturnType()))
6076 return nullptr;
6077
6079 FT1->getAssociatedConstraints(AC1);
6080 FT2->getAssociatedConstraints(AC2);
6081 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6082 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
6083 return nullptr;
6084 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
6085 return nullptr;
6086 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6087 return nullptr;
6088 return AtLeastAsConstrained1 ? FT1 : FT2;
6089}
6090
6093 TemplateSpecCandidateSet &FailedCandidates,
6094 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
6095 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
6096 bool Complain, QualType TargetType) {
6097 if (SpecBegin == SpecEnd) {
6098 if (Complain) {
6099 Diag(Loc, NoneDiag);
6100 FailedCandidates.NoteCandidates(*this, Loc);
6101 }
6102 return SpecEnd;
6103 }
6104
6105 if (SpecBegin + 1 == SpecEnd)
6106 return SpecBegin;
6107
6108 // Find the function template that is better than all of the templates it
6109 // has been compared to.
6110 UnresolvedSetIterator Best = SpecBegin;
6111 FunctionTemplateDecl *BestTemplate
6112 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
6113 assert(BestTemplate && "Not a function template specialization?");
6114 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
6115 FunctionTemplateDecl *Challenger
6116 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6117 assert(Challenger && "Not a function template specialization?");
6118 if (declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6119 Loc, TPOC_Other, 0),
6120 Challenger)) {
6121 Best = I;
6122 BestTemplate = Challenger;
6123 }
6124 }
6125
6126 // Make sure that the "best" function template is more specialized than all
6127 // of the others.
6128 bool Ambiguous = false;
6129 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6130 FunctionTemplateDecl *Challenger
6131 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6132 if (I != Best &&
6133 !declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6134 Loc, TPOC_Other, 0),
6135 BestTemplate)) {
6136 Ambiguous = true;
6137 break;
6138 }
6139 }
6140
6141 if (!Ambiguous) {
6142 // We found an answer. Return it.
6143 return Best;
6144 }
6145
6146 // Diagnose the ambiguity.
6147 if (Complain) {
6148 Diag(Loc, AmbigDiag);
6149
6150 // FIXME: Can we order the candidates in some sane way?
6151 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6152 PartialDiagnostic PD = CandidateDiag;
6153 const auto *FD = cast<FunctionDecl>(*I);
6155 FD->getPrimaryTemplate()->getTemplateParameters(),
6156 *FD->getTemplateSpecializationArgs());
6157 if (!TargetType.isNull())
6158 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
6159 Diag((*I)->getLocation(), PD);
6160 }
6161 }
6162
6163 return SpecEnd;
6164}
6165
6167 FunctionDecl *FD2) {
6168 assert(!FD1->getDescribedTemplate() && !FD2->getDescribedTemplate() &&
6169 "not for function templates");
6170 assert(!FD1->isFunctionTemplateSpecialization() ||
6172 assert(!FD2->isFunctionTemplateSpecialization() ||
6174
6175 FunctionDecl *F1 = FD1;
6176 if (FunctionDecl *P = FD1->getTemplateInstantiationPattern(false))
6177 F1 = P;
6178
6179 FunctionDecl *F2 = FD2;
6180 if (FunctionDecl *P = FD2->getTemplateInstantiationPattern(false))
6181 F2 = P;
6182
6184 F1->getAssociatedConstraints(AC1);
6185 F2->getAssociatedConstraints(AC2);
6186 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6187 if (IsAtLeastAsConstrained(F1, AC1, F2, AC2, AtLeastAsConstrained1))
6188 return nullptr;
6189 if (IsAtLeastAsConstrained(F2, AC2, F1, AC1, AtLeastAsConstrained2))
6190 return nullptr;
6191 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6192 return nullptr;
6193 return AtLeastAsConstrained1 ? FD1 : FD2;
6194}
6195
6196/// Determine whether one template specialization, P1, is at least as
6197/// specialized than another, P2.
6198///
6199/// \tparam TemplateLikeDecl The kind of P2, which must be a
6200/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
6201/// \param T1 The injected-class-name of P1 (faked for a variable template).
6202/// \param T2 The injected-class-name of P2 (faked for a variable template).
6203/// \param Template The primary template of P2, in case it is a partial
6204/// specialization, the same as P2 otherwise.
6205template <typename TemplateLikeDecl>
6207 TemplateLikeDecl *P2,
6209 TemplateDeductionInfo &Info) {
6210 // C++ [temp.class.order]p1:
6211 // For two class template partial specializations, the first is at least as
6212 // specialized as the second if, given the following rewrite to two
6213 // function templates, the first function template is at least as
6214 // specialized as the second according to the ordering rules for function
6215 // templates (14.6.6.2):
6216 // - the first function template has the same template parameters as the
6217 // first partial specialization and has a single function parameter
6218 // whose type is a class template specialization with the template
6219 // arguments of the first partial specialization, and
6220 // - the second function template has the same template parameters as the
6221 // second partial specialization and has a single function parameter
6222 // whose type is a class template specialization with the template
6223 // arguments of the second partial specialization.
6224 //
6225 // Rather than synthesize function templates, we merely perform the
6226 // equivalent partial ordering by performing deduction directly on
6227 // the template arguments of the class template partial
6228 // specializations. This computation is slightly simpler than the
6229 // general problem of function template partial ordering, because
6230 // class template partial specializations are more constrained. We
6231 // know that every template parameter is deducible from the class
6232 // template partial specialization's template arguments, for
6233 // example.
6235
6236 // Determine whether P1 is at least as specialized as P2.
6237 Deduced.resize(P2->getTemplateParameters()->size());
6239 S, P2->getTemplateParameters(), T2, T1, Info, Deduced, TDF_None,
6240 PartialOrderingKind::Call, /*DeducedFromArrayBound=*/false,
6241 /*HasDeducedAnyParam=*/nullptr) != TemplateDeductionResult::Success)
6242 return false;
6243
6244 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
6245 Deduced.end());
6246 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
6247 Info);
6248 if (Inst.isInvalid())
6249 return false;
6250
6252 Ps = cast<TemplateSpecializationType>(T2)->template_arguments(),
6253 As = cast<TemplateSpecializationType>(T1)->template_arguments();
6254
6255 Sema::SFINAETrap Trap(S);
6256
6259 Result = ::FinishTemplateArgumentDeduction(
6260 S, P2, P2->getTemplateParameters(), Template,
6261 /*IsPartialOrdering=*/true, Ps, As, Deduced, Info,
6262 /*CopyDeducedArgs=*/false);
6263 });
6264
6266 return false;
6267
6268 if (Trap.hasErrorOccurred())
6269 return false;
6270
6271 return true;
6272}
6273
6274namespace {
6275// A dummy class to return nullptr instead of P2 when performing "more
6276// specialized than primary" check.
6277struct GetP2 {
6278 template <typename T1, typename T2,
6279 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6280 T2 *operator()(T1 *, T2 *P2) {
6281 return P2;
6282 }
6283 template <typename T1, typename T2,
6284 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6285 T1 *operator()(T1 *, T2 *) {
6286 return nullptr;
6287 }
6288};
6289
6290// The assumption is that two template argument lists have the same size.
6291struct TemplateArgumentListAreEqual {
6292 ASTContext &Ctx;
6293 TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
6294
6295 template <typename T1, typename T2,
6296 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6297 bool operator()(T1 *PS1, T2 *PS2) {
6298 ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
6299 Args2 = PS2->getTemplateArgs().asArray();
6300
6301 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6302 // We use profile, instead of structural comparison of the arguments,
6303 // because canonicalization can't do the right thing for dependent
6304 // expressions.
6305 llvm::FoldingSetNodeID IDA, IDB;
6306 Args1[I].Profile(IDA, Ctx);
6307 Args2[I].Profile(IDB, Ctx);
6308 if (IDA != IDB)
6309 return false;
6310 }
6311 return true;
6312 }
6313
6314 template <typename T1, typename T2,
6315 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6316 bool operator()(T1 *Spec, T2 *Primary) {
6317 ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
6318 Args2 = Primary->getInjectedTemplateArgs(Ctx);
6319
6320 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6321 // We use profile, instead of structural comparison of the arguments,
6322 // because canonicalization can't do the right thing for dependent
6323 // expressions.
6324 llvm::FoldingSetNodeID IDA, IDB;
6325 Args1[I].Profile(IDA, Ctx);
6326 // Unlike the specialization arguments, the injected arguments are not
6327 // always canonical.
6328 Ctx.getCanonicalTemplateArgument(Args2[I]).Profile(IDB, Ctx);
6329 if (IDA != IDB)
6330 return false;
6331 }
6332 return true;
6333 }
6334};
6335} // namespace
6336
6337/// Returns the more specialized template specialization between T1/P1 and
6338/// T2/P2.
6339/// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
6340/// specialization and T2/P2 is the primary template.
6341/// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
6342///
6343/// \param T1 the type of the first template partial specialization
6344///
6345/// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
6346/// template partial specialization; otherwise, the type of the
6347/// primary template.
6348///
6349/// \param P1 the first template partial specialization
6350///
6351/// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
6352/// partial specialization; otherwise, the primary template.
6353///
6354/// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
6355/// more specialized, returns nullptr if P1 is not more specialized.
6356/// - otherwise, returns the more specialized template partial
6357/// specialization. If neither partial specialization is more
6358/// specialized, returns NULL.
6359template <typename TemplateLikeDecl, typename PrimaryDel>
6360static TemplateLikeDecl *
6361getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
6362 PrimaryDel *P2, TemplateDeductionInfo &Info) {
6363 constexpr bool IsMoreSpecialThanPrimaryCheck =
6364 !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
6365
6366 TemplateDecl *P2T;
6367 if constexpr (IsMoreSpecialThanPrimaryCheck)
6368 P2T = P2;
6369 else
6370 P2T = P2->getSpecializedTemplate();
6371
6372 bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, P2T, Info);
6373 if (IsMoreSpecialThanPrimaryCheck && !Better1)
6374 return nullptr;
6375
6376 bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1,
6377 P1->getSpecializedTemplate(), Info);
6378 if (IsMoreSpecialThanPrimaryCheck && !Better2)
6379 return P1;
6380
6381 // C++ [temp.deduct.partial]p10:
6382 // F is more specialized than G if F is at least as specialized as G and G
6383 // is not at least as specialized as F.
6384 if (Better1 != Better2) // We have a clear winner
6385 return Better1 ? P1 : GetP2()(P1, P2);
6386
6387 if (!Better1 && !Better2)
6388 return nullptr;
6389
6394 return P1;
6396 return GetP2()(P1, P2);
6398 break;
6399 }
6400
6401 if (!S.Context.getLangOpts().CPlusPlus20)
6402 return nullptr;
6403
6404 // Match GCC on not implementing [temp.func.order]p6.2.1.
6405
6406 // C++20 [temp.func.order]p6:
6407 // If deduction against the other template succeeds for both transformed
6408 // templates, constraints can be considered as follows:
6409
6410 TemplateParameterList *TPL1 = P1->getTemplateParameters();
6411 TemplateParameterList *TPL2 = P2->getTemplateParameters();
6412 if (TPL1->size() != TPL2->size())
6413 return nullptr;
6414
6415 // C++20 [temp.func.order]p6.2.2:
6416 // Otherwise, if the corresponding template-parameters of the
6417 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6418 // function parameters that positionally correspond between the two
6419 // templates are not of the same type, neither template is more specialized
6420 // than the other.
6421 if (!S.TemplateParameterListsAreEqual(TPL1, TPL2, false,
6423 return nullptr;
6424
6425 if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
6426 return nullptr;
6427
6429 P1->getAssociatedConstraints(AC1);
6430 P2->getAssociatedConstraints(AC2);
6431 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6432 if (S.IsAtLeastAsConstrained(P1, AC1, P2, AC2, AtLeastAsConstrained1) ||
6433 (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
6434 return nullptr;
6435 if (S.IsAtLeastAsConstrained(P2, AC2, P1, AC1, AtLeastAsConstrained2))
6436 return nullptr;
6437 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6438 return nullptr;
6439 return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
6440}
6441
6453
6456 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
6459
6461 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6462 if (MaybeSpec)
6463 Info.clearSFINAEDiagnostic();
6464 return MaybeSpec;
6465}
6466
6471 // Pretend the variable template specializations are class template
6472 // specializations and form a fake injected class name type for comparison.
6473 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
6474 "the partial specializations being compared should specialize"
6475 " the same template.");
6477 QualType PT1 = Context.getCanonicalTemplateSpecializationType(
6479 QualType PT2 = Context.getCanonicalTemplateSpecializationType(
6481
6482 TemplateDeductionInfo Info(Loc);
6483 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6484}
6485
6488 VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
6489 TemplateName Name(Primary->getCanonicalDecl());
6490
6491 SmallVector<TemplateArgument, 8> PrimaryCanonArgs(
6493 Context.canonicalizeTemplateArguments(PrimaryCanonArgs);
6494
6495 QualType PrimaryT = Context.getCanonicalTemplateSpecializationType(
6496 ElaboratedTypeKeyword::None, Name, PrimaryCanonArgs);
6497 QualType PartialT = Context.getCanonicalTemplateSpecializationType(
6499
6501 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6502 if (MaybeSpec)
6503 Info.clearSFINAEDiagnostic();
6504 return MaybeSpec;
6505}
6506
6509 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
6510 bool PartialOrdering, bool *StrictPackMatch) {
6511 // C++1z [temp.arg.template]p4: (DR 150)
6512 // A template template-parameter P is at least as specialized as a
6513 // template template-argument A if, given the following rewrite to two
6514 // function templates...
6515
6516 // Rather than synthesize function templates, we merely perform the
6517 // equivalent partial ordering by performing deduction directly on
6518 // the template parameter lists of the template template parameters.
6519 //
6521
6525 if (Inst.isInvalid())
6526 return false;
6527
6528 // Given an invented class template X with the template parameter list of
6529 // A (including default arguments):
6530 // - Each function template has a single function parameter whose type is
6531 // a specialization of X with template arguments corresponding to the
6532 // template parameters from the respective function template
6534
6535 // Check P's arguments against A's parameter list. This will fill in default
6536 // template arguments as needed. AArgs are already correct by construction.
6537 // We can't just use CheckTemplateIdType because that will expand alias
6538 // templates.
6540 {
6542 P->getRAngleLoc());
6543 for (unsigned I = 0, N = P->size(); I != N; ++I) {
6544 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
6545 // expansions, to form an "as written" argument list.
6546 TemplateArgument Arg = PArgs[I];
6547 if (Arg.getKind() == TemplateArgument::Pack) {
6548 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
6549 Arg = *Arg.pack_begin();
6550 }
6552 Arg, QualType(), P->getParam(I)->getLocation()));
6553 }
6554 PArgs.clear();
6555
6556 // C++1z [temp.arg.template]p3:
6557 // If the rewrite produces an invalid type, then P is not at least as
6558 // specialized as A.
6560 /*PartialOrdering=*/false, /*MatchingTTP=*/true);
6561 CTAI.SugaredConverted = std::move(PArgs);
6562 if (CheckTemplateArgumentList(AArg, ArgLoc, PArgList, DefaultArgs,
6563 /*PartialTemplateArgs=*/false, CTAI,
6564 /*UpdateArgsWithConversions=*/true,
6565 /*ConstraintsNotSatisfied=*/nullptr))
6566 return false;
6567 PArgs = std::move(CTAI.SugaredConverted);
6568 if (StrictPackMatch)
6569 *StrictPackMatch |= CTAI.StrictPackMatch;
6570 }
6571
6572 // Determine whether P1 is at least as specialized as P2.
6573 TemplateDeductionInfo Info(ArgLoc, A->getDepth());
6575 Deduced.resize(A->size());
6576
6577 // ... the function template corresponding to P is at least as specialized
6578 // as the function template corresponding to A according to the partial
6579 // ordering rules for function templates.
6580
6581 // Provisional resolution for CWG2398: Regarding temp.arg.template]p4, when
6582 // applying the partial ordering rules for function templates on
6583 // the rewritten template template parameters:
6584 // - In a deduced context, the matching of packs versus fixed-size needs to
6585 // be inverted between Ps and As. On non-deduced context, matching needs to
6586 // happen both ways, according to [temp.arg.template]p3, but this is
6587 // currently implemented as a special case elsewhere.
6589 *this, A, AArgs, PArgs, Info, Deduced,
6590 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/true,
6592 /*HasDeducedAnyParam=*/nullptr)) {
6594 if (StrictPackMatch && Info.hasStrictPackMatch())
6595 *StrictPackMatch = true;
6596 break;
6597
6599 Diag(AArg->getLocation(), diag::err_template_param_list_different_arity)
6600 << (A->size() > P->size()) << /*isTemplateTemplateParameter=*/true
6602 return false;
6604 Diag(AArg->getLocation(), diag::err_non_deduced_mismatch)
6605 << Info.FirstArg << Info.SecondArg;
6606 return false;
6609 diag::err_inconsistent_deduction)
6610 << Info.FirstArg << Info.SecondArg;
6611 return false;
6613 return false;
6614
6615 // None of these should happen for a plain deduction.
6630 llvm_unreachable("Unexpected Result");
6631 }
6632
6635 TDK = ::FinishTemplateArgumentDeduction(
6636 *this, AArg, AArg->getTemplateParameters(), AArg, PartialOrdering,
6637 AArgs, PArgs, Deduced, Info, /*CopyDeducedArgs=*/false);
6638 });
6639 switch (TDK) {
6641 return true;
6642
6643 // It doesn't seem possible to get a non-deduced mismatch when partial
6644 // ordering TTPs, except with an invalid template parameter list which has
6645 // a parameter after a pack.
6647 assert(PArg->isInvalidDecl() && "Unexpected NonDeducedMismatch");
6648 return false;
6649
6650 // Substitution failures should have already been diagnosed.
6654 return false;
6655
6656 // None of these should happen when just converting deduced arguments.
6671 llvm_unreachable("Unexpected Result");
6672 }
6673 llvm_unreachable("Unexpected TDK");
6674}
6675
6676namespace {
6677struct MarkUsedTemplateParameterVisitor : DynamicRecursiveASTVisitor {
6678 llvm::SmallBitVector &Used;
6679 unsigned Depth;
6680 bool VisitDeclRefTypes = true;
6681
6682 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used, unsigned Depth,
6683 bool VisitDeclRefTypes = true)
6684 : Used(Used), Depth(Depth), VisitDeclRefTypes(VisitDeclRefTypes) {}
6685
6686 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
6687 if (T->getDepth() == Depth)
6688 Used[T->getIndex()] = true;
6689 return true;
6690 }
6691
6692 bool TraverseTemplateName(TemplateName Template) override {
6693 if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
6694 Template.getAsTemplateDecl()))
6695 if (TTP->getDepth() == Depth)
6696 Used[TTP->getIndex()] = true;
6698 return true;
6699 }
6700
6701 bool VisitDeclRefExpr(DeclRefExpr *E) override {
6702 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
6703 if (NTTP->getDepth() == Depth)
6704 Used[NTTP->getIndex()] = true;
6705 if (VisitDeclRefTypes)
6707 return true;
6708 }
6709
6710 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
6711 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
6712 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
6713 if (TTP->getDepth() == Depth)
6714 Used[TTP->getIndex()] = true;
6715 }
6716 for (auto &TLoc : ULE->template_arguments())
6718 }
6719 return true;
6720 }
6721};
6722}
6723
6724/// Mark the template parameters that are used by the given
6725/// expression.
6726static void
6728 const Expr *E,
6729 bool OnlyDeduced,
6730 unsigned Depth,
6731 llvm::SmallBitVector &Used) {
6732 if (!OnlyDeduced) {
6733 MarkUsedTemplateParameterVisitor(Used, Depth)
6734 .TraverseStmt(const_cast<Expr *>(E));
6735 return;
6736 }
6737
6738 // We can deduce from a pack expansion.
6739 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
6740 E = Expansion->getPattern();
6741
6743 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E);
6744 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
6745 if (const auto *TTP = ULE->getTemplateTemplateDecl())
6746 Used[TTP->getIndex()] = true;
6747 for (auto &TLoc : ULE->template_arguments())
6748 MarkUsedTemplateParameters(Ctx, TLoc.getArgument(), OnlyDeduced, Depth,
6749 Used);
6750 return;
6751 }
6752
6753 const NonTypeOrVarTemplateParmDecl NTTP =
6755 if (!NTTP)
6756 return;
6757 if (NTTP.getDepth() == Depth)
6758 Used[NTTP.getIndex()] = true;
6759
6760 // In C++17 mode, additional arguments may be deduced from the type of a
6761 // non-type argument.
6762 if (Ctx.getLangOpts().CPlusPlus17)
6763 MarkUsedTemplateParameters(Ctx, NTTP.getType(), OnlyDeduced, Depth, Used);
6764}
6765
6766/// Mark the template parameters that are used by the given
6767/// nested name specifier.
6769 bool OnlyDeduced, unsigned Depth,
6770 llvm::SmallBitVector &Used) {
6772 return;
6773 MarkUsedTemplateParameters(Ctx, QualType(NNS.getAsType(), 0), OnlyDeduced,
6774 Depth, Used);
6775}
6776
6777/// Mark the template parameters that are used by the given
6778/// template name.
6779static void
6781 TemplateName Name,
6782 bool OnlyDeduced,
6783 unsigned Depth,
6784 llvm::SmallBitVector &Used) {
6785 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
6787 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
6788 if (TTP->getDepth() == Depth)
6789 Used[TTP->getIndex()] = true;
6790 }
6791 return;
6792 }
6793
6795 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
6796 Depth, Used);
6798 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
6799 Depth, Used);
6800}
6801
6802/// Mark the template parameters that are used by the given
6803/// type.
6804static void
6806 bool OnlyDeduced,
6807 unsigned Depth,
6808 llvm::SmallBitVector &Used) {
6809 if (T.isNull())
6810 return;
6811
6812 // Non-dependent types have nothing deducible
6813 if (!T->isDependentType())
6814 return;
6815
6816 T = Ctx.getCanonicalType(T);
6817 switch (T->getTypeClass()) {
6818 case Type::Pointer:
6821 OnlyDeduced,
6822 Depth,
6823 Used);
6824 break;
6825
6826 case Type::BlockPointer:
6829 OnlyDeduced,
6830 Depth,
6831 Used);
6832 break;
6833
6834 case Type::LValueReference:
6835 case Type::RValueReference:
6838 OnlyDeduced,
6839 Depth,
6840 Used);
6841 break;
6842
6843 case Type::MemberPointer: {
6844 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
6845 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
6846 Depth, Used);
6848 QualType(MemPtr->getQualifier().getAsType(), 0),
6849 OnlyDeduced, Depth, Used);
6850 break;
6851 }
6852
6853 case Type::DependentSizedArray:
6855 cast<DependentSizedArrayType>(T)->getSizeExpr(),
6856 OnlyDeduced, Depth, Used);
6857 // Fall through to check the element type
6858 [[fallthrough]];
6859
6860 case Type::ConstantArray:
6861 case Type::IncompleteArray:
6862 case Type::ArrayParameter:
6864 cast<ArrayType>(T)->getElementType(),
6865 OnlyDeduced, Depth, Used);
6866 break;
6867 case Type::Vector:
6868 case Type::ExtVector:
6870 cast<VectorType>(T)->getElementType(),
6871 OnlyDeduced, Depth, Used);
6872 break;
6873
6874 case Type::DependentVector: {
6875 const auto *VecType = cast<DependentVectorType>(T);
6876 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6877 Depth, Used);
6878 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
6879 Used);
6880 break;
6881 }
6882 case Type::DependentSizedExtVector: {
6883 const DependentSizedExtVectorType *VecType
6885 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6886 Depth, Used);
6887 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
6888 Depth, Used);
6889 break;
6890 }
6891
6892 case Type::DependentAddressSpace: {
6893 const DependentAddressSpaceType *DependentASType =
6895 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
6896 OnlyDeduced, Depth, Used);
6898 DependentASType->getAddrSpaceExpr(),
6899 OnlyDeduced, Depth, Used);
6900 break;
6901 }
6902
6903 case Type::ConstantMatrix: {
6905 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6906 Depth, Used);
6907 break;
6908 }
6909
6910 case Type::DependentSizedMatrix: {
6912 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6913 Depth, Used);
6914 MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
6915 Used);
6916 MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
6917 Depth, Used);
6918 break;
6919 }
6920
6921 case Type::FunctionProto: {
6923 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
6924 Used);
6925 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
6926 // C++17 [temp.deduct.type]p5:
6927 // The non-deduced contexts are: [...]
6928 // -- A function parameter pack that does not occur at the end of the
6929 // parameter-declaration-list.
6930 if (!OnlyDeduced || I + 1 == N ||
6931 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
6932 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
6933 Depth, Used);
6934 } else {
6935 // FIXME: C++17 [temp.deduct.call]p1:
6936 // When a function parameter pack appears in a non-deduced context,
6937 // the type of that pack is never deduced.
6938 //
6939 // We should also track a set of "never deduced" parameters, and
6940 // subtract that from the list of deduced parameters after marking.
6941 }
6942 }
6943 if (auto *E = Proto->getNoexceptExpr())
6944 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
6945 break;
6946 }
6947
6948 case Type::TemplateTypeParm: {
6949 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
6950 if (TTP->getDepth() == Depth)
6951 Used[TTP->getIndex()] = true;
6952 break;
6953 }
6954
6955 case Type::SubstTemplateTypeParmPack: {
6956 const SubstTemplateTypeParmPackType *Subst
6958 if (Subst->getReplacedParameter()->getDepth() == Depth)
6959 Used[Subst->getIndex()] = true;
6960 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(), OnlyDeduced,
6961 Depth, Used);
6962 break;
6963 }
6964 case Type::SubstBuiltinTemplatePack: {
6965 MarkUsedTemplateParameters(Ctx, cast<SubstPackType>(T)->getArgumentPack(),
6966 OnlyDeduced, Depth, Used);
6967 break;
6968 }
6969
6970 case Type::InjectedClassName:
6972 ->getOriginalDecl()
6973 ->getCanonicalTemplateSpecializationType(Ctx);
6974 [[fallthrough]];
6975
6976 case Type::TemplateSpecialization: {
6977 const TemplateSpecializationType *Spec
6979
6980 TemplateName Name = Spec->getTemplateName();
6981 if (OnlyDeduced && Name.getAsDependentTemplateName())
6982 break;
6983
6984 MarkUsedTemplateParameters(Ctx, Name, OnlyDeduced, Depth, Used);
6985
6986 // C++0x [temp.deduct.type]p9:
6987 // If the template argument list of P contains a pack expansion that is
6988 // not the last template argument, the entire template argument list is a
6989 // non-deduced context.
6990 if (OnlyDeduced &&
6991 hasPackExpansionBeforeEnd(Spec->template_arguments()))
6992 break;
6993
6994 for (const auto &Arg : Spec->template_arguments())
6995 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6996 break;
6997 }
6998
6999 case Type::Complex:
7000 if (!OnlyDeduced)
7002 cast<ComplexType>(T)->getElementType(),
7003 OnlyDeduced, Depth, Used);
7004 break;
7005
7006 case Type::Atomic:
7007 if (!OnlyDeduced)
7009 cast<AtomicType>(T)->getValueType(),
7010 OnlyDeduced, Depth, Used);
7011 break;
7012
7013 case Type::DependentName:
7014 if (!OnlyDeduced)
7016 cast<DependentNameType>(T)->getQualifier(),
7017 OnlyDeduced, Depth, Used);
7018 break;
7019
7020 case Type::TypeOf:
7021 if (!OnlyDeduced)
7022 MarkUsedTemplateParameters(Ctx, cast<TypeOfType>(T)->getUnmodifiedType(),
7023 OnlyDeduced, Depth, Used);
7024 break;
7025
7026 case Type::TypeOfExpr:
7027 if (!OnlyDeduced)
7029 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
7030 OnlyDeduced, Depth, Used);
7031 break;
7032
7033 case Type::Decltype:
7034 if (!OnlyDeduced)
7036 cast<DecltypeType>(T)->getUnderlyingExpr(),
7037 OnlyDeduced, Depth, Used);
7038 break;
7039
7040 case Type::PackIndexing:
7041 if (!OnlyDeduced) {
7043 OnlyDeduced, Depth, Used);
7045 OnlyDeduced, Depth, Used);
7046 }
7047 break;
7048
7049 case Type::UnaryTransform:
7050 if (!OnlyDeduced) {
7051 auto *UTT = cast<UnaryTransformType>(T);
7052 auto Next = UTT->getUnderlyingType();
7053 if (Next.isNull())
7054 Next = UTT->getBaseType();
7055 MarkUsedTemplateParameters(Ctx, Next, OnlyDeduced, Depth, Used);
7056 }
7057 break;
7058
7059 case Type::PackExpansion:
7061 cast<PackExpansionType>(T)->getPattern(),
7062 OnlyDeduced, Depth, Used);
7063 break;
7064
7065 case Type::Auto:
7066 case Type::DeducedTemplateSpecialization:
7068 cast<DeducedType>(T)->getDeducedType(),
7069 OnlyDeduced, Depth, Used);
7070 break;
7071 case Type::DependentBitInt:
7073 cast<DependentBitIntType>(T)->getNumBitsExpr(),
7074 OnlyDeduced, Depth, Used);
7075 break;
7076
7077 case Type::HLSLAttributedResource:
7079 Ctx, cast<HLSLAttributedResourceType>(T)->getWrappedType(), OnlyDeduced,
7080 Depth, Used);
7081 if (cast<HLSLAttributedResourceType>(T)->hasContainedType())
7083 Ctx, cast<HLSLAttributedResourceType>(T)->getContainedType(),
7084 OnlyDeduced, Depth, Used);
7085 break;
7086
7087 // None of these types have any template parameters in them.
7088 case Type::Builtin:
7089 case Type::VariableArray:
7090 case Type::FunctionNoProto:
7091 case Type::Record:
7092 case Type::Enum:
7093 case Type::ObjCInterface:
7094 case Type::ObjCObject:
7095 case Type::ObjCObjectPointer:
7096 case Type::UnresolvedUsing:
7097 case Type::Pipe:
7098 case Type::BitInt:
7099 case Type::HLSLInlineSpirv:
7100#define TYPE(Class, Base)
7101#define ABSTRACT_TYPE(Class, Base)
7102#define DEPENDENT_TYPE(Class, Base)
7103#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7104#include "clang/AST/TypeNodes.inc"
7105 break;
7106 }
7107}
7108
7109/// Mark the template parameters that are used by this
7110/// template argument.
7111static void
7114 bool OnlyDeduced,
7115 unsigned Depth,
7116 llvm::SmallBitVector &Used) {
7117 switch (TemplateArg.getKind()) {
7123 break;
7124
7126 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
7127 Depth, Used);
7128 break;
7129
7133 TemplateArg.getAsTemplateOrTemplatePattern(),
7134 OnlyDeduced, Depth, Used);
7135 break;
7136
7138 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
7139 Depth, Used);
7140 break;
7141
7143 for (const auto &P : TemplateArg.pack_elements())
7144 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
7145 break;
7146 }
7147}
7148
7149void
7150Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
7151 unsigned Depth,
7152 llvm::SmallBitVector &Used) {
7153 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
7154}
7155
7157 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used) {
7158 MarkUsedTemplateParameterVisitor(Used, Depth, /*VisitDeclRefTypes=*/false)
7159 .TraverseStmt(const_cast<Expr *>(E));
7160}
7161
7162void
7164 bool OnlyDeduced, unsigned Depth,
7165 llvm::SmallBitVector &Used) {
7166 // C++0x [temp.deduct.type]p9:
7167 // If the template argument list of P contains a pack expansion that is not
7168 // the last template argument, the entire template argument list is a
7169 // non-deduced context.
7170 if (OnlyDeduced &&
7171 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
7172 return;
7173
7174 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7175 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
7176 Depth, Used);
7177}
7178
7180 unsigned Depth,
7181 llvm::SmallBitVector &Used) {
7182 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7183 ::MarkUsedTemplateParameters(Context, TemplateArgs[I],
7184 /*OnlyDeduced=*/false, Depth, Used);
7185}
7186
7188 ArrayRef<TemplateArgumentLoc> TemplateArgs, unsigned Depth,
7189 llvm::SmallBitVector &Used) {
7190 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7192 /*OnlyDeduced=*/false, Depth, Used);
7193}
7194
7197 llvm::SmallBitVector &Deduced) {
7198 TemplateParameterList *TemplateParams
7199 = FunctionTemplate->getTemplateParameters();
7200 Deduced.clear();
7201 Deduced.resize(TemplateParams->size());
7202
7203 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
7204 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
7205 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
7206 true, TemplateParams->getDepth(), Deduced);
7207}
7208
7211 QualType T) {
7212 if (!T->isDependentType())
7213 return false;
7214
7215 TemplateParameterList *TemplateParams
7216 = FunctionTemplate->getTemplateParameters();
7217 llvm::SmallBitVector Deduced(TemplateParams->size());
7218 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
7219 Deduced);
7220
7221 return Deduced.any();
7222}
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.
#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 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 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...
PackFold
What directions packs are allowed to match non-packs.
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:220
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
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
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
Definition ASTContext.h:926
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
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
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 ...
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.
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.
const DependentSizedArrayType * getAsDependentSizedArrayType(QualType T) const
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8146
Pointer to a block type.
Definition TypeBase.h:3542
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2943
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2983
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
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:2703
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition DeclCXX.h:2305
bool isStatic() const
Definition DeclCXX.cpp:2401
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:768
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
base_class_range bases()
Definition DeclCXX.h:608
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1736
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:3275
Declaration of a C++20 concept.
const TypeClass * getTypePtr() const
Definition TypeLoc.h:438
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4373
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4394
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4391
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.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
ValueDecl * getDecl()
Definition Expr.h:1338
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:263
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:524
bool isInvalidDecl() const
Definition DeclBase.h:588
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
Captures a template argument whose value has been deduced via c++ template argument deduction.
Definition Template.h:331
void setDeducedFromArrayBound(bool Deduced)
Specify whether the given non-type template argument was deduced from an array bound.
Definition Template.h:358
bool wasDeducedFromArrayBound() const
For a non-type template argument, determine whether the template argument was deduced from an array b...
Definition Template.h:354
SourceLocation getElaboratedKeywordLoc() const
Definition TypeLoc.h:2489
NestedNameSpecifierLoc getQualifierLoc() const
Definition TypeLoc.h:2501
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4061
QualType getPointeeType() const
Definition TypeBase.h:4073
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4101
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4432
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4227
virtual bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc)
virtual bool TraverseTemplateName(TemplateName Template)
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:1924
bool isInvalid() const
Determine if the explicit specifier is invalid.
Definition DeclCXX.h:1953
const Expr * getExpr() const
Definition DeclCXX.h:1933
The return type of classify().
Definition Expr.h:337
bool isLValue() const
Definition Expr.h:387
This represents one expression.
Definition Expr.h:112
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3077
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
QualType getType() const
Definition Expr.h:144
ExtVectorType - Extended vector type.
Definition TypeBase.h:4267
Stores a list of template parameters and the associated requires-clause (if any) for a TemplateDecl a...
Represents a function declaration or definition.
Definition Decl.h:2000
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4193
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3853
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
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:4252
void getAssociatedConstraints(SmallVectorImpl< AssociatedConstraint > &ACs) const
Get the associated-constraints of this function declaration.
Definition Decl.h:2752
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4317
bool isImmediateEscalating() const
Definition Decl.cpp:3303
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4118
size_t param_size() const
Definition Decl.h:2790
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5266
param_type_iterator param_type_begin() const
Definition TypeBase.h:5710
const ExtParameterInfo * getExtParameterInfosOrNull() const
Return a pointer to the beginning of the array of extra parameter information, if present,...
Definition TypeBase.h:5748
unsigned getNumParams() const
Definition TypeBase.h:5544
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition TypeBase.h:5686
Qualifiers getMethodQuals() const
Definition TypeBase.h:5692
QualType getParamType(unsigned i) const
Definition TypeBase.h:5546
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5579
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5670
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5555
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition TypeBase.h:5631
param_type_iterator param_type_end() const
Definition TypeBase.h:5714
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5551
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition TypeBase.h:5700
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:4462
QualType getReturnType() const
Definition TypeBase.h:4802
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Describes an C or C++ initializer list.
Definition Expr.h:5233
unsigned getNumInits() const
Definition Expr.h:5263
unsigned getNumInitsWithEmbedExpanded() const
getNumInits but if the list has an EmbedExpr inside includes full length of embedded data.
Definition Expr.h:5267
ArrayRef< Expr * > inits()
Definition Expr.h:5283
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3617
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:369
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:557
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4337
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4351
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3653
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3685
QualType getPointeeType() const
Definition TypeBase.h:3671
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:264
void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final=false)
Replaces the current 'innermost' level with the provided argument list.
Definition Template.h:237
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
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:7912
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition ExprCXX.h:3130
bool isVarDeclReference() const
Definition ExprCXX.h:3304
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3282
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3191
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3243
decls_iterator decls_begin() const
Definition ExprCXX.h:3223
TemplateTemplateParmDecl * getTemplateTemplateDecl() const
Definition ExprCXX.h:3320
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3344
bool isConceptReference() const
Definition ExprCXX.h:3293
decls_iterator decls_end() const
Definition ExprCXX.h:3226
ArrayRef< TemplateArgumentLoc > template_arguments() const
Definition ExprCXX.h:3339
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4365
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:290
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8383
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8294
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8420
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8334
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:8479
QualType getCanonicalType() const
Definition TypeBase.h:8346
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8388
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8340
Represents a template name as written in source code.
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:495
GC getObjCGCAttr() const
Definition TypeBase.h:519
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
void removeObjCLifetime()
Definition TypeBase.h:551
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:457
bool hasNonTrivialObjCLifetime() const
True if the lifetime is neither None or ExplicitNone.
Definition TypeBase.h:559
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:727
bool hasAddressSpace() const
Definition TypeBase.h:570
void removeObjCGCAttr()
Definition TypeBase.h:523
void removeAddressSpace()
Definition TypeBase.h:596
bool hasObjCGCAttr() const
Definition TypeBase.h:518
void setCVRQualifiers(unsigned mask)
Definition TypeBase.h:491
bool hasObjCLifetime() const
Definition TypeBase.h:544
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
Qualifiers withoutObjCLifetime() const
Definition TypeBase.h:533
LangAS getAddressSpace() const
Definition TypeBase.h:571
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:548
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3635
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:3573
QualType getPointeeType() const
Definition TypeBase.h:3591
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, bool DeferHint=false)
Emit a diagnostic.
Definition SemaBase.cpp:61
RAII object used to change the argument pack substitution index within a Sema object.
Definition Sema.h:13552
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8401
A RAII object to temporarily push a declaration context.
Definition Sema.h:3476
A helper class for building up ExtParameterInfos.
Definition Sema.h:12955
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:12974
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12392
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12425
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
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:12984
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
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:1445
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:6890
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:11929
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:11921
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:11925
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition Sema.h:1283
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:925
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:756
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:1191
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:12126
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:918
UnsignedOrNone getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs)
Determine the number of arguments in the given pack expansion type.
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:1418
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:12458
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.
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.
bool IsFunctionConversion(QualType FromType, QualType ToType, bool *DiscardingCFIUncheckedCallee=nullptr, bool *AddingCFIUncheckedCallee=nullptr) const
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
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)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15325
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.
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6675
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:627
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
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.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6383
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
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:12827
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
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
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...
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, unsigned D, unsigned 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:3538
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
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:8265
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8276
SourceLocation getNameLoc() const
Definition TypeLoc.h:552
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:556
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isVoidType() const
Definition TypeBase.h:8887
const TemplateSpecializationType * getAsNonAliasTemplateSpecializationType() const
Look through sugar for an instance of TemplateSpecializationType which is not a type alias,...
Definition Type.cpp:1921
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:8863
bool isRValueReferenceType() const
Definition TypeBase.h:8563
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:8630
bool isFunctionPointerType() const
Definition TypeBase.h:8598
bool isPointerType() const
Definition TypeBase.h:8531
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9174
bool isReferenceType() const
Definition TypeBase.h:8555
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2899
bool isLValueReferenceType() const
Definition TypeBase.h:8559
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3119
bool isMemberPointerType() const
Definition TypeBase.h:8612
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5310
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9023
bool isFunctionType() const
Definition TypeBase.h:8527
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8616
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2921
bool isAnyPointerType() const
Definition TypeBase.h:8539
TypeClass getTypeClass() const
Definition TypeBase.h:2385
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9107
bool isRecordType() const
Definition TypeBase.h:8658
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:712
QualType getType() const
Definition Decl.h:723
QualType getType() const
Definition Value.cpp:237
Represents a variable declaration or definition.
Definition Decl.h:926
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1578
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:4175
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.
#define bool
Definition gpuintrin.h:32
__inline void unsigned int _2
The JSON file list parser is used to communicate input to InstallAPI.
@ OO_None
Not an overloaded operator.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:816
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:785
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1782
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1788
@ 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)
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:905
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:585
@ Concept
The name was classified as a concept name.
Definition Sema.h:589
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition ASTLambda.h:69
@ 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:302
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition Template.h:308
@ TPOC_Other
Partial ordering of function templates in other contexts, e.g., taking the address of a function temp...
Definition Template.h:313
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:304
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:367
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:417
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:412
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:415
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:388
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:374
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:410
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:419
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:407
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:377
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:371
@ Success
Template argument deduction was successful.
Definition Sema.h:369
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:391
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:380
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:394
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:383
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:404
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:421
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:398
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:401
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:832
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5886
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 false
Definition stdbool.h:26
#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:5325
Extra information about a function prototype.
Definition TypeBase.h:5351
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5356
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:11956
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:11952
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:11945
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:11942
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:11942
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition Sema.h:13022
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13029
A stack object to be created when performing template instantiation.
Definition Sema.h:13197
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13357
brief A function argument from which we performed template argument
Definition Sema.h:12558
Location information for a TemplateArgument.