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