clang 20.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"
42#include "clang/Sema/Sema.h"
43#include "clang/Sema/Template.h"
45#include "llvm/ADT/APInt.h"
46#include "llvm/ADT/APSInt.h"
47#include "llvm/ADT/ArrayRef.h"
48#include "llvm/ADT/DenseMap.h"
49#include "llvm/ADT/FoldingSet.h"
50#include "llvm/ADT/SmallBitVector.h"
51#include "llvm/ADT/SmallPtrSet.h"
52#include "llvm/ADT/SmallVector.h"
53#include "llvm/Support/Casting.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/Support/ErrorHandling.h"
56#include <algorithm>
57#include <cassert>
58#include <optional>
59#include <tuple>
60#include <type_traits>
61#include <utility>
62
63namespace clang {
64
65 /// Various flags that control template argument deduction.
66 ///
67 /// These flags can be bitwise-OR'd together.
69 /// No template argument deduction flags, which indicates the
70 /// strictest results for template argument deduction (as used for, e.g.,
71 /// matching class template partial specializations).
73
74 /// Within template argument deduction from a function call, we are
75 /// matching with a parameter type for which the original parameter was
76 /// a reference.
78
79 /// Within template argument deduction from a function call, we
80 /// are matching in a case where we ignore cv-qualifiers.
82
83 /// Within template argument deduction from a function call,
84 /// we are matching in a case where we can perform template argument
85 /// deduction from a template-id of a derived class of the argument type.
87
88 /// Allow non-dependent types to differ, e.g., when performing
89 /// template argument deduction from a function call where conversions
90 /// may apply.
92
93 /// Whether we are performing template argument deduction for
94 /// parameters and arguments in a top-level template argument
96
97 /// Within template argument deduction from overload resolution per
98 /// C++ [over.over] allow matching function types that are compatible in
99 /// terms of noreturn and default calling convention adjustments, or
100 /// similarly matching a declared template specialization against a
101 /// possible template, per C++ [temp.deduct.decl]. In either case, permit
102 /// deduction where the parameter is a function type that can be converted
103 /// to the argument type.
105
106 /// Within template argument deduction for a conversion function, we are
107 /// matching with an argument type for which the original argument was
108 /// a reference.
110 };
111}
112
113using namespace clang;
114using namespace sema;
115
116/// Compare two APSInts, extending and switching the sign as
117/// necessary to compare their values regardless of underlying type.
118static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
119 if (Y.getBitWidth() > X.getBitWidth())
120 X = X.extend(Y.getBitWidth());
121 else if (Y.getBitWidth() < X.getBitWidth())
122 Y = Y.extend(X.getBitWidth());
123
124 // If there is a signedness mismatch, correct it.
125 if (X.isSigned() != Y.isSigned()) {
126 // If the signed value is negative, then the values cannot be the same.
127 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
128 return false;
129
130 Y.setIsSigned(true);
131 X.setIsSigned(true);
132 }
133
134 return X == Y;
135}
136
137/// The kind of PartialOrdering we're performing template argument deduction
138/// for (C++11 [temp.deduct.partial]).
140
142 Sema &S, TemplateParameterList *TemplateParams, QualType Param,
144 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
145 PartialOrderingKind POK, bool DeducedFromArrayBound,
146 bool *HasDeducedAnyParam);
147
155 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
156 PackFold PackFold, bool *HasDeducedAnyParam);
157
160 bool OnlyDeduced, unsigned Depth,
161 llvm::SmallBitVector &Used);
162
164 bool OnlyDeduced, unsigned Level,
165 llvm::SmallBitVector &Deduced);
166
167/// If the given expression is of a form that permits the deduction
168/// of a non-type template parameter, return the declaration of that
169/// non-type template parameter.
170static const NonTypeTemplateParmDecl *
171getDeducedParameterFromExpr(const Expr *E, unsigned Depth) {
172 // If we are within an alias template, the expression may have undergone
173 // any number of parameter substitutions already.
174 while (true) {
175 if (const auto *IC = dyn_cast<ImplicitCastExpr>(E))
176 E = IC->getSubExpr();
177 else if (const auto *CE = dyn_cast<ConstantExpr>(E))
178 E = CE->getSubExpr();
179 else if (const auto *Subst = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
180 E = Subst->getReplacement();
181 else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) {
182 // Look through implicit copy construction from an lvalue of the same type.
183 if (CCE->getParenOrBraceRange().isValid())
184 break;
185 // Note, there could be default arguments.
186 assert(CCE->getNumArgs() >= 1 && "implicit construct expr should have 1 arg");
187 E = CCE->getArg(0);
188 } else
189 break;
190 }
191
192 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
193 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
194 if (NTTP->getDepth() == Depth)
195 return NTTP;
196
197 return nullptr;
198}
199
200static const NonTypeTemplateParmDecl *
203}
204
205/// Determine whether two declaration pointers refer to the same
206/// declaration.
207static bool isSameDeclaration(Decl *X, Decl *Y) {
208 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
209 X = NX->getUnderlyingDecl();
210 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
211 Y = NY->getUnderlyingDecl();
212
213 return X->getCanonicalDecl() == Y->getCanonicalDecl();
214}
215
216/// Verify that the given, deduced template arguments are compatible.
217///
218/// \returns The deduced template argument, or a NULL template argument if
219/// the deduced template arguments were incompatible.
224 bool AggregateCandidateDeduction = false) {
225 // We have no deduction for one or both of the arguments; they're compatible.
226 if (X.isNull())
227 return Y;
228 if (Y.isNull())
229 return X;
230
231 // If we have two non-type template argument values deduced for the same
232 // parameter, they must both match the type of the parameter, and thus must
233 // match each other's type. As we're only keeping one of them, we must check
234 // for that now. The exception is that if either was deduced from an array
235 // bound, the type is permitted to differ.
236 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
237 QualType XType = X.getNonTypeTemplateArgumentType();
238 if (!XType.isNull()) {
240 if (YType.isNull() || !Context.hasSameType(XType, YType))
242 }
243 }
244
245 switch (X.getKind()) {
247 llvm_unreachable("Non-deduced template arguments handled above");
248
250 // If two template type arguments have the same type, they're compatible.
251 QualType TX = X.getAsType(), TY = Y.getAsType();
252 if (Y.getKind() == TemplateArgument::Type && Context.hasSameType(TX, TY))
253 return DeducedTemplateArgument(Context.getCommonSugaredType(TX, TY),
254 X.wasDeducedFromArrayBound() ||
256
257 // If one of the two arguments was deduced from an array bound, the other
258 // supersedes it.
259 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
260 return X.wasDeducedFromArrayBound() ? Y : X;
261
262 // The arguments are not compatible.
264 }
265
267 // If we deduced a constant in one case and either a dependent expression or
268 // declaration in another case, keep the integral constant.
269 // If both are integral constants with the same value, keep that value.
273 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
274 return X.wasDeducedFromArrayBound() ? Y : X;
275
276 // All other combinations are incompatible.
278
280 // If we deduced a value and a dependent expression, keep the value.
283 X.structurallyEquals(Y)))
284 return X;
285
286 // All other combinations are incompatible.
288
291 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
292 return X;
293
294 // All other combinations are incompatible.
296
299 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
301 return X;
302
303 // All other combinations are incompatible.
305
308 return checkDeducedTemplateArguments(Context, Y, X);
309
310 // Compare the expressions for equality
311 llvm::FoldingSetNodeID ID1, ID2;
312 X.getAsExpr()->Profile(ID1, Context, true);
313 Y.getAsExpr()->Profile(ID2, Context, true);
314 if (ID1 == ID2)
315 return X.wasDeducedFromArrayBound() ? Y : X;
316
317 // Differing dependent expressions are incompatible.
319 }
320
322 assert(!X.wasDeducedFromArrayBound());
323
324 // If we deduced a declaration and a dependent expression, keep the
325 // declaration.
327 return X;
328
329 // If we deduced a declaration and an integral constant, keep the
330 // integral constant and whichever type did not come from an array
331 // bound.
334 return TemplateArgument(Context, Y.getAsIntegral(),
335 X.getParamTypeForDecl());
336 return Y;
337 }
338
339 // If we deduced two declarations, make sure that they refer to the
340 // same declaration.
342 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
343 return X;
344
345 // All other combinations are incompatible.
347
349 // If we deduced a null pointer and a dependent expression, keep the
350 // null pointer.
353 X.getNullPtrType(), Y.getAsExpr()->getType()),
354 true);
355
356 // If we deduced a null pointer and an integral constant, keep the
357 // integral constant.
359 return Y;
360
361 // If we deduced two null pointers, they are the same.
363 return TemplateArgument(
364 Context.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
365 true);
366
367 // All other combinations are incompatible.
369
371 if (Y.getKind() != TemplateArgument::Pack ||
372 (!AggregateCandidateDeduction && X.pack_size() != Y.pack_size()))
374
377 XA = X.pack_begin(),
378 XAEnd = X.pack_end(), YA = Y.pack_begin(), YAEnd = Y.pack_end();
379 XA != XAEnd; ++XA) {
380 if (YA != YAEnd) {
382 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
384 if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
386 NewPack.push_back(Merged);
387 ++YA;
388 } else {
389 NewPack.push_back(*XA);
390 }
391 }
392
394 TemplateArgument::CreatePackCopy(Context, NewPack),
395 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
396 }
397 }
398
399 llvm_unreachable("Invalid TemplateArgument Kind!");
400}
401
402/// Deduce the value of the given non-type template parameter
403/// as the given deduced template argument. All non-type template parameter
404/// deduction is funneled through here.
407 const NonTypeTemplateParmDecl *NTTP,
408 const DeducedTemplateArgument &NewDeduced,
409 QualType ValueType, TemplateDeductionInfo &Info,
410 bool PartialOrdering,
412 bool *HasDeducedAnyParam) {
413 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
414 "deducing non-type template argument with wrong depth");
415
417 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
418 if (Result.isNull()) {
419 Info.Param = const_cast<NonTypeTemplateParmDecl*>(NTTP);
420 Info.FirstArg = Deduced[NTTP->getIndex()];
421 Info.SecondArg = NewDeduced;
422 return TemplateDeductionResult::Inconsistent;
423 }
424
425 Deduced[NTTP->getIndex()] = Result;
426 if (!S.getLangOpts().CPlusPlus17)
427 return TemplateDeductionResult::Success;
428
429 if (NTTP->isExpandedParameterPack())
430 // FIXME: We may still need to deduce parts of the type here! But we
431 // don't have any way to find which slice of the type to use, and the
432 // type stored on the NTTP itself is nonsense. Perhaps the type of an
433 // expanded NTTP should be a pack expansion type?
434 return TemplateDeductionResult::Success;
435
436 // Get the type of the parameter for deduction. If it's a (dependent) array
437 // or function type, we will not have decayed it yet, so do that now.
438 QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
439 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
440 ParamType = Expansion->getPattern();
441
442 // FIXME: It's not clear how deduction of a parameter of reference
443 // type from an argument (of non-reference type) should be performed.
444 // For now, we just make the argument have same reference type as the
445 // parameter.
446 if (ParamType->isReferenceType() && !ValueType->isReferenceType()) {
447 if (ParamType->isRValueReferenceType())
448 ValueType = S.Context.getRValueReferenceType(ValueType);
449 else
450 ValueType = S.Context.getLValueReferenceType(ValueType);
451 }
452
454 S, TemplateParams, ParamType, ValueType, Info, Deduced,
458 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound(), HasDeducedAnyParam);
459}
460
461/// Deduce the value of the given non-type template parameter
462/// from the given integral constant.
464 Sema &S, TemplateParameterList *TemplateParams,
465 const NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
466 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
468 bool *HasDeducedAnyParam) {
470 S, TemplateParams, NTTP,
472 DeducedFromArrayBound),
473 ValueType, Info, PartialOrdering, Deduced, HasDeducedAnyParam);
474}
475
476/// Deduce the value of the given non-type template parameter
477/// from the given null pointer template argument type.
480 const NonTypeTemplateParmDecl *NTTP,
481 QualType NullPtrType, TemplateDeductionInfo &Info,
482 bool PartialOrdering,
484 bool *HasDeducedAnyParam) {
487 NTTP->getLocation()),
488 NullPtrType,
489 NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer
490 : CK_NullToPointer)
491 .get();
493 S, TemplateParams, NTTP, DeducedTemplateArgument(Value), Value->getType(),
494 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
495}
496
497/// Deduce the value of the given non-type template parameter
498/// from the given type- or value-dependent expression.
499///
500/// \returns true if deduction succeeded, false otherwise.
503 const NonTypeTemplateParmDecl *NTTP, Expr *Value,
506 bool *HasDeducedAnyParam) {
508 S, TemplateParams, NTTP, DeducedTemplateArgument(Value), Value->getType(),
509 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
510}
511
512/// Deduce the value of the given non-type template parameter
513/// from the given declaration.
514///
515/// \returns true if deduction succeeded, false otherwise.
518 const NonTypeTemplateParmDecl *NTTP, ValueDecl *D,
520 bool PartialOrdering,
522 bool *HasDeducedAnyParam) {
523 TemplateArgument New(D, T);
525 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info,
526 PartialOrdering, Deduced, HasDeducedAnyParam);
527}
528
530 Sema &S, TemplateParameterList *TemplateParams, TemplateName Param,
534 bool *HasDeducedAnyParam) {
535 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
536 if (!ParamDecl) {
537 // The parameter type is dependent and is not a template template parameter,
538 // so there is nothing that we can deduce.
539 return TemplateDeductionResult::Success;
540 }
541
542 if (auto *TempParam = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
543 // If we're not deducing at this depth, there's nothing to deduce.
544 if (TempParam->getDepth() != Info.getDeducedDepth())
545 return TemplateDeductionResult::Success;
546
547 ArrayRef<NamedDecl *> Params =
548 ParamDecl->getTemplateParameters()->asArray();
549 unsigned StartPos = 0;
550 for (unsigned I = 0, E = std::min(Params.size(), DefaultArguments.size());
551 I < E; ++I) {
552 if (Params[I]->isParameterPack()) {
553 StartPos = DefaultArguments.size();
554 break;
555 }
556 StartPos = I + 1;
557 }
558
559 // Provisional resolution for CWG2398: If Arg names a template
560 // specialization, then we deduce a synthesized template name
561 // based on A, but using the TS's extra arguments, relative to P, as
562 // defaults.
563 DeducedTemplateArgument NewDeduced =
566 Arg, {StartPos, DefaultArguments.drop_front(StartPos)}))
567 : Arg;
568
570 S.Context, Deduced[TempParam->getIndex()], NewDeduced);
571 if (Result.isNull()) {
572 Info.Param = TempParam;
573 Info.FirstArg = Deduced[TempParam->getIndex()];
574 Info.SecondArg = NewDeduced;
575 return TemplateDeductionResult::Inconsistent;
576 }
577
578 Deduced[TempParam->getIndex()] = Result;
579 if (HasDeducedAnyParam)
580 *HasDeducedAnyParam = true;
581 return TemplateDeductionResult::Success;
582 }
583
584 // Verify that the two template names are equivalent.
586 Param, Arg, /*IgnoreDeduced=*/DefaultArguments.size() != 0))
587 return TemplateDeductionResult::Success;
588
589 // Mismatch of non-dependent template parameter to argument.
590 Info.FirstArg = TemplateArgument(Param);
591 Info.SecondArg = TemplateArgument(Arg);
592 return TemplateDeductionResult::NonDeducedMismatch;
593}
594
595/// Deduce the template arguments by comparing the template parameter
596/// type (which is a template-id) with the template argument type.
597///
598/// \param S the Sema
599///
600/// \param TemplateParams the template parameters that we are deducing
601///
602/// \param P the parameter type
603///
604/// \param A the argument type
605///
606/// \param Info information about the template argument deduction itself
607///
608/// \param Deduced the deduced template arguments
609///
610/// \returns the result of template argument deduction so far. Note that a
611/// "success" result means that template argument deduction has not yet failed,
612/// but it may still fail, later, for other reasons.
613
615 for (const Type *T = QT.getTypePtr(); /**/; /**/) {
616 const TemplateSpecializationType *TST =
618 assert(TST && "Expected a TemplateSpecializationType");
619 if (!TST->isSugared())
620 return TST;
621 T = TST->desugar().getTypePtr();
622 }
623}
624
627 const QualType P, QualType A,
630 bool *HasDeducedAnyParam) {
631 QualType UP = P;
632 if (const auto *IP = P->getAs<InjectedClassNameType>())
633 UP = IP->getInjectedSpecializationType();
634
635 assert(isa<TemplateSpecializationType>(UP.getCanonicalType()));
637 TemplateName TNP = TP->getTemplateName();
638
639 // If the parameter is an alias template, there is nothing to deduce.
640 if (const auto *TD = TNP.getAsTemplateDecl(); TD && TD->isTypeAlias())
641 return TemplateDeductionResult::Success;
642
643 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
644 // arguments.
648 ->template_arguments();
649
650 QualType UA = A;
651 std::optional<NestedNameSpecifier *> NNS;
652 // Treat an injected-class-name as its underlying template-id.
653 if (const auto *Elaborated = A->getAs<ElaboratedType>()) {
654 NNS = Elaborated->getQualifier();
655 } else if (const auto *Injected = A->getAs<InjectedClassNameType>()) {
656 UA = Injected->getInjectedSpecializationType();
657 NNS = nullptr;
658 }
659
660 // Check whether the template argument is a dependent template-id.
661 if (isa<TemplateSpecializationType>(UA.getCanonicalType())) {
663 TemplateName TNA = SA->getTemplateName();
664
665 // If the argument is an alias template, there is nothing to deduce.
666 if (const auto *TD = TNA.getAsTemplateDecl(); TD && TD->isTypeAlias())
667 return TemplateDeductionResult::Success;
668
669 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
670 // arguments.
674 ->template_arguments();
675
676 // Perform template argument deduction for the template name.
677 if (auto Result = DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
678 /*DefaultArguments=*/AResolved,
679 PartialOrdering, Deduced,
680 HasDeducedAnyParam);
681 Result != TemplateDeductionResult::Success)
682 return Result;
683
684 // Perform template argument deduction on each template
685 // argument. Ignore any missing/extra arguments, since they could be
686 // filled in by default arguments.
688 S, TemplateParams, PResolved, AResolved, Info, Deduced,
689 /*NumberOfArgumentsMustMatch=*/false, PartialOrdering,
690 PackFold::ParameterToArgument, HasDeducedAnyParam);
691 }
692
693 // If the argument type is a class template specialization, we
694 // perform template argument deduction using its template
695 // arguments.
696 const auto *RA = UA->getAs<RecordType>();
697 const auto *SA =
698 RA ? dyn_cast<ClassTemplateSpecializationDecl>(RA->getDecl()) : nullptr;
699 if (!SA) {
701 Info.SecondArg = TemplateArgument(A);
702 return TemplateDeductionResult::NonDeducedMismatch;
703 }
704
705 TemplateName TNA = TemplateName(SA->getSpecializedTemplate());
706 if (NNS)
708 *NNS, false, TemplateName(SA->getSpecializedTemplate()));
709
710 // Perform template argument deduction for the template name.
711 if (auto Result = DeduceTemplateArguments(
712 S, TemplateParams, TNP, TNA, Info,
713 /*DefaultArguments=*/SA->getTemplateArgs().asArray(), PartialOrdering,
714 Deduced, HasDeducedAnyParam);
715 Result != TemplateDeductionResult::Success)
716 return Result;
717
718 // Perform template argument deduction for the template arguments.
719 return DeduceTemplateArguments(S, TemplateParams, PResolved,
720 SA->getTemplateArgs().asArray(), Info, Deduced,
721 /*NumberOfArgumentsMustMatch=*/true,
723 HasDeducedAnyParam);
724}
725
727 assert(T->isCanonicalUnqualified());
728
729 switch (T->getTypeClass()) {
730 case Type::TypeOfExpr:
731 case Type::TypeOf:
732 case Type::DependentName:
733 case Type::Decltype:
734 case Type::PackIndexing:
735 case Type::UnresolvedUsing:
736 case Type::TemplateTypeParm:
737 case Type::Auto:
738 return true;
739
740 case Type::ConstantArray:
741 case Type::IncompleteArray:
742 case Type::VariableArray:
743 case Type::DependentSizedArray:
745 cast<ArrayType>(T)->getElementType().getTypePtr());
746
747 default:
748 return false;
749 }
750}
751
752/// Determines whether the given type is an opaque type that
753/// might be more qualified when instantiated.
757}
758
759/// Helper function to build a TemplateParameter when we don't
760/// know its type statically.
762 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
763 return TemplateParameter(TTP);
764 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
765 return TemplateParameter(NTTP);
766
767 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
768}
769
770/// A pack that we're currently deducing.
772 // The index of the pack.
773 unsigned Index;
774
775 // The old value of the pack before we started deducing it.
777
778 // A deferred value of this pack from an inner deduction, that couldn't be
779 // deduced because this deduction hadn't happened yet.
781
782 // The new value of the pack.
784
785 // The outer deduction for this pack, if any.
786 DeducedPack *Outer = nullptr;
787
788 DeducedPack(unsigned Index) : Index(Index) {}
789};
790
791namespace {
792
793/// A scope in which we're performing pack deduction.
794class PackDeductionScope {
795public:
796 /// Prepare to deduce the packs named within Pattern.
797 /// \param FinishingDeduction Don't attempt to deduce the pack. Useful when
798 /// just checking a previous deduction of the pack.
799 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
802 bool DeducePackIfNotAlreadyDeduced = false,
803 bool FinishingDeduction = false)
804 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info),
805 DeducePackIfNotAlreadyDeduced(DeducePackIfNotAlreadyDeduced),
806 FinishingDeduction(FinishingDeduction) {
807 unsigned NumNamedPacks = addPacks(Pattern);
808 finishConstruction(NumNamedPacks);
809 }
810
811 /// Prepare to directly deduce arguments of the parameter with index \p Index.
812 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
814 TemplateDeductionInfo &Info, unsigned Index)
815 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
816 addPack(Index);
817 finishConstruction(1);
818 }
819
820private:
821 void addPack(unsigned Index) {
822 // Save the deduced template argument for the parameter pack expanded
823 // by this pack expansion, then clear out the deduction.
824 DeducedFromEarlierParameter = !Deduced[Index].isNull();
825 DeducedPack Pack(Index);
826 if (!FinishingDeduction) {
827 Pack.Saved = Deduced[Index];
828 Deduced[Index] = TemplateArgument();
829 }
830
831 // FIXME: What if we encounter multiple packs with different numbers of
832 // pre-expanded expansions? (This should already have been diagnosed
833 // during substitution.)
834 if (std::optional<unsigned> ExpandedPackExpansions =
835 getExpandedPackSize(TemplateParams->getParam(Index)))
836 FixedNumExpansions = ExpandedPackExpansions;
837
838 Packs.push_back(Pack);
839 }
840
841 unsigned addPacks(TemplateArgument Pattern) {
842 // Compute the set of template parameter indices that correspond to
843 // parameter packs expanded by the pack expansion.
844 llvm::SmallBitVector SawIndices(TemplateParams->size());
846
847 auto AddPack = [&](unsigned Index) {
848 if (SawIndices[Index])
849 return;
850 SawIndices[Index] = true;
851 addPack(Index);
852
853 // Deducing a parameter pack that is a pack expansion also constrains the
854 // packs appearing in that parameter to have the same deduced arity. Also,
855 // in C++17 onwards, deducing a non-type template parameter deduces its
856 // type, so we need to collect the pending deduced values for those packs.
857 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
858 TemplateParams->getParam(Index))) {
859 if (!NTTP->isExpandedParameterPack())
860 // FIXME: CWG2982 suggests a type-constraint forms a non-deduced
861 // context, however it is not yet resolved.
862 if (auto *Expansion = dyn_cast<PackExpansionType>(
863 S.Context.getUnconstrainedType(NTTP->getType())))
864 ExtraDeductions.push_back(Expansion->getPattern());
865 }
866 // FIXME: Also collect the unexpanded packs in any type and template
867 // parameter packs that are pack expansions.
868 };
869
870 auto Collect = [&](TemplateArgument Pattern) {
872 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
873 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
874 unsigned Depth, Index;
875 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
876 if (Depth == Info.getDeducedDepth())
877 AddPack(Index);
878 }
879 };
880
881 // Look for unexpanded packs in the pattern.
882 Collect(Pattern);
883 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
884
885 unsigned NumNamedPacks = Packs.size();
886
887 // Also look for unexpanded packs that are indirectly deduced by deducing
888 // the sizes of the packs in this pattern.
889 while (!ExtraDeductions.empty())
890 Collect(ExtraDeductions.pop_back_val());
891
892 return NumNamedPacks;
893 }
894
895 void finishConstruction(unsigned NumNamedPacks) {
896 // Dig out the partially-substituted pack, if there is one.
897 const TemplateArgument *PartialPackArgs = nullptr;
898 unsigned NumPartialPackArgs = 0;
899 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
900 if (auto *Scope = S.CurrentInstantiationScope)
901 if (auto *Partial = Scope->getPartiallySubstitutedPack(
902 &PartialPackArgs, &NumPartialPackArgs))
903 PartialPackDepthIndex = getDepthAndIndex(Partial);
904
905 // This pack expansion will have been partially or fully expanded if
906 // it only names explicitly-specified parameter packs (including the
907 // partially-substituted one, if any).
908 bool IsExpanded = true;
909 for (unsigned I = 0; I != NumNamedPacks; ++I) {
910 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
911 IsExpanded = false;
912 IsPartiallyExpanded = false;
913 break;
914 }
915 if (PartialPackDepthIndex ==
916 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
917 IsPartiallyExpanded = true;
918 }
919 }
920
921 // Skip over the pack elements that were expanded into separate arguments.
922 // If we partially expanded, this is the number of partial arguments.
923 // FIXME: `&& FixedNumExpansions` is a workaround for UB described in
924 // https://github.com/llvm/llvm-project/issues/100095
925 if (IsPartiallyExpanded)
926 PackElements += NumPartialPackArgs;
927 else if (IsExpanded && FixedNumExpansions)
928 PackElements += *FixedNumExpansions;
929
930 for (auto &Pack : Packs) {
931 if (Info.PendingDeducedPacks.size() > Pack.Index)
932 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
933 else
934 Info.PendingDeducedPacks.resize(Pack.Index + 1);
935 Info.PendingDeducedPacks[Pack.Index] = &Pack;
936
937 if (PartialPackDepthIndex ==
938 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
939 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
940 // We pre-populate the deduced value of the partially-substituted
941 // pack with the specified value. This is not entirely correct: the
942 // value is supposed to have been substituted, not deduced, but the
943 // cases where this is observable require an exact type match anyway.
944 //
945 // FIXME: If we could represent a "depth i, index j, pack elem k"
946 // parameter, we could substitute the partially-substituted pack
947 // everywhere and avoid this.
948 if (!FinishingDeduction && !IsPartiallyExpanded)
949 Deduced[Pack.Index] = Pack.New[PackElements];
950 }
951 }
952 }
953
954public:
955 ~PackDeductionScope() {
956 for (auto &Pack : Packs)
957 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
958 }
959
960 // Return the size of the saved packs if all of them has the same size.
961 std::optional<unsigned> getSavedPackSizeIfAllEqual() const {
962 unsigned PackSize = Packs[0].Saved.pack_size();
963
964 if (std::all_of(Packs.begin() + 1, Packs.end(), [&PackSize](const auto &P) {
965 return P.Saved.pack_size() == PackSize;
966 }))
967 return PackSize;
968 return {};
969 }
970
971 /// Determine whether this pack has already been deduced from a previous
972 /// argument.
973 bool isDeducedFromEarlierParameter() const {
974 return DeducedFromEarlierParameter;
975 }
976
977 /// Determine whether this pack has already been partially expanded into a
978 /// sequence of (prior) function parameters / template arguments.
979 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
980
981 /// Determine whether this pack expansion scope has a known, fixed arity.
982 /// This happens if it involves a pack from an outer template that has
983 /// (notionally) already been expanded.
984 bool hasFixedArity() { return FixedNumExpansions.has_value(); }
985
986 /// Determine whether the next element of the argument is still part of this
987 /// pack. This is the case unless the pack is already expanded to a fixed
988 /// length.
989 bool hasNextElement() {
990 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
991 }
992
993 /// Move to deducing the next element in each pack that is being deduced.
994 void nextPackElement() {
995 // Capture the deduced template arguments for each parameter pack expanded
996 // by this pack expansion, add them to the list of arguments we've deduced
997 // for that pack, then clear out the deduced argument.
998 if (!FinishingDeduction) {
999 for (auto &Pack : Packs) {
1000 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
1001 if (!Pack.New.empty() || !DeducedArg.isNull()) {
1002 while (Pack.New.size() < PackElements)
1003 Pack.New.push_back(DeducedTemplateArgument());
1004 if (Pack.New.size() == PackElements)
1005 Pack.New.push_back(DeducedArg);
1006 else
1007 Pack.New[PackElements] = DeducedArg;
1008 DeducedArg = Pack.New.size() > PackElements + 1
1009 ? Pack.New[PackElements + 1]
1011 }
1012 }
1013 }
1014 ++PackElements;
1015 }
1016
1017 /// Finish template argument deduction for a set of argument packs,
1018 /// producing the argument packs and checking for consistency with prior
1019 /// deductions.
1020 TemplateDeductionResult finish() {
1021 if (FinishingDeduction)
1022 return TemplateDeductionResult::Success;
1023 // Build argument packs for each of the parameter packs expanded by this
1024 // pack expansion.
1025 for (auto &Pack : Packs) {
1026 // Put back the old value for this pack.
1027 if (!FinishingDeduction)
1028 Deduced[Pack.Index] = Pack.Saved;
1029
1030 // Always make sure the size of this pack is correct, even if we didn't
1031 // deduce any values for it.
1032 //
1033 // FIXME: This isn't required by the normative wording, but substitution
1034 // and post-substitution checking will always fail if the arity of any
1035 // pack is not equal to the number of elements we processed. (Either that
1036 // or something else has gone *very* wrong.) We're permitted to skip any
1037 // hard errors from those follow-on steps by the intent (but not the
1038 // wording) of C++ [temp.inst]p8:
1039 //
1040 // If the function selected by overload resolution can be determined
1041 // without instantiating a class template definition, it is unspecified
1042 // whether that instantiation actually takes place
1043 Pack.New.resize(PackElements);
1044
1045 // Build or find a new value for this pack.
1047 if (Pack.New.empty()) {
1048 // If we deduced an empty argument pack, create it now.
1050 } else {
1051 TemplateArgument *ArgumentPack =
1052 new (S.Context) TemplateArgument[Pack.New.size()];
1053 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
1054 NewPack = DeducedTemplateArgument(
1055 TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())),
1056 // FIXME: This is wrong, it's possible that some pack elements are
1057 // deduced from an array bound and others are not:
1058 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
1059 // g({1, 2, 3}, {{}, {}});
1060 // ... should deduce T = {int, size_t (from array bound)}.
1061 Pack.New[0].wasDeducedFromArrayBound());
1062 }
1063
1064 // Pick where we're going to put the merged pack.
1066 if (Pack.Outer) {
1067 if (Pack.Outer->DeferredDeduction.isNull()) {
1068 // Defer checking this pack until we have a complete pack to compare
1069 // it against.
1070 Pack.Outer->DeferredDeduction = NewPack;
1071 continue;
1072 }
1073 Loc = &Pack.Outer->DeferredDeduction;
1074 } else {
1075 Loc = &Deduced[Pack.Index];
1076 }
1077
1078 // Check the new pack matches any previous value.
1079 DeducedTemplateArgument OldPack = *Loc;
1081 S.Context, OldPack, NewPack, DeducePackIfNotAlreadyDeduced);
1082
1083 Info.AggregateDeductionCandidateHasMismatchedArity =
1084 OldPack.getKind() == TemplateArgument::Pack &&
1085 NewPack.getKind() == TemplateArgument::Pack &&
1086 OldPack.pack_size() != NewPack.pack_size() && !Result.isNull();
1087
1088 // If we deferred a deduction of this pack, check that one now too.
1089 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
1090 OldPack = Result;
1091 NewPack = Pack.DeferredDeduction;
1092 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
1093 }
1094
1095 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
1096 if (Result.isNull()) {
1097 Info.Param = makeTemplateParameter(Param);
1098 Info.FirstArg = OldPack;
1099 Info.SecondArg = NewPack;
1100 return TemplateDeductionResult::Inconsistent;
1101 }
1102
1103 // If we have a pre-expanded pack and we didn't deduce enough elements
1104 // for it, fail deduction.
1105 if (std::optional<unsigned> Expansions = getExpandedPackSize(Param)) {
1106 if (*Expansions != PackElements) {
1107 Info.Param = makeTemplateParameter(Param);
1108 Info.FirstArg = Result;
1109 return TemplateDeductionResult::IncompletePack;
1110 }
1111 }
1112
1113 *Loc = Result;
1114 }
1115
1116 return TemplateDeductionResult::Success;
1117 }
1118
1119private:
1120 Sema &S;
1121 TemplateParameterList *TemplateParams;
1124 unsigned PackElements = 0;
1125 bool IsPartiallyExpanded = false;
1126 bool DeducePackIfNotAlreadyDeduced = false;
1127 bool DeducedFromEarlierParameter = false;
1128 bool FinishingDeduction = false;
1129 /// The number of expansions, if we have a fully-expanded pack in this scope.
1130 std::optional<unsigned> FixedNumExpansions;
1131
1133};
1134
1135} // namespace
1136
1137template <class T>
1139 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1142 bool FinishingDeduction, T &&DeductFunc) {
1143 // C++0x [temp.deduct.type]p10:
1144 // Similarly, if P has a form that contains (T), then each parameter type
1145 // Pi of the respective parameter-type- list of P is compared with the
1146 // corresponding parameter type Ai of the corresponding parameter-type-list
1147 // of A. [...]
1148 unsigned ArgIdx = 0, ParamIdx = 0;
1149 for (; ParamIdx != Params.size(); ++ParamIdx) {
1150 // Check argument types.
1151 const PackExpansionType *Expansion
1152 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1153 if (!Expansion) {
1154 // Simple case: compare the parameter and argument types at this point.
1155
1156 // Make sure we have an argument.
1157 if (ArgIdx >= Args.size())
1158 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1159
1160 if (isa<PackExpansionType>(Args[ArgIdx])) {
1161 // C++0x [temp.deduct.type]p22:
1162 // If the original function parameter associated with A is a function
1163 // parameter pack and the function parameter associated with P is not
1164 // a function parameter pack, then template argument deduction fails.
1165 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1166 }
1167
1168 if (TemplateDeductionResult Result =
1169 DeductFunc(S, TemplateParams, ParamIdx, ArgIdx,
1170 Params[ParamIdx].getUnqualifiedType(),
1171 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, POK);
1172 Result != TemplateDeductionResult::Success)
1173 return Result;
1174
1175 ++ArgIdx;
1176 continue;
1177 }
1178
1179 // C++0x [temp.deduct.type]p10:
1180 // If the parameter-declaration corresponding to Pi is a function
1181 // parameter pack, then the type of its declarator- id is compared with
1182 // each remaining parameter type in the parameter-type-list of A. Each
1183 // comparison deduces template arguments for subsequent positions in the
1184 // template parameter packs expanded by the function parameter pack.
1185
1186 QualType Pattern = Expansion->getPattern();
1187 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern,
1188 /*DeducePackIfNotAlreadyDeduced=*/false,
1189 FinishingDeduction);
1190
1191 // A pack scope with fixed arity is not really a pack any more, so is not
1192 // a non-deduced context.
1193 if (ParamIdx + 1 == Params.size() || PackScope.hasFixedArity()) {
1194 for (; ArgIdx < Args.size() && PackScope.hasNextElement(); ++ArgIdx) {
1195 // Deduce template arguments from the pattern.
1196 if (TemplateDeductionResult Result = DeductFunc(
1197 S, TemplateParams, ParamIdx, ArgIdx,
1198 Pattern.getUnqualifiedType(), Args[ArgIdx].getUnqualifiedType(),
1199 Info, Deduced, POK);
1200 Result != TemplateDeductionResult::Success)
1201 return Result;
1202 PackScope.nextPackElement();
1203 }
1204 } else {
1205 // C++0x [temp.deduct.type]p5:
1206 // The non-deduced contexts are:
1207 // - A function parameter pack that does not occur at the end of the
1208 // parameter-declaration-clause.
1209 //
1210 // FIXME: There is no wording to say what we should do in this case. We
1211 // choose to resolve this by applying the same rule that is applied for a
1212 // function call: that is, deduce all contained packs to their
1213 // explicitly-specified values (or to <> if there is no such value).
1214 //
1215 // This is seemingly-arbitrarily different from the case of a template-id
1216 // with a non-trailing pack-expansion in its arguments, which renders the
1217 // entire template-argument-list a non-deduced context.
1218
1219 // If the parameter type contains an explicitly-specified pack that we
1220 // could not expand, skip the number of parameters notionally created
1221 // by the expansion.
1222 std::optional<unsigned> NumExpansions = Expansion->getNumExpansions();
1223 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1224 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
1225 ++I, ++ArgIdx)
1226 PackScope.nextPackElement();
1227 }
1228 }
1229
1230 // Build argument packs for each of the parameter packs expanded by this
1231 // pack expansion.
1232 if (auto Result = PackScope.finish();
1233 Result != TemplateDeductionResult::Success)
1234 return Result;
1235 }
1236
1237 // DR692, DR1395
1238 // C++0x [temp.deduct.type]p10:
1239 // If the parameter-declaration corresponding to P_i ...
1240 // During partial ordering, if Ai was originally a function parameter pack:
1241 // - if P does not contain a function parameter type corresponding to Ai then
1242 // Ai is ignored;
1243 if (POK == PartialOrderingKind::Call && ArgIdx + 1 == Args.size() &&
1244 isa<PackExpansionType>(Args[ArgIdx]))
1245 return TemplateDeductionResult::Success;
1246
1247 // Make sure we don't have any extra arguments.
1248 if (ArgIdx < Args.size())
1249 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1250
1251 return TemplateDeductionResult::Success;
1252}
1253
1254/// Deduce the template arguments by comparing the list of parameter
1255/// types to the list of argument types, as in the parameter-type-lists of
1256/// function types (C++ [temp.deduct.type]p10).
1257///
1258/// \param S The semantic analysis object within which we are deducing
1259///
1260/// \param TemplateParams The template parameters that we are deducing
1261///
1262/// \param Params The list of parameter types
1263///
1264/// \param Args The list of argument types
1265///
1266/// \param Info information about the template argument deduction itself
1267///
1268/// \param Deduced the deduced template arguments
1269///
1270/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1271/// how template argument deduction is performed.
1272///
1273/// \param PartialOrdering If true, we are performing template argument
1274/// deduction for during partial ordering for a call
1275/// (C++0x [temp.deduct.partial]).
1276///
1277/// \param HasDeducedAnyParam If set, the object pointed at will indicate
1278/// whether any template parameter was deduced.
1279///
1280/// \param HasDeducedParam If set, the bit vector will be used to represent
1281/// which template parameters were deduced, in order.
1282///
1283/// \returns the result of template argument deduction so far. Note that a
1284/// "success" result means that template argument deduction has not yet failed,
1285/// but it may still fail, later, for other reasons.
1287 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1289 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1290 PartialOrderingKind POK, bool *HasDeducedAnyParam,
1291 llvm::SmallBitVector *HasDeducedParam) {
1292 return ::DeduceForEachType(
1293 S, TemplateParams, Params, Args, Info, Deduced, POK,
1294 /*FinishingDeduction=*/false,
1295 [&](Sema &S, TemplateParameterList *TemplateParams, int ParamIdx,
1296 int ArgIdx, QualType P, QualType A, TemplateDeductionInfo &Info,
1298 PartialOrderingKind POK) {
1299 bool HasDeducedAnyParamCopy = false;
1301 S, TemplateParams, P, A, Info, Deduced, TDF, POK,
1302 /*DeducedFromArrayBound=*/false, &HasDeducedAnyParamCopy);
1303 if (HasDeducedAnyParam && HasDeducedAnyParamCopy)
1304 *HasDeducedAnyParam = true;
1305 if (HasDeducedParam && HasDeducedAnyParamCopy)
1306 (*HasDeducedParam)[ParamIdx] = true;
1307 return TDR;
1308 });
1309}
1310
1311/// Determine whether the parameter has qualifiers that the argument
1312/// lacks. Put another way, determine whether there is no way to add
1313/// a deduced set of qualifiers to the ParamType that would result in
1314/// its qualifiers matching those of the ArgType.
1316 QualType ArgType) {
1317 Qualifiers ParamQs = ParamType.getQualifiers();
1318 Qualifiers ArgQs = ArgType.getQualifiers();
1319
1320 if (ParamQs == ArgQs)
1321 return false;
1322
1323 // Mismatched (but not missing) Objective-C GC attributes.
1324 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1325 ParamQs.hasObjCGCAttr())
1326 return true;
1327
1328 // Mismatched (but not missing) address spaces.
1329 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1330 ParamQs.hasAddressSpace())
1331 return true;
1332
1333 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1334 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1335 ParamQs.hasObjCLifetime())
1336 return true;
1337
1338 // CVR qualifiers inconsistent or a superset.
1339 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1340}
1341
1343 const FunctionType *PF = P->getAs<FunctionType>(),
1344 *AF = A->getAs<FunctionType>();
1345
1346 // Just compare if not functions.
1347 if (!PF || !AF)
1348 return Context.hasSameType(P, A);
1349
1350 // Noreturn and noexcept adjustment.
1351 if (QualType AdjustedParam; IsFunctionConversion(P, A, AdjustedParam))
1352 P = AdjustedParam;
1353
1354 // FIXME: Compatible calling conventions.
1356}
1357
1358/// Get the index of the first template parameter that was originally from the
1359/// innermost template-parameter-list. This is 0 except when we concatenate
1360/// the template parameter lists of a class template and a constructor template
1361/// when forming an implicit deduction guide.
1363 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1364 if (!Guide || !Guide->isImplicit())
1365 return 0;
1366 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1367}
1368
1369/// Determine whether a type denotes a forwarding reference.
1370static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1371 // C++1z [temp.deduct.call]p3:
1372 // A forwarding reference is an rvalue reference to a cv-unqualified
1373 // template parameter that does not represent a template parameter of a
1374 // class template.
1375 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1376 if (ParamRef->getPointeeType().getQualifiers())
1377 return false;
1378 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1379 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1380 }
1381 return false;
1382}
1383
1384/// Attempt to deduce the template arguments by checking the base types
1385/// according to (C++20 [temp.deduct.call] p4b3.
1386///
1387/// \param S the semantic analysis object within which we are deducing.
1388///
1389/// \param RD the top level record object we are deducing against.
1390///
1391/// \param TemplateParams the template parameters that we are deducing.
1392///
1393/// \param P the template specialization parameter type.
1394///
1395/// \param Info information about the template argument deduction itself.
1396///
1397/// \param Deduced the deduced template arguments.
1398///
1399/// \returns the result of template argument deduction with the bases. "invalid"
1400/// means no matches, "success" found a single item, and the
1401/// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
1404 TemplateParameterList *TemplateParams, QualType P,
1407 bool *HasDeducedAnyParam) {
1408 // C++14 [temp.deduct.call] p4b3:
1409 // If P is a class and P has the form simple-template-id, then the
1410 // transformed A can be a derived class of the deduced A. Likewise if
1411 // P is a pointer to a class of the form simple-template-id, the
1412 // transformed A can be a pointer to a derived class pointed to by the
1413 // deduced A. However, if there is a class C that is a (direct or
1414 // indirect) base class of D and derived (directly or indirectly) from a
1415 // class B and that would be a valid deduced A, the deduced A cannot be
1416 // B or pointer to B, respectively.
1417 //
1418 // These alternatives are considered only if type deduction would
1419 // otherwise fail. If they yield more than one possible deduced A, the
1420 // type deduction fails.
1421
1422 // Use a breadth-first search through the bases to collect the set of
1423 // successful matches. Visited contains the set of nodes we have already
1424 // visited, while ToVisit is our stack of records that we still need to
1425 // visit. Matches contains a list of matches that have yet to be
1426 // disqualified.
1429 // We iterate over this later, so we have to use MapVector to ensure
1430 // determinism.
1431 struct MatchValue {
1433 bool HasDeducedAnyParam;
1434 };
1435 llvm::MapVector<const CXXRecordDecl *, MatchValue> Matches;
1436
1437 auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
1438 for (const auto &Base : RD->bases()) {
1439 QualType T = Base.getType();
1440 assert(T->isRecordType() && "Base class that isn't a record?");
1441 if (Visited.insert(T->getAsCXXRecordDecl()).second)
1442 ToVisit.push_back(T);
1443 }
1444 };
1445
1446 // Set up the loop by adding all the bases.
1447 AddBases(RD);
1448
1449 // Search each path of bases until we either run into a successful match
1450 // (where all bases of it are invalid), or we run out of bases.
1451 while (!ToVisit.empty()) {
1452 QualType NextT = ToVisit.pop_back_val();
1453
1454 SmallVector<DeducedTemplateArgument, 8> DeducedCopy(Deduced.begin(),
1455 Deduced.end());
1457 bool HasDeducedAnyParamCopy = false;
1459 S, TemplateParams, P, NextT, BaseInfo, PartialOrdering, DeducedCopy,
1460 &HasDeducedAnyParamCopy);
1461
1462 // If this was a successful deduction, add it to the list of matches,
1463 // otherwise we need to continue searching its bases.
1464 const CXXRecordDecl *RD = NextT->getAsCXXRecordDecl();
1466 Matches.insert({RD, {DeducedCopy, HasDeducedAnyParamCopy}});
1467 else
1468 AddBases(RD);
1469 }
1470
1471 // At this point, 'Matches' contains a list of seemingly valid bases, however
1472 // in the event that we have more than 1 match, it is possible that the base
1473 // of one of the matches might be disqualified for being a base of another
1474 // valid match. We can count on cyclical instantiations being invalid to
1475 // simplify the disqualifications. That is, if A & B are both matches, and B
1476 // inherits from A (disqualifying A), we know that A cannot inherit from B.
1477 if (Matches.size() > 1) {
1478 Visited.clear();
1479 for (const auto &Match : Matches)
1480 AddBases(Match.first);
1481
1482 // We can give up once we have a single item (or have run out of things to
1483 // search) since cyclical inheritance isn't valid.
1484 while (Matches.size() > 1 && !ToVisit.empty()) {
1485 const CXXRecordDecl *RD = ToVisit.pop_back_val()->getAsCXXRecordDecl();
1486 Matches.erase(RD);
1487
1488 // Always add all bases, since the inheritance tree can contain
1489 // disqualifications for multiple matches.
1490 AddBases(RD);
1491 }
1492 }
1493
1494 if (Matches.empty())
1496 if (Matches.size() > 1)
1498
1499 std::swap(Matches.front().second.Deduced, Deduced);
1500 if (bool HasDeducedAnyParamCopy = Matches.front().second.HasDeducedAnyParam;
1501 HasDeducedAnyParamCopy && HasDeducedAnyParam)
1502 *HasDeducedAnyParam = HasDeducedAnyParamCopy;
1504}
1505
1506/// When propagating a partial ordering kind into a NonCall context,
1507/// this is used to downgrade a 'Call' into a 'NonCall', so that
1508/// the kind still reflects whether we are in a partial ordering context.
1511 return std::min(POK, PartialOrderingKind::NonCall);
1512}
1513
1514/// Deduce the template arguments by comparing the parameter type and
1515/// the argument type (C++ [temp.deduct.type]).
1516///
1517/// \param S the semantic analysis object within which we are deducing
1518///
1519/// \param TemplateParams the template parameters that we are deducing
1520///
1521/// \param P the parameter type
1522///
1523/// \param A the argument type
1524///
1525/// \param Info information about the template argument deduction itself
1526///
1527/// \param Deduced the deduced template arguments
1528///
1529/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1530/// how template argument deduction is performed.
1531///
1532/// \param PartialOrdering Whether we're performing template argument deduction
1533/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1534///
1535/// \returns the result of template argument deduction so far. Note that a
1536/// "success" result means that template argument deduction has not yet failed,
1537/// but it may still fail, later, for other reasons.
1539 Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
1541 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1542 PartialOrderingKind POK, bool DeducedFromArrayBound,
1543 bool *HasDeducedAnyParam) {
1544
1545 // If the argument type is a pack expansion, look at its pattern.
1546 // This isn't explicitly called out
1547 if (const auto *AExp = dyn_cast<PackExpansionType>(A))
1548 A = AExp->getPattern();
1549 assert(!isa<PackExpansionType>(A.getCanonicalType()));
1550
1551 if (POK == PartialOrderingKind::Call) {
1552 // C++11 [temp.deduct.partial]p5:
1553 // Before the partial ordering is done, certain transformations are
1554 // performed on the types used for partial ordering:
1555 // - If P is a reference type, P is replaced by the type referred to.
1556 const ReferenceType *PRef = P->getAs<ReferenceType>();
1557 if (PRef)
1558 P = PRef->getPointeeType();
1559
1560 // - If A is a reference type, A is replaced by the type referred to.
1561 const ReferenceType *ARef = A->getAs<ReferenceType>();
1562 if (ARef)
1563 A = A->getPointeeType();
1564
1565 if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
1566 // C++11 [temp.deduct.partial]p9:
1567 // If, for a given type, deduction succeeds in both directions (i.e.,
1568 // the types are identical after the transformations above) and both
1569 // P and A were reference types [...]:
1570 // - if [one type] was an lvalue reference and [the other type] was
1571 // not, [the other type] is not considered to be at least as
1572 // specialized as [the first type]
1573 // - if [one type] is more cv-qualified than [the other type],
1574 // [the other type] is not considered to be at least as specialized
1575 // as [the first type]
1576 // Objective-C ARC adds:
1577 // - [one type] has non-trivial lifetime, [the other type] has
1578 // __unsafe_unretained lifetime, and the types are otherwise
1579 // identical
1580 //
1581 // A is "considered to be at least as specialized" as P iff deduction
1582 // succeeds, so we model this as a deduction failure. Note that
1583 // [the first type] is P and [the other type] is A here; the standard
1584 // gets this backwards.
1585 Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
1586 if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
1587 PQuals.isStrictSupersetOf(AQuals) ||
1588 (PQuals.hasNonTrivialObjCLifetime() &&
1589 AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1590 PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
1591 Info.FirstArg = TemplateArgument(P);
1592 Info.SecondArg = TemplateArgument(A);
1594 }
1595 }
1596 Qualifiers DiscardedQuals;
1597 // C++11 [temp.deduct.partial]p7:
1598 // Remove any top-level cv-qualifiers:
1599 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1600 // version of P.
1601 P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
1602 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1603 // version of A.
1604 A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
1605 } else {
1606 // C++0x [temp.deduct.call]p4 bullet 1:
1607 // - If the original P is a reference type, the deduced A (i.e., the type
1608 // referred to by the reference) can be more cv-qualified than the
1609 // transformed A.
1610 if (TDF & TDF_ParamWithReferenceType) {
1611 Qualifiers Quals;
1612 QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
1614 P = S.Context.getQualifiedType(UnqualP, Quals);
1615 }
1616
1617 if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
1618 // C++0x [temp.deduct.type]p10:
1619 // If P and A are function types that originated from deduction when
1620 // taking the address of a function template (14.8.2.2) or when deducing
1621 // template arguments from a function declaration (14.8.2.6) and Pi and
1622 // Ai are parameters of the top-level parameter-type-list of P and A,
1623 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1624 // is an lvalue reference, in
1625 // which case the type of Pi is changed to be the template parameter
1626 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1627 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1628 // deduced as X&. - end note ]
1629 TDF &= ~TDF_TopLevelParameterTypeList;
1630 if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
1632 P = P->getPointeeType();
1633 }
1634 }
1635
1636 // C++ [temp.deduct.type]p9:
1637 // A template type argument T, a template template argument TT or a
1638 // template non-type argument i can be deduced if P and A have one of
1639 // the following forms:
1640 //
1641 // T
1642 // cv-list T
1643 if (const auto *TTP = P->getAs<TemplateTypeParmType>()) {
1644 // Just skip any attempts to deduce from a placeholder type or a parameter
1645 // at a different depth.
1646 if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
1648
1649 unsigned Index = TTP->getIndex();
1650
1651 // If the argument type is an array type, move the qualifiers up to the
1652 // top level, so they can be matched with the qualifiers on the parameter.
1653 if (A->isArrayType()) {
1654 Qualifiers Quals;
1655 A = S.Context.getUnqualifiedArrayType(A, Quals);
1656 if (Quals)
1657 A = S.Context.getQualifiedType(A, Quals);
1658 }
1659
1660 // The argument type can not be less qualified than the parameter
1661 // type.
1662 if (!(TDF & TDF_IgnoreQualifiers) &&
1664 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1665 Info.FirstArg = TemplateArgument(P);
1666 Info.SecondArg = TemplateArgument(A);
1668 }
1669
1670 // Do not match a function type with a cv-qualified type.
1671 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1672 if (A->isFunctionType() && P.hasQualifiers())
1674
1675 assert(TTP->getDepth() == Info.getDeducedDepth() &&
1676 "saw template type parameter with wrong depth");
1677 assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&
1678 "Unresolved overloaded function");
1680
1681 // Remove any qualifiers on the parameter from the deduced type.
1682 // We checked the qualifiers for consistency above.
1683 Qualifiers DeducedQs = DeducedType.getQualifiers();
1684 Qualifiers ParamQs = P.getQualifiers();
1685 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1686 if (ParamQs.hasObjCGCAttr())
1687 DeducedQs.removeObjCGCAttr();
1688 if (ParamQs.hasAddressSpace())
1689 DeducedQs.removeAddressSpace();
1690 if (ParamQs.hasObjCLifetime())
1691 DeducedQs.removeObjCLifetime();
1692
1693 // Objective-C ARC:
1694 // If template deduction would produce a lifetime qualifier on a type
1695 // that is not a lifetime type, template argument deduction fails.
1696 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1698 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1699 Info.FirstArg = TemplateArgument(P);
1700 Info.SecondArg = TemplateArgument(A);
1702 }
1703
1704 // Objective-C ARC:
1705 // If template deduction would produce an argument type with lifetime type
1706 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1707 if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
1708 !DeducedQs.hasObjCLifetime())
1710
1711 DeducedType =
1712 S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
1713
1714 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1716 checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
1717 if (Result.isNull()) {
1718 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1719 Info.FirstArg = Deduced[Index];
1720 Info.SecondArg = NewDeduced;
1722 }
1723
1724 Deduced[Index] = Result;
1725 if (HasDeducedAnyParam)
1726 *HasDeducedAnyParam = true;
1728 }
1729
1730 // Set up the template argument deduction information for a failure.
1731 Info.FirstArg = TemplateArgument(P);
1732 Info.SecondArg = TemplateArgument(A);
1733
1734 // If the parameter is an already-substituted template parameter
1735 // pack, do nothing: we don't know which of its arguments to look
1736 // at, so we have to wait until all of the parameter packs in this
1737 // expansion have arguments.
1738 if (P->getAs<SubstTemplateTypeParmPackType>())
1740
1741 // Check the cv-qualifiers on the parameter and argument types.
1742 if (!(TDF & TDF_IgnoreQualifiers)) {
1743 if (TDF & TDF_ParamWithReferenceType) {
1746 } else if (TDF & TDF_ArgWithReferenceType) {
1747 // C++ [temp.deduct.conv]p4:
1748 // If the original A is a reference type, A can be more cv-qualified
1749 // than the deduced A
1750 if (!A.getQualifiers().compatiblyIncludes(P.getQualifiers(),
1751 S.getASTContext()))
1753
1754 // Strip out all extra qualifiers from the argument to figure out the
1755 // type we're converting to, prior to the qualification conversion.
1756 Qualifiers Quals;
1757 A = S.Context.getUnqualifiedArrayType(A, Quals);
1758 A = S.Context.getQualifiedType(A, P.getQualifiers());
1759 } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
1760 if (P.getCVRQualifiers() != A.getCVRQualifiers())
1762 }
1763 }
1764
1765 // If the parameter type is not dependent, there is nothing to deduce.
1766 if (!P->isDependentType()) {
1767 if (TDF & TDF_SkipNonDependent)
1770 : S.Context.hasSameType(P, A))
1775 if (!(TDF & TDF_IgnoreQualifiers))
1777 // Otherwise, when ignoring qualifiers, the types not having the same
1778 // unqualified type does not mean they do not match, so in this case we
1779 // must keep going and analyze with a non-dependent parameter type.
1780 }
1781
1782 switch (P.getCanonicalType()->getTypeClass()) {
1783 // Non-canonical types cannot appear here.
1784#define NON_CANONICAL_TYPE(Class, Base) \
1785 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1786#define TYPE(Class, Base)
1787#include "clang/AST/TypeNodes.inc"
1788
1789 case Type::TemplateTypeParm:
1790 case Type::SubstTemplateTypeParmPack:
1791 llvm_unreachable("Type nodes handled above");
1792
1793 case Type::Auto:
1794 // C++23 [temp.deduct.funcaddr]/3:
1795 // A placeholder type in the return type of a function template is a
1796 // non-deduced context.
1797 // There's no corresponding wording for [temp.deduct.decl], but we treat
1798 // it the same to match other compilers.
1799 if (P->isDependentType())
1801 [[fallthrough]];
1802 case Type::Builtin:
1803 case Type::VariableArray:
1804 case Type::Vector:
1805 case Type::FunctionNoProto:
1806 case Type::Record:
1807 case Type::Enum:
1808 case Type::ObjCObject:
1809 case Type::ObjCInterface:
1810 case Type::ObjCObjectPointer:
1811 case Type::BitInt:
1812 return (TDF & TDF_SkipNonDependent) ||
1813 ((TDF & TDF_IgnoreQualifiers)
1815 : S.Context.hasSameType(P, A))
1818
1819 // _Complex T [placeholder extension]
1820 case Type::Complex: {
1821 const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
1822 if (!CA)
1825 S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
1826 Deduced, TDF, degradeCallPartialOrderingKind(POK),
1827 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1828 }
1829
1830 // _Atomic T [extension]
1831 case Type::Atomic: {
1832 const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
1833 if (!AA)
1836 S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
1837 Deduced, TDF, degradeCallPartialOrderingKind(POK),
1838 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1839 }
1840
1841 // T *
1842 case Type::Pointer: {
1843 QualType PointeeType;
1844 if (const auto *PA = A->getAs<PointerType>()) {
1845 PointeeType = PA->getPointeeType();
1846 } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
1847 PointeeType = PA->getPointeeType();
1848 } else {
1850 }
1852 S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
1853 PointeeType, Info, Deduced,
1856 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1857 }
1858
1859 // T &
1860 case Type::LValueReference: {
1861 const auto *RP = P->castAs<LValueReferenceType>(),
1862 *RA = A->getAs<LValueReferenceType>();
1863 if (!RA)
1865
1867 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1868 Deduced, 0, degradeCallPartialOrderingKind(POK),
1869 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1870 }
1871
1872 // T && [C++0x]
1873 case Type::RValueReference: {
1874 const auto *RP = P->castAs<RValueReferenceType>(),
1875 *RA = A->getAs<RValueReferenceType>();
1876 if (!RA)
1878
1880 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1881 Deduced, 0, degradeCallPartialOrderingKind(POK),
1882 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1883 }
1884
1885 // T [] (implied, but not stated explicitly)
1886 case Type::IncompleteArray: {
1887 const auto *IAA = S.Context.getAsIncompleteArrayType(A);
1888 if (!IAA)
1890
1891 const auto *IAP = S.Context.getAsIncompleteArrayType(P);
1892 assert(IAP && "Template parameter not of incomplete array type");
1893
1895 S, TemplateParams, IAP->getElementType(), IAA->getElementType(), Info,
1896 Deduced, TDF & TDF_IgnoreQualifiers,
1898 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1899 }
1900
1901 // T [integer-constant]
1902 case Type::ConstantArray: {
1903 const auto *CAA = S.Context.getAsConstantArrayType(A),
1905 assert(CAP);
1906 if (!CAA || CAA->getSize() != CAP->getSize())
1908
1910 S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
1911 Deduced, TDF & TDF_IgnoreQualifiers,
1913 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1914 }
1915
1916 // type [i]
1917 case Type::DependentSizedArray: {
1918 const auto *AA = S.Context.getAsArrayType(A);
1919 if (!AA)
1921
1922 // Check the element type of the arrays
1923 const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
1924 assert(DAP);
1926 S, TemplateParams, DAP->getElementType(), AA->getElementType(),
1927 Info, Deduced, TDF & TDF_IgnoreQualifiers,
1929 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1931 return Result;
1932
1933 // Determine the array bound is something we can deduce.
1934 const NonTypeTemplateParmDecl *NTTP =
1935 getDeducedParameterFromExpr(Info, DAP->getSizeExpr());
1936 if (!NTTP)
1938
1939 // We can perform template argument deduction for the given non-type
1940 // template parameter.
1941 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1942 "saw non-type template parameter with wrong depth");
1943 if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
1944 llvm::APSInt Size(CAA->getSize());
1946 S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
1947 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
1948 Deduced, HasDeducedAnyParam);
1949 }
1950 if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
1951 if (DAA->getSizeExpr())
1953 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info,
1954 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
1955
1956 // Incomplete type does not match a dependently-sized array type
1958 }
1959
1960 // type(*)(T)
1961 // T(*)()
1962 // T(*)(T)
1963 case Type::FunctionProto: {
1964 const auto *FPP = P->castAs<FunctionProtoType>(),
1965 *FPA = A->getAs<FunctionProtoType>();
1966 if (!FPA)
1968
1969 if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
1970 FPP->getRefQualifier() != FPA->getRefQualifier() ||
1971 FPP->isVariadic() != FPA->isVariadic())
1973
1974 // Check return types.
1976 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
1977 Info, Deduced, 0, degradeCallPartialOrderingKind(POK),
1978 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1980 return Result;
1981
1982 // Check parameter types.
1984 S, TemplateParams, FPP->param_types(), FPA->param_types(), Info,
1985 Deduced, TDF & TDF_TopLevelParameterTypeList, POK,
1986 HasDeducedAnyParam,
1987 /*HasDeducedParam=*/nullptr);
1989 return Result;
1990
1993
1994 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1995 // deducing through the noexcept-specifier if it's part of the canonical
1996 // type. libstdc++ relies on this.
1997 Expr *NoexceptExpr = FPP->getNoexceptExpr();
1998 if (const NonTypeTemplateParmDecl *NTTP =
1999 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
2000 : nullptr) {
2001 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
2002 "saw non-type template parameter with wrong depth");
2003
2004 llvm::APSInt Noexcept(1);
2005 switch (FPA->canThrow()) {
2006 case CT_Cannot:
2007 Noexcept = 1;
2008 [[fallthrough]];
2009
2010 case CT_Can:
2011 // We give E in noexcept(E) the "deduced from array bound" treatment.
2012 // FIXME: Should we?
2014 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
2015 /*DeducedFromArrayBound=*/true, Info,
2016 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2017
2018 case CT_Dependent:
2019 if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
2021 S, TemplateParams, NTTP, ArgNoexceptExpr, Info,
2022 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2023 // Can't deduce anything from throw(T...).
2024 break;
2025 }
2026 }
2027 // FIXME: Detect non-deduced exception specification mismatches?
2028 //
2029 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
2030 // top-level differences in noexcept-specifications.
2031
2033 }
2034
2035 case Type::InjectedClassName:
2036 // Treat a template's injected-class-name as if the template
2037 // specialization type had been used.
2038
2039 // template-name<T> (where template-name refers to a class template)
2040 // template-name<i>
2041 // TT<T>
2042 // TT<i>
2043 // TT<>
2044 case Type::TemplateSpecialization: {
2045 // When Arg cannot be a derived class, we can just try to deduce template
2046 // arguments from the template-id.
2047 if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
2048 return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
2049 POK != PartialOrderingKind::None,
2050 Deduced, HasDeducedAnyParam);
2051
2052 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
2053 Deduced.end());
2054
2056 S, TemplateParams, P, A, Info, POK != PartialOrderingKind::None,
2057 Deduced, HasDeducedAnyParam);
2059 return Result;
2060
2061 // We cannot inspect base classes as part of deduction when the type
2062 // is incomplete, so either instantiate any templates necessary to
2063 // complete the type, or skip over it if it cannot be completed.
2064 if (!S.isCompleteType(Info.getLocation(), A))
2065 return Result;
2066
2067 const CXXRecordDecl *RD = A->getAsCXXRecordDecl();
2068 if (RD->isInvalidDecl())
2069 return Result;
2070
2071 // Reset the incorrectly deduced argument from above.
2072 Deduced = DeducedOrig;
2073
2074 // Check bases according to C++14 [temp.deduct.call] p4b3:
2075 auto BaseResult = DeduceTemplateBases(S, RD, TemplateParams, P, Info,
2076 POK != PartialOrderingKind::None,
2077 Deduced, HasDeducedAnyParam);
2079 : Result;
2080 }
2081
2082 // T type::*
2083 // T T::*
2084 // T (type::*)()
2085 // type (T::*)()
2086 // type (type::*)(T)
2087 // type (T::*)(T)
2088 // T (type::*)(T)
2089 // T (T::*)()
2090 // T (T::*)(T)
2091 case Type::MemberPointer: {
2092 const auto *MPP = P->castAs<MemberPointerType>(),
2093 *MPA = A->getAs<MemberPointerType>();
2094 if (!MPA)
2096
2097 QualType PPT = MPP->getPointeeType();
2098 if (PPT->isFunctionType())
2099 S.adjustMemberFunctionCC(PPT, /*HasThisPointer=*/false,
2100 /*IsCtorOrDtor=*/false, Info.getLocation());
2101 QualType APT = MPA->getPointeeType();
2102 if (APT->isFunctionType())
2103 S.adjustMemberFunctionCC(APT, /*HasThisPointer=*/false,
2104 /*IsCtorOrDtor=*/false, Info.getLocation());
2105
2106 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
2108 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF,
2110 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2112 return Result;
2114 S, TemplateParams, QualType(MPP->getClass(), 0),
2115 QualType(MPA->getClass(), 0), Info, Deduced, SubTDF,
2117 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2118 }
2119
2120 // (clang extension)
2121 //
2122 // type(^)(T)
2123 // T(^)()
2124 // T(^)(T)
2125 case Type::BlockPointer: {
2126 const auto *BPP = P->castAs<BlockPointerType>(),
2127 *BPA = A->getAs<BlockPointerType>();
2128 if (!BPA)
2131 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
2132 Deduced, 0, degradeCallPartialOrderingKind(POK),
2133 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2134 }
2135
2136 // (clang extension)
2137 //
2138 // T __attribute__(((ext_vector_type(<integral constant>))))
2139 case Type::ExtVector: {
2140 const auto *VP = P->castAs<ExtVectorType>();
2141 QualType ElementType;
2142 if (const auto *VA = A->getAs<ExtVectorType>()) {
2143 // Make sure that the vectors have the same number of elements.
2144 if (VP->getNumElements() != VA->getNumElements())
2146 ElementType = VA->getElementType();
2147 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2148 // We can't check the number of elements, since the argument has a
2149 // dependent number of elements. This can only occur during partial
2150 // ordering.
2151 ElementType = VA->getElementType();
2152 } else {
2154 }
2155 // Perform deduction on the element types.
2157 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
2159 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2160 }
2161
2162 case Type::DependentVector: {
2163 const auto *VP = P->castAs<DependentVectorType>();
2164
2165 if (const auto *VA = A->getAs<VectorType>()) {
2166 // Perform deduction on the element types.
2168 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2169 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2170 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2172 return Result;
2173
2174 // Perform deduction on the vector size, if we can.
2175 const NonTypeTemplateParmDecl *NTTP =
2176 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2177 if (!NTTP)
2179
2180 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2181 ArgSize = VA->getNumElements();
2182 // Note that we use the "array bound" rules here; just like in that
2183 // case, we don't have any particular type for the vector size, but
2184 // we can provide one if necessary.
2186 S, TemplateParams, NTTP, ArgSize, S.Context.UnsignedIntTy, true,
2187 Info, POK != PartialOrderingKind::None, Deduced,
2188 HasDeducedAnyParam);
2189 }
2190
2191 if (const auto *VA = A->getAs<DependentVectorType>()) {
2192 // Perform deduction on the element types.
2194 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2195 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2196 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2198 return Result;
2199
2200 // Perform deduction on the vector size, if we can.
2201 const NonTypeTemplateParmDecl *NTTP =
2202 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2203 if (!NTTP)
2205
2207 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2208 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2209 }
2210
2212 }
2213
2214 // (clang extension)
2215 //
2216 // T __attribute__(((ext_vector_type(N))))
2217 case Type::DependentSizedExtVector: {
2218 const auto *VP = P->castAs<DependentSizedExtVectorType>();
2219
2220 if (const auto *VA = A->getAs<ExtVectorType>()) {
2221 // Perform deduction on the element types.
2223 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2224 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2225 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2227 return Result;
2228
2229 // Perform deduction on the vector size, if we can.
2230 const NonTypeTemplateParmDecl *NTTP =
2231 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2232 if (!NTTP)
2234
2235 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2236 ArgSize = VA->getNumElements();
2237 // Note that we use the "array bound" rules here; just like in that
2238 // case, we don't have any particular type for the vector size, but
2239 // we can provide one if necessary.
2241 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2242 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2243 }
2244
2245 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2246 // Perform deduction on the element types.
2248 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2249 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2250 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2252 return Result;
2253
2254 // Perform deduction on the vector size, if we can.
2255 const NonTypeTemplateParmDecl *NTTP =
2256 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2257 if (!NTTP)
2259
2261 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2262 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2263 }
2264
2266 }
2267
2268 // (clang extension)
2269 //
2270 // T __attribute__((matrix_type(<integral constant>,
2271 // <integral constant>)))
2272 case Type::ConstantMatrix: {
2273 const auto *MP = P->castAs<ConstantMatrixType>(),
2274 *MA = A->getAs<ConstantMatrixType>();
2275 if (!MA)
2277
2278 // Check that the dimensions are the same
2279 if (MP->getNumRows() != MA->getNumRows() ||
2280 MP->getNumColumns() != MA->getNumColumns()) {
2282 }
2283 // Perform deduction on element types.
2285 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2286 Deduced, TDF, degradeCallPartialOrderingKind(POK),
2287 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2288 }
2289
2290 case Type::DependentSizedMatrix: {
2291 const auto *MP = P->castAs<DependentSizedMatrixType>();
2292 const auto *MA = A->getAs<MatrixType>();
2293 if (!MA)
2295
2296 // Check the element type of the matrixes.
2298 S, TemplateParams, MP->getElementType(), MA->getElementType(),
2299 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2300 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2302 return Result;
2303
2304 // Try to deduce a matrix dimension.
2305 auto DeduceMatrixArg =
2306 [&S, &Info, &Deduced, &TemplateParams, &HasDeducedAnyParam, POK](
2307 Expr *ParamExpr, const MatrixType *A,
2308 unsigned (ConstantMatrixType::*GetArgDimension)() const,
2309 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2310 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2311 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
2312 if (!ParamExpr->isValueDependent()) {
2313 std::optional<llvm::APSInt> ParamConst =
2314 ParamExpr->getIntegerConstantExpr(S.Context);
2315 if (!ParamConst)
2317
2318 if (ACM) {
2319 if ((ACM->*GetArgDimension)() == *ParamConst)
2322 }
2323
2324 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2325 if (std::optional<llvm::APSInt> ArgConst =
2326 ArgExpr->getIntegerConstantExpr(S.Context))
2327 if (*ArgConst == *ParamConst)
2330 }
2331
2332 const NonTypeTemplateParmDecl *NTTP =
2333 getDeducedParameterFromExpr(Info, ParamExpr);
2334 if (!NTTP)
2336
2337 if (ACM) {
2338 llvm::APSInt ArgConst(
2340 ArgConst = (ACM->*GetArgDimension)();
2342 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
2343 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
2344 Deduced, HasDeducedAnyParam);
2345 }
2346
2348 S, TemplateParams, NTTP, (ADM->*GetArgDimensionExpr)(), Info,
2349 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2350 };
2351
2352 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
2356 return Result;
2357
2358 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2361 }
2362
2363 // (clang extension)
2364 //
2365 // T __attribute__(((address_space(N))))
2366 case Type::DependentAddressSpace: {
2367 const auto *ASP = P->castAs<DependentAddressSpaceType>();
2368
2369 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
2370 // Perform deduction on the pointer type.
2372 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2373 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2374 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2376 return Result;
2377
2378 // Perform deduction on the address space, if we can.
2379 const NonTypeTemplateParmDecl *NTTP =
2380 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2381 if (!NTTP)
2383
2385 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info,
2386 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2387 }
2388
2390 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2391 false);
2392 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
2393
2394 // Perform deduction on the pointer types.
2396 S, TemplateParams, ASP->getPointeeType(),
2397 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF,
2399 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2401 return Result;
2402
2403 // Perform deduction on the address space, if we can.
2404 const NonTypeTemplateParmDecl *NTTP =
2405 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2406 if (!NTTP)
2408
2410 S, TemplateParams, NTTP, ArgAddressSpace, S.Context.IntTy, true,
2411 Info, POK != PartialOrderingKind::None, Deduced,
2412 HasDeducedAnyParam);
2413 }
2414
2416 }
2417 case Type::DependentBitInt: {
2418 const auto *IP = P->castAs<DependentBitIntType>();
2419
2420 if (const auto *IA = A->getAs<BitIntType>()) {
2421 if (IP->isUnsigned() != IA->isUnsigned())
2423
2424 const NonTypeTemplateParmDecl *NTTP =
2425 getDeducedParameterFromExpr(Info, IP->getNumBitsExpr());
2426 if (!NTTP)
2428
2429 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2430 ArgSize = IA->getNumBits();
2431
2433 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2434 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2435 }
2436
2437 if (const auto *IA = A->getAs<DependentBitIntType>()) {
2438 if (IP->isUnsigned() != IA->isUnsigned())
2441 }
2442
2444 }
2445
2446 case Type::TypeOfExpr:
2447 case Type::TypeOf:
2448 case Type::DependentName:
2449 case Type::UnresolvedUsing:
2450 case Type::Decltype:
2451 case Type::UnaryTransform:
2452 case Type::DeducedTemplateSpecialization:
2453 case Type::DependentTemplateSpecialization:
2454 case Type::PackExpansion:
2455 case Type::Pipe:
2456 case Type::ArrayParameter:
2457 case Type::HLSLAttributedResource:
2458 // No template argument deduction for these types
2460
2461 case Type::PackIndexing: {
2462 const PackIndexingType *PIT = P->getAs<PackIndexingType>();
2463 if (PIT->hasSelectedType()) {
2465 S, TemplateParams, PIT->getSelectedType(), A, Info, Deduced, TDF,
2467 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2468 }
2470 }
2471 }
2472
2473 llvm_unreachable("Invalid Type Class!");
2474}
2475
2481 bool *HasDeducedAnyParam) {
2482 // If the template argument is a pack expansion, perform template argument
2483 // deduction against the pattern of that expansion. This only occurs during
2484 // partial ordering.
2485 if (A.isPackExpansion())
2487
2488 switch (P.getKind()) {
2490 llvm_unreachable("Null template argument in parameter list");
2491
2495 S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0,
2496 PartialOrdering ? PartialOrderingKind::NonCall
2497 : PartialOrderingKind::None,
2498 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2499 Info.FirstArg = P;
2500 Info.SecondArg = A;
2502
2504 // PartialOrdering does not matter here, since template specializations are
2505 // not being deduced.
2508 S, TemplateParams, P.getAsTemplate(), A.getAsTemplate(), Info,
2509 /*DefaultArguments=*/{}, /*PartialOrdering=*/false, Deduced,
2510 HasDeducedAnyParam);
2511 Info.FirstArg = P;
2512 Info.SecondArg = A;
2514
2516 llvm_unreachable("caller should handle pack expansions");
2517
2520 isSameDeclaration(P.getAsDecl(), A.getAsDecl()))
2522
2523 Info.FirstArg = P;
2524 Info.SecondArg = A;
2526
2529 S.Context.hasSameType(P.getNullPtrType(), A.getNullPtrType()))
2531
2532 Info.FirstArg = P;
2533 Info.SecondArg = A;
2535
2538 if (hasSameExtendedValue(P.getAsIntegral(), A.getAsIntegral()))
2540 }
2541 Info.FirstArg = P;
2542 Info.SecondArg = A;
2544
2549
2550 Info.FirstArg = P;
2551 Info.SecondArg = A;
2553
2555 if (const NonTypeTemplateParmDecl *NTTP =
2556 getDeducedParameterFromExpr(Info, P.getAsExpr())) {
2557 switch (A.getKind()) {
2562 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2564 HasDeducedAnyParam);
2565
2568 S, TemplateParams, NTTP, A.getNullPtrType(), Info, PartialOrdering,
2569 Deduced, HasDeducedAnyParam);
2570
2573 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
2574 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
2575
2581 Info.FirstArg = P;
2582 Info.SecondArg = A;
2584 }
2585 llvm_unreachable("Unknown template argument kind");
2586 }
2587
2588 // Can't deduce anything, but that's okay.
2591 llvm_unreachable("Argument packs should be expanded by the caller!");
2592 }
2593
2594 llvm_unreachable("Invalid TemplateArgument Kind!");
2595}
2596
2597/// Determine whether there is a template argument to be used for
2598/// deduction.
2599///
2600/// This routine "expands" argument packs in-place, overriding its input
2601/// parameters so that \c Args[ArgIdx] will be the available template argument.
2602///
2603/// \returns true if there is another template argument (which will be at
2604/// \c Args[ArgIdx]), false otherwise.
2606 unsigned &ArgIdx) {
2607 if (ArgIdx == Args.size())
2608 return false;
2609
2610 const TemplateArgument &Arg = Args[ArgIdx];
2611 if (Arg.getKind() != TemplateArgument::Pack)
2612 return true;
2613
2614 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2615 Args = Arg.pack_elements();
2616 ArgIdx = 0;
2617 return ArgIdx < Args.size();
2618}
2619
2620/// Determine whether the given set of template arguments has a pack
2621/// expansion that is not the last template argument.
2623 bool FoundPackExpansion = false;
2624 for (const auto &A : Args) {
2625 if (FoundPackExpansion)
2626 return true;
2627
2628 if (A.getKind() == TemplateArgument::Pack)
2629 return hasPackExpansionBeforeEnd(A.pack_elements());
2630
2631 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2632 // templates, it should not be treated as a pack expansion.
2633 if (A.isPackExpansion())
2634 FoundPackExpansion = true;
2635 }
2636
2637 return false;
2638}
2639
2646 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
2647 PackFold PackFold, bool *HasDeducedAnyParam) {
2648 if (PackFold == PackFold::ArgumentToParameter)
2649 std::swap(Ps, As);
2650 // C++0x [temp.deduct.type]p9:
2651 // If the template argument list of P contains a pack expansion that is not
2652 // the last template argument, the entire template argument list is a
2653 // non-deduced context.
2656
2657 // C++0x [temp.deduct.type]p9:
2658 // If P has a form that contains <T> or <i>, then each argument Pi of the
2659 // respective template argument list P is compared with the corresponding
2660 // argument Ai of the corresponding template argument list of A.
2661 unsigned ArgIdx = 0, ParamIdx = 0;
2663 const TemplateArgument &P = Ps[ParamIdx];
2664 if (!P.isPackExpansion()) {
2665 // The simple case: deduce template arguments by matching Pi and Ai.
2666
2667 // Check whether we have enough arguments.
2668 if (!hasTemplateArgumentForDeduction(As, ArgIdx))
2669 return NumberOfArgumentsMustMatch
2672
2673 // C++1z [temp.deduct.type]p9:
2674 // During partial ordering, if Ai was originally a pack expansion [and]
2675 // Pi is not a pack expansion, template argument deduction fails.
2676 if (As[ArgIdx].isPackExpansion())
2678
2679 // Perform deduction for this Pi/Ai pair.
2680 TemplateArgument Pi = P, Ai = As[ArgIdx];
2681 if (PackFold == PackFold::ArgumentToParameter)
2682 std::swap(Pi, Ai);
2683 if (auto Result = DeduceTemplateArguments(S, TemplateParams, Pi, Ai, Info,
2684 PartialOrdering, Deduced,
2685 HasDeducedAnyParam);
2687 return Result;
2688
2689 // Move to the next argument.
2690 ++ArgIdx;
2691 continue;
2692 }
2693
2694 // The parameter is a pack expansion.
2695
2696 // C++0x [temp.deduct.type]p9:
2697 // If Pi is a pack expansion, then the pattern of Pi is compared with
2698 // each remaining argument in the template argument list of A. Each
2699 // comparison deduces template arguments for subsequent positions in the
2700 // template parameter packs expanded by Pi.
2701 TemplateArgument Pattern = P.getPackExpansionPattern();
2702
2703 // Prepare to deduce the packs within the pattern.
2704 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2705
2706 // Keep track of the deduced template arguments for each parameter pack
2707 // expanded by this pack expansion (the outer index) and for each
2708 // template argument (the inner SmallVectors).
2709 for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
2710 PackScope.hasNextElement();
2711 ++ArgIdx) {
2712 TemplateArgument Pi = Pattern, Ai = As[ArgIdx];
2713 if (PackFold == PackFold::ArgumentToParameter)
2714 std::swap(Pi, Ai);
2715 // Deduce template arguments from the pattern.
2716 if (auto Result = DeduceTemplateArguments(S, TemplateParams, Pi, Ai, Info,
2717 PartialOrdering, Deduced,
2718 HasDeducedAnyParam);
2720 return Result;
2721
2722 PackScope.nextPackElement();
2723 }
2724
2725 // Build argument packs for each of the parameter packs expanded by this
2726 // pack expansion.
2727 if (auto Result = PackScope.finish();
2729 return Result;
2730 }
2731
2733}
2734
2739 bool NumberOfArgumentsMustMatch) {
2740 return ::DeduceTemplateArguments(
2741 *this, TemplateParams, Ps, As, Info, Deduced, NumberOfArgumentsMustMatch,
2742 /*PartialOrdering=*/false, PackFold::ParameterToArgument,
2743 /*HasDeducedAnyParam=*/nullptr);
2744}
2745
2746/// Determine whether two template arguments are the same.
2747static bool isSameTemplateArg(ASTContext &Context,
2749 const TemplateArgument &Y,
2750 bool PartialOrdering,
2751 bool PackExpansionMatchesPack = false) {
2752 // If we're checking deduced arguments (X) against original arguments (Y),
2753 // we will have flattened packs to non-expansions in X.
2754 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2755 X = X.getPackExpansionPattern();
2756
2757 if (X.getKind() != Y.getKind())
2758 return false;
2759
2760 switch (X.getKind()) {
2762 llvm_unreachable("Comparing NULL template argument");
2763
2765 return Context.getCanonicalType(X.getAsType()) ==
2766 Context.getCanonicalType(Y.getAsType());
2767
2769 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
2770
2772 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2773
2776 return Context.getCanonicalTemplateName(
2777 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2780
2782 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2783
2785 return X.structurallyEquals(Y);
2786
2788 llvm::FoldingSetNodeID XID, YID;
2789 X.getAsExpr()->Profile(XID, Context, true);
2790 Y.getAsExpr()->Profile(YID, Context, true);
2791 return XID == YID;
2792 }
2793
2795 unsigned PackIterationSize = X.pack_size();
2796 if (X.pack_size() != Y.pack_size()) {
2797 if (!PartialOrdering)
2798 return false;
2799
2800 // C++0x [temp.deduct.type]p9:
2801 // During partial ordering, if Ai was originally a pack expansion:
2802 // - if P does not contain a template argument corresponding to Ai
2803 // then Ai is ignored;
2804 bool XHasMoreArg = X.pack_size() > Y.pack_size();
2805 if (!(XHasMoreArg && X.pack_elements().back().isPackExpansion()) &&
2806 !(!XHasMoreArg && Y.pack_elements().back().isPackExpansion()))
2807 return false;
2808
2809 if (XHasMoreArg)
2810 PackIterationSize = Y.pack_size();
2811 }
2812
2813 ArrayRef<TemplateArgument> XP = X.pack_elements();
2815 for (unsigned i = 0; i < PackIterationSize; ++i)
2816 if (!isSameTemplateArg(Context, XP[i], YP[i], PartialOrdering,
2817 PackExpansionMatchesPack))
2818 return false;
2819 return true;
2820 }
2821 }
2822
2823 llvm_unreachable("Invalid TemplateArgument Kind!");
2824}
2825
2828 QualType NTTPType, SourceLocation Loc,
2830 switch (Arg.getKind()) {
2832 llvm_unreachable("Can't get a NULL template argument here");
2833
2835 return TemplateArgumentLoc(
2837
2839 if (NTTPType.isNull())
2840 NTTPType = Arg.getParamTypeForDecl();
2843 .getAs<Expr>();
2845 }
2846
2848 if (NTTPType.isNull())
2849 NTTPType = Arg.getNullPtrType();
2851 .getAs<Expr>();
2852 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2853 E);
2854 }
2855
2860 }
2861
2867 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2868 else if (QualifiedTemplateName *QTN =
2869 Template.getAsQualifiedTemplateName())
2870 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2871
2873 return TemplateArgumentLoc(Context, Arg,
2874 Builder.getWithLocInContext(Context), Loc);
2875
2876 return TemplateArgumentLoc(
2877 Context, Arg, Builder.getWithLocInContext(Context), Loc, Loc);
2878 }
2879
2881 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2882
2885 }
2886
2887 llvm_unreachable("Invalid TemplateArgument Kind!");
2888}
2889
2892 SourceLocation Location) {
2894 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2895}
2896
2897/// Convert the given deduced template argument and add it to the set of
2898/// fully-converted template arguments.
2900 Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template,
2901 TemplateDeductionInfo &Info, bool IsDeduced,
2902 SmallVectorImpl<TemplateArgument> &SugaredOutput,
2903 SmallVectorImpl<TemplateArgument> &CanonicalOutput) {
2904 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2905 unsigned ArgumentPackIndex) {
2906 // Convert the deduced template argument into a template
2907 // argument that we can check, almost as if the user had written
2908 // the template argument explicitly.
2910 Arg, QualType(), Info.getLocation(), Param);
2911
2912 // Check the template argument, converting it as necessary.
2913 return S.CheckTemplateArgument(
2914 Param, ArgLoc, Template, Template->getLocation(),
2915 Template->getSourceRange().getEnd(), ArgumentPackIndex, SugaredOutput,
2916 CanonicalOutput,
2917 IsDeduced
2921 };
2922
2923 if (Arg.getKind() == TemplateArgument::Pack) {
2924 // This is a template argument pack, so check each of its arguments against
2925 // the template parameter.
2926 SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
2927 CanonicalPackedArgsBuilder;
2928 for (const auto &P : Arg.pack_elements()) {
2929 // When converting the deduced template argument, append it to the
2930 // general output list. We need to do this so that the template argument
2931 // checking logic has all of the prior template arguments available.
2932 DeducedTemplateArgument InnerArg(P);
2934 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2935 "deduced nested pack");
2936 if (P.isNull()) {
2937 // We deduced arguments for some elements of this pack, but not for
2938 // all of them. This happens if we get a conditionally-non-deduced
2939 // context in a pack expansion (such as an overload set in one of the
2940 // arguments).
2941 S.Diag(Param->getLocation(),
2942 diag::err_template_arg_deduced_incomplete_pack)
2943 << Arg << Param;
2944 return true;
2945 }
2946 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
2947 return true;
2948
2949 // Move the converted template argument into our argument pack.
2950 SugaredPackedArgsBuilder.push_back(SugaredOutput.pop_back_val());
2951 CanonicalPackedArgsBuilder.push_back(CanonicalOutput.pop_back_val());
2952 }
2953
2954 // If the pack is empty, we still need to substitute into the parameter
2955 // itself, in case that substitution fails.
2956 if (SugaredPackedArgsBuilder.empty()) {
2958 MultiLevelTemplateArgumentList Args(Template, SugaredOutput,
2959 /*Final=*/true);
2960
2961 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2962 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2963 NTTP, SugaredOutput,
2964 Template->getSourceRange());
2965 if (Inst.isInvalid() ||
2966 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2967 NTTP->getDeclName()).isNull())
2968 return true;
2969 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2970 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2971 TTP, SugaredOutput,
2972 Template->getSourceRange());
2973 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2974 return true;
2975 }
2976 // For type parameters, no substitution is ever required.
2977 }
2978
2979 // Create the resulting argument pack.
2980 SugaredOutput.push_back(
2981 TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
2982 CanonicalOutput.push_back(TemplateArgument::CreatePackCopy(
2983 S.Context, CanonicalPackedArgsBuilder));
2984 return false;
2985 }
2986
2987 return ConvertArg(Arg, 0);
2988}
2989
2990// FIXME: This should not be a template, but
2991// ClassTemplatePartialSpecializationDecl sadly does not derive from
2992// TemplateDecl.
2993/// \param IsIncomplete When used, we only consider template parameters that
2994/// were deduced, disregarding any default arguments. After the function
2995/// finishes, the object pointed at will contain a value indicating if the
2996/// conversion was actually incomplete.
2997template <typename TemplateDeclT>
2999 Sema &S, TemplateDeclT *Template, bool IsDeduced,
3002 SmallVectorImpl<TemplateArgument> &SugaredBuilder,
3003 SmallVectorImpl<TemplateArgument> &CanonicalBuilder,
3004 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
3005 unsigned NumAlreadyConverted = 0, bool *IsIncomplete = nullptr) {
3006 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3007
3008 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3009 NamedDecl *Param = TemplateParams->getParam(I);
3010
3011 // C++0x [temp.arg.explicit]p3:
3012 // A trailing template parameter pack (14.5.3) not otherwise deduced will
3013 // be deduced to an empty sequence of template arguments.
3014 // FIXME: Where did the word "trailing" come from?
3015 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
3016 if (auto Result =
3017 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish();
3019 return Result;
3020 }
3021
3022 if (!Deduced[I].isNull()) {
3023 if (I < NumAlreadyConverted) {
3024 // We may have had explicitly-specified template arguments for a
3025 // template parameter pack (that may or may not have been extended
3026 // via additional deduced arguments).
3027 if (Param->isParameterPack() && CurrentInstantiationScope &&
3028 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
3029 // Forget the partially-substituted pack; its substitution is now
3030 // complete.
3031 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
3032 // We still need to check the argument in case it was extended by
3033 // deduction.
3034 } else {
3035 // We have already fully type-checked and converted this
3036 // argument, because it was explicitly-specified. Just record the
3037 // presence of this argument.
3038 SugaredBuilder.push_back(Deduced[I]);
3039 CanonicalBuilder.push_back(
3041 continue;
3042 }
3043 }
3044
3045 // We may have deduced this argument, so it still needs to be
3046 // checked and converted.
3047 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
3048 IsDeduced, SugaredBuilder,
3049 CanonicalBuilder)) {
3050 Info.Param = makeTemplateParameter(Param);
3051 // FIXME: These template arguments are temporary. Free them!
3052 Info.reset(
3053 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3054 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3056 }
3057
3058 continue;
3059 }
3060
3061 // [C++26][temp.deduct.partial]p12 - When partial ordering, it's ok for
3062 // template parameters to remain not deduced. As a provisional fix for a
3063 // core issue that does not exist yet, which may be related to CWG2160, only
3064 // consider template parameters that were deduced, disregarding any default
3065 // arguments.
3066 if (IsIncomplete) {
3067 *IsIncomplete = true;
3068 SugaredBuilder.push_back({});
3069 CanonicalBuilder.push_back({});
3070 continue;
3071 }
3072
3073 // Substitute into the default template argument, if available.
3074 bool HasDefaultArg = false;
3075 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
3076 if (!TD) {
3077 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
3078 isa<VarTemplatePartialSpecializationDecl>(Template));
3080 }
3081
3082 TemplateArgumentLoc DefArg;
3083 {
3084 Qualifiers ThisTypeQuals;
3085 CXXRecordDecl *ThisContext = nullptr;
3086 if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
3087 if (Rec->isLambda())
3088 if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
3089 ThisContext = Method->getParent();
3090 ThisTypeQuals = Method->getMethodQualifiers();
3091 }
3092
3093 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
3094 S.getLangOpts().CPlusPlus17);
3095
3097 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param,
3098 SugaredBuilder, CanonicalBuilder, HasDefaultArg);
3099 }
3100
3101 // If there was no default argument, deduction is incomplete.
3102 if (DefArg.getArgument().isNull()) {
3104 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
3105 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3106 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3107
3110 }
3111
3112 // Check whether we can actually use the default argument.
3114 Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
3115 0, SugaredBuilder, CanonicalBuilder, Sema::CTAK_Specified)) {
3117 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
3118 // FIXME: These template arguments are temporary. Free them!
3119 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3120 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3122 }
3123
3124 // If we get here, we successfully used the default template argument.
3125 }
3126
3128}
3129
3131 if (auto *DC = dyn_cast<DeclContext>(D))
3132 return DC;
3133 return D->getDeclContext();
3134}
3135
3136template<typename T> struct IsPartialSpecialization {
3137 static constexpr bool value = false;
3138};
3139template<>
3141 static constexpr bool value = true;
3142};
3143template<>
3145 static constexpr bool value = true;
3146};
3147template <typename TemplateDeclT>
3148static bool DeducedArgsNeedReplacement(TemplateDeclT *Template) {
3149 return false;
3150}
3151template <>
3154 return !Spec->isClassScopeExplicitSpecialization();
3155}
3156template <>
3159 return !Spec->isClassScopeExplicitSpecialization();
3160}
3161
3162template <typename TemplateDeclT>
3164CheckDeducedArgumentConstraints(Sema &S, TemplateDeclT *Template,
3165 ArrayRef<TemplateArgument> SugaredDeducedArgs,
3166 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
3167 TemplateDeductionInfo &Info) {
3168 llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
3169 Template->getAssociatedConstraints(AssociatedConstraints);
3170
3171 std::optional<ArrayRef<TemplateArgument>> Innermost;
3172 // If we don't need to replace the deduced template arguments,
3173 // we can add them immediately as the inner-most argument list.
3174 if (!DeducedArgsNeedReplacement(Template))
3175 Innermost = CanonicalDeducedArgs;
3176
3178 Template, Template->getDeclContext(), /*Final=*/false, Innermost,
3179 /*RelativeToPrimary=*/true, /*Pattern=*/
3180 nullptr, /*ForConstraintInstantiation=*/true);
3181
3182 // getTemplateInstantiationArgs picks up the non-deduced version of the
3183 // template args when this is a variable template partial specialization and
3184 // not class-scope explicit specialization, so replace with Deduced Args
3185 // instead of adding to inner-most.
3186 if (!Innermost)
3187 MLTAL.replaceInnermostTemplateArguments(Template, CanonicalDeducedArgs);
3188
3189 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
3190 Info.getLocation(),
3193 Info.reset(
3194 TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
3195 TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
3197 }
3199}
3200
3201/// Complete template argument deduction for a partial specialization.
3202template <typename T>
3203static std::enable_if_t<IsPartialSpecialization<T>::value,
3206 Sema &S, T *Partial, bool IsPartialOrdering,
3207 ArrayRef<TemplateArgument> TemplateArgs,
3209 TemplateDeductionInfo &Info) {
3210 // Unevaluated SFINAE context.
3213 Sema::SFINAETrap Trap(S);
3214
3215 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
3216
3217 // C++ [temp.deduct.type]p2:
3218 // [...] or if any template argument remains neither deduced nor
3219 // explicitly specified, template argument deduction fails.
3220 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3222 S, Partial, IsPartialOrdering, Deduced, Info, SugaredBuilder,
3223 CanonicalBuilder);
3225 return Result;
3226
3227 // Form the template argument list from the deduced template arguments.
3228 TemplateArgumentList *SugaredDeducedArgumentList =
3229 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
3230 TemplateArgumentList *CanonicalDeducedArgumentList =
3231 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
3232
3233 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3234
3235 // Substitute the deduced template arguments into the template
3236 // arguments of the class template partial specialization, and
3237 // verify that the instantiated template arguments are both valid
3238 // and are equivalent to the template arguments originally provided
3239 // to the class template.
3240 LocalInstantiationScope InstScope(S);
3241 auto *Template = Partial->getSpecializedTemplate();
3242 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
3243 Partial->getTemplateArgsAsWritten();
3244
3245 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
3246 PartialTemplArgInfo->RAngleLoc);
3247
3248 if (S.SubstTemplateArguments(PartialTemplArgInfo->arguments(),
3250 SugaredBuilder,
3251 /*Final=*/true),
3252 InstArgs)) {
3253 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
3254 if (ParamIdx >= Partial->getTemplateParameters()->size())
3255 ParamIdx = Partial->getTemplateParameters()->size() - 1;
3256
3257 Decl *Param = const_cast<NamedDecl *>(
3258 Partial->getTemplateParameters()->getParam(ParamIdx));
3259 Info.Param = makeTemplateParameter(Param);
3260 Info.FirstArg = (*PartialTemplArgInfo)[ArgIdx].getArgument();
3262 }
3263
3265 SmallVector<TemplateArgument, 4> SugaredConvertedInstArgs,
3266 CanonicalConvertedInstArgs;
3268 Template, Partial->getLocation(), InstArgs, /*DefaultArgs=*/{}, false,
3269 SugaredConvertedInstArgs, CanonicalConvertedInstArgs,
3270 /*UpdateArgsWithConversions=*/true, &ConstraintsNotSatisfied))
3274
3275 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3276 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3277 TemplateArgument InstArg = SugaredConvertedInstArgs.data()[I];
3278 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
3279 IsPartialOrdering)) {
3280 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3281 Info.FirstArg = TemplateArgs[I];
3282 Info.SecondArg = InstArg;
3284 }
3285 }
3286
3287 if (Trap.hasErrorOccurred())
3289
3290 if (!IsPartialOrdering) {
3292 S, Partial, SugaredBuilder, CanonicalBuilder, Info);
3294 return Result;
3295 }
3296
3298}
3299
3300/// Complete template argument deduction for a class or variable template,
3301/// when partial ordering against a partial specialization.
3302// FIXME: Factor out duplication with partial specialization version above.
3304 Sema &S, TemplateDecl *Template, bool PartialOrdering,
3305 ArrayRef<TemplateArgument> TemplateArgs,
3307 TemplateDeductionInfo &Info) {
3308 // Unevaluated SFINAE context.
3311 Sema::SFINAETrap Trap(S);
3312
3313 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
3314
3315 // C++ [temp.deduct.type]p2:
3316 // [...] or if any template argument remains neither deduced nor
3317 // explicitly specified, template argument deduction fails.
3318 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3320 S, Template, /*IsDeduced*/ PartialOrdering, Deduced, Info,
3321 SugaredBuilder, CanonicalBuilder,
3322 /*CurrentInstantiationScope=*/nullptr,
3323 /*NumAlreadyConverted=*/0U);
3325 return Result;
3326
3327 // Check that we produced the correct argument list.
3328 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3329 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3330 TemplateArgument InstArg = CanonicalBuilder[I];
3331 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg, PartialOrdering,
3332 /*PackExpansionMatchesPack=*/true)) {
3333 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3334 Info.FirstArg = TemplateArgs[I];
3335 Info.SecondArg = InstArg;
3337 }
3338 }
3339
3340 if (Trap.hasErrorOccurred())
3342
3343 if (!PartialOrdering) {
3345 S, Template, SugaredBuilder, CanonicalBuilder, Info);
3347 return Result;
3348 }
3349
3351}
3352
3353/// Complete template argument deduction for DeduceTemplateArgumentsFromType.
3354/// FIXME: this is mostly duplicated with the above two versions. Deduplicate
3355/// the three implementations.
3357 Sema &S, TemplateDecl *TD,
3359 TemplateDeductionInfo &Info) {
3360 // Unevaluated SFINAE context.
3363 Sema::SFINAETrap Trap(S);
3364
3366
3367 // C++ [temp.deduct.type]p2:
3368 // [...] or if any template argument remains neither deduced nor
3369 // explicitly specified, template argument deduction fails.
3370 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3372 S, TD, /*IsPartialOrdering=*/false, Deduced, Info, SugaredBuilder,
3373 CanonicalBuilder);
3375 return Result;
3376
3377 if (Trap.hasErrorOccurred())
3379
3380 if (auto Result = CheckDeducedArgumentConstraints(S, TD, SugaredBuilder,
3381 CanonicalBuilder, Info);
3383 return Result;
3384
3386}
3387
3388/// Perform template argument deduction to determine whether the given template
3389/// arguments match the given class or variable template partial specialization
3390/// per C++ [temp.class.spec.match].
3391template <typename T>
3392static std::enable_if_t<IsPartialSpecialization<T>::value,
3395 ArrayRef<TemplateArgument> TemplateArgs,
3396 TemplateDeductionInfo &Info) {
3397 if (Partial->isInvalidDecl())
3399
3400 // C++ [temp.class.spec.match]p2:
3401 // A partial specialization matches a given actual template
3402 // argument list if the template arguments of the partial
3403 // specialization can be deduced from the actual template argument
3404 // list (14.8.2).
3405
3406 // Unevaluated SFINAE context.
3409 Sema::SFINAETrap Trap(S);
3410
3411 // This deduction has no relation to any outer instantiation we might be
3412 // performing.
3413 LocalInstantiationScope InstantiationScope(S);
3414
3416 Deduced.resize(Partial->getTemplateParameters()->size());
3418 S, Partial->getTemplateParameters(),
3419 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3420 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/false,
3421 PackFold::ParameterToArgument,
3422 /*HasDeducedAnyParam=*/nullptr);
3424 return Result;
3425
3426 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3427 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs,
3428 Info);
3429 if (Inst.isInvalid())
3431
3432 if (Trap.hasErrorOccurred())
3434
3437 Result = ::FinishTemplateArgumentDeduction(S, Partial,
3438 /*IsPartialOrdering=*/false,
3439 TemplateArgs, Deduced, Info);
3440 });
3441 return Result;
3442}
3443
3446 ArrayRef<TemplateArgument> TemplateArgs,
3447 TemplateDeductionInfo &Info) {
3448 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3449}
3452 ArrayRef<TemplateArgument> TemplateArgs,
3453 TemplateDeductionInfo &Info) {
3454 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3455}
3456
3460 if (TD->isInvalidDecl())
3462
3463 QualType PType;
3464 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
3465 // Use the InjectedClassNameType.
3466 PType = Context.getTypeDeclType(CTD->getTemplatedDecl());
3467 } else if (const auto *AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(TD)) {
3468 PType = AliasTemplate->getTemplatedDecl()->getUnderlyingType();
3469 } else {
3470 assert(false && "Expected a class or alias template");
3471 }
3472
3473 // Unevaluated SFINAE context.
3476 SFINAETrap Trap(*this);
3477
3478 // This deduction has no relation to any outer instantiation we might be
3479 // performing.
3480 LocalInstantiationScope InstantiationScope(*this);
3481
3483 TD->getTemplateParameters()->size());
3486 if (auto DeducedResult = DeduceTemplateArguments(
3487 TD->getTemplateParameters(), PArgs, AArgs, Info, Deduced, false);
3488 DeducedResult != TemplateDeductionResult::Success) {
3489 return DeducedResult;
3490 }
3491
3492 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3493 InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs, Info);
3494 if (Inst.isInvalid())
3496
3497 if (Trap.hasErrorOccurred())
3499
3502 Result = ::FinishTemplateArgumentDeduction(*this, TD, Deduced, Info);
3503 });
3504 return Result;
3505}
3506
3507/// Determine whether the given type T is a simple-template-id type.
3509 if (const TemplateSpecializationType *Spec
3511 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
3512
3513 // C++17 [temp.local]p2:
3514 // the injected-class-name [...] is equivalent to the template-name followed
3515 // by the template-arguments of the class template specialization or partial
3516 // specialization enclosed in <>
3517 // ... which means it's equivalent to a simple-template-id.
3518 //
3519 // This only arises during class template argument deduction for a copy
3520 // deduction candidate, where it permits slicing.
3522 return true;
3523
3524 return false;
3525}
3526
3528 FunctionTemplateDecl *FunctionTemplate,
3529 TemplateArgumentListInfo &ExplicitTemplateArgs,
3532 TemplateDeductionInfo &Info) {
3533 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3534 TemplateParameterList *TemplateParams
3535 = FunctionTemplate->getTemplateParameters();
3536
3537 if (ExplicitTemplateArgs.size() == 0) {
3538 // No arguments to substitute; just copy over the parameter types and
3539 // fill in the function type.
3540 for (auto *P : Function->parameters())
3541 ParamTypes.push_back(P->getType());
3542
3543 if (FunctionType)
3544 *FunctionType = Function->getType();
3546 }
3547
3548 // Unevaluated SFINAE context.
3551 SFINAETrap Trap(*this);
3552
3553 // C++ [temp.arg.explicit]p3:
3554 // Template arguments that are present shall be specified in the
3555 // declaration order of their corresponding template-parameters. The
3556 // template argument list shall not specify more template-arguments than
3557 // there are corresponding template-parameters.
3558 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3559
3560 // Enter a new template instantiation context where we check the
3561 // explicitly-specified template arguments against this function template,
3562 // and then substitute them into the function parameter types.
3565 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3567 if (Inst.isInvalid())
3569
3571 ExplicitTemplateArgs, /*DefaultArgs=*/{}, true,
3572 SugaredBuilder, CanonicalBuilder,
3573 /*UpdateArgsWithConversions=*/false) ||
3574 Trap.hasErrorOccurred()) {
3575 unsigned Index = SugaredBuilder.size();
3576 if (Index >= TemplateParams->size())
3578 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3580 }
3581
3582 // Form the template argument list from the explicitly-specified
3583 // template arguments.
3584 TemplateArgumentList *SugaredExplicitArgumentList =
3586 TemplateArgumentList *CanonicalExplicitArgumentList =
3587 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3588 Info.setExplicitArgs(SugaredExplicitArgumentList,
3589 CanonicalExplicitArgumentList);
3590
3591 // Template argument deduction and the final substitution should be
3592 // done in the context of the templated declaration. Explicit
3593 // argument substitution, on the other hand, needs to happen in the
3594 // calling context.
3595 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3596
3597 // If we deduced template arguments for a template parameter pack,
3598 // note that the template argument pack is partially substituted and record
3599 // the explicit template arguments. They'll be used as part of deduction
3600 // for this template parameter pack.
3601 unsigned PartiallySubstitutedPackIndex = -1u;
3602 if (!SugaredBuilder.empty()) {
3603 const TemplateArgument &Arg = SugaredBuilder.back();
3604 if (Arg.getKind() == TemplateArgument::Pack) {
3605 auto *Param = TemplateParams->getParam(SugaredBuilder.size() - 1);
3606 // If this is a fully-saturated fixed-size pack, it should be
3607 // fully-substituted, not partially-substituted.
3608 std::optional<unsigned> Expansions = getExpandedPackSize(Param);
3609 if (!Expansions || Arg.pack_size() < *Expansions) {
3610 PartiallySubstitutedPackIndex = SugaredBuilder.size() - 1;
3612 Param, Arg.pack_begin(), Arg.pack_size());
3613 }
3614 }
3615 }
3616
3617 const FunctionProtoType *Proto
3618 = Function->getType()->getAs<FunctionProtoType>();
3619 assert(Proto && "Function template does not have a prototype?");
3620
3621 // Isolate our substituted parameters from our caller.
3622 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3623
3624 ExtParameterInfoBuilder ExtParamInfos;
3625
3627 SugaredExplicitArgumentList->asArray(),
3628 /*Final=*/true);
3629
3630 // Instantiate the types of each of the function parameters given the
3631 // explicitly-specified template arguments. If the function has a trailing
3632 // return type, substitute it after the arguments to ensure we substitute
3633 // in lexical order.
3634 if (Proto->hasTrailingReturn()) {
3635 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3636 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3637 /*params=*/nullptr, ExtParamInfos))
3639 }
3640
3641 // Instantiate the return type.
3642 QualType ResultType;
3643 {
3644 // C++11 [expr.prim.general]p3:
3645 // If a declaration declares a member function or member function
3646 // template of a class X, the expression this is a prvalue of type
3647 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3648 // and the end of the function-definition, member-declarator, or
3649 // declarator.
3650 Qualifiers ThisTypeQuals;
3651 CXXRecordDecl *ThisContext = nullptr;
3652 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3653 ThisContext = Method->getParent();
3654 ThisTypeQuals = Method->getMethodQualifiers();
3655 }
3656
3657 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3659
3660 ResultType =
3661 SubstType(Proto->getReturnType(), MLTAL,
3662 Function->getTypeSpecStartLoc(), Function->getDeclName());
3663 if (ResultType.isNull() || Trap.hasErrorOccurred())
3665 // CUDA: Kernel function must have 'void' return type.
3666 if (getLangOpts().CUDA)
3667 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3668 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3669 << Function->getType() << Function->getSourceRange();
3671 }
3672 }
3673
3674 // Instantiate the types of each of the function parameters given the
3675 // explicitly-specified template arguments if we didn't do so earlier.
3676 if (!Proto->hasTrailingReturn() &&
3677 SubstParmTypes(Function->getLocation(), Function->parameters(),
3678 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3679 /*params*/ nullptr, ExtParamInfos))
3681
3682 if (FunctionType) {
3683 auto EPI = Proto->getExtProtoInfo();
3684 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3685 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3686 Function->getLocation(),
3687 Function->getDeclName(),
3688 EPI);
3689 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3691 }
3692
3693 // C++ [temp.arg.explicit]p2:
3694 // Trailing template arguments that can be deduced (14.8.2) may be
3695 // omitted from the list of explicit template-arguments. If all of the
3696 // template arguments can be deduced, they may all be omitted; in this
3697 // case, the empty template argument list <> itself may also be omitted.
3698 //
3699 // Take all of the explicitly-specified arguments and put them into
3700 // the set of deduced template arguments. The partially-substituted
3701 // parameter pack, however, will be set to NULL since the deduction
3702 // mechanism handles the partially-substituted argument pack directly.
3703 Deduced.reserve(TemplateParams->size());
3704 for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3705 const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
3706 if (I == PartiallySubstitutedPackIndex)
3707 Deduced.push_back(DeducedTemplateArgument());
3708 else
3709 Deduced.push_back(Arg);
3710 }
3711
3713}
3714
3715/// Check whether the deduced argument type for a call to a function
3716/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3719 Sema::OriginalCallArg OriginalArg,
3720 QualType DeducedA) {
3721 ASTContext &Context = S.Context;
3722
3723 auto Failed = [&]() -> TemplateDeductionResult {
3724 Info.FirstArg = TemplateArgument(DeducedA);
3725 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3726 Info.CallArgIndex = OriginalArg.ArgIdx;
3727 return OriginalArg.DecomposedParam
3730 };
3731
3732 QualType A = OriginalArg.OriginalArgType;
3733 QualType OriginalParamType = OriginalArg.OriginalParamType;
3734
3735 // Check for type equality (top-level cv-qualifiers are ignored).
3736 if (Context.hasSameUnqualifiedType(A, DeducedA))
3738
3739 // Strip off references on the argument types; they aren't needed for
3740 // the following checks.
3741 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3742 DeducedA = DeducedARef->getPointeeType();
3743 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3744 A = ARef->getPointeeType();
3745
3746 // C++ [temp.deduct.call]p4:
3747 // [...] However, there are three cases that allow a difference:
3748 // - If the original P is a reference type, the deduced A (i.e., the
3749 // type referred to by the reference) can be more cv-qualified than
3750 // the transformed A.
3751 if (const ReferenceType *OriginalParamRef
3752 = OriginalParamType->getAs<ReferenceType>()) {
3753 // We don't want to keep the reference around any more.
3754 OriginalParamType = OriginalParamRef->getPointeeType();
3755
3756 // FIXME: Resolve core issue (no number yet): if the original P is a
3757 // reference type and the transformed A is function type "noexcept F",
3758 // the deduced A can be F.
3759 QualType Tmp;
3760 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
3762
3763 Qualifiers AQuals = A.getQualifiers();
3764 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3765
3766 // Under Objective-C++ ARC, the deduced type may have implicitly
3767 // been given strong or (when dealing with a const reference)
3768 // unsafe_unretained lifetime. If so, update the original
3769 // qualifiers to include this lifetime.
3770 if (S.getLangOpts().ObjCAutoRefCount &&
3771 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3773 (DeducedAQuals.hasConst() &&
3774 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3775 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3776 }
3777
3778 if (AQuals == DeducedAQuals) {
3779 // Qualifiers match; there's nothing to do.
3780 } else if (!DeducedAQuals.compatiblyIncludes(AQuals, S.getASTContext())) {
3781 return Failed();
3782 } else {
3783 // Qualifiers are compatible, so have the argument type adopt the
3784 // deduced argument type's qualifiers as if we had performed the
3785 // qualification conversion.
3786 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3787 }
3788 }
3789
3790 // - The transformed A can be another pointer or pointer to member
3791 // type that can be converted to the deduced A via a function pointer
3792 // conversion and/or a qualification conversion.
3793 //
3794 // Also allow conversions which merely strip __attribute__((noreturn)) from
3795 // function types (recursively).
3796 bool ObjCLifetimeConversion = false;
3797 QualType ResultTy;
3798 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3799 (S.IsQualificationConversion(A, DeducedA, false,
3800 ObjCLifetimeConversion) ||
3801 S.IsFunctionConversion(A, DeducedA, ResultTy)))
3803
3804 // - If P is a class and P has the form simple-template-id, then the
3805 // transformed A can be a derived class of the deduced A. [...]
3806 // [...] Likewise, if P is a pointer to a class of the form
3807 // simple-template-id, the transformed A can be a pointer to a
3808 // derived class pointed to by the deduced A.
3809 if (const PointerType *OriginalParamPtr
3810 = OriginalParamType->getAs<PointerType>()) {
3811 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3812 if (const PointerType *APtr = A->getAs<PointerType>()) {
3813 if (A->getPointeeType()->isRecordType()) {
3814 OriginalParamType = OriginalParamPtr->getPointeeType();
3815 DeducedA = DeducedAPtr->getPointeeType();
3816 A = APtr->getPointeeType();
3817 }
3818 }
3819 }
3820 }
3821
3822 if (Context.hasSameUnqualifiedType(A, DeducedA))
3824
3825 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3826 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3828
3829 return Failed();
3830}
3831
3832/// Find the pack index for a particular parameter index in an instantiation of
3833/// a function template with specific arguments.
3834///
3835/// \return The pack index for whichever pack produced this parameter, or -1
3836/// if this was not produced by a parameter. Intended to be used as the
3837/// ArgumentPackSubstitutionIndex for further substitutions.
3838// FIXME: We should track this in OriginalCallArgs so we don't need to
3839// reconstruct it here.
3840static unsigned getPackIndexForParam(Sema &S,
3841 FunctionTemplateDecl *FunctionTemplate,
3843 unsigned ParamIdx) {
3844 unsigned Idx = 0;
3845 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3846 if (PD->isParameterPack()) {
3847 unsigned NumExpansions =
3848 S.getNumArgumentsInExpansion(PD->getType(), Args).value_or(1);
3849 if (Idx + NumExpansions > ParamIdx)
3850 return ParamIdx - Idx;
3851 Idx += NumExpansions;
3852 } else {
3853 if (Idx == ParamIdx)
3854 return -1; // Not a pack expansion
3855 ++Idx;
3856 }
3857 }
3858
3859 llvm_unreachable("parameter index would not be produced from template");
3860}
3861
3862// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`,
3863// we'll try to instantiate and update its explicit specifier after constraint
3864// checking.
3867 const MultiLevelTemplateArgumentList &SubstArgs,
3868 TemplateDeductionInfo &Info, FunctionTemplateDecl *FunctionTemplate,
3869 ArrayRef<TemplateArgument> DeducedArgs) {
3870 auto GetExplicitSpecifier = [](FunctionDecl *D) {
3871 return isa<CXXConstructorDecl>(D)
3872 ? cast<CXXConstructorDecl>(D)->getExplicitSpecifier()
3873 : cast<CXXConversionDecl>(D)->getExplicitSpecifier();
3874 };
3875 auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) {
3876 isa<CXXConstructorDecl>(D)
3877 ? cast<CXXConstructorDecl>(D)->setExplicitSpecifier(ES)
3878 : cast<CXXConversionDecl>(D)->setExplicitSpecifier(ES);
3879 };
3880
3881 ExplicitSpecifier ES = GetExplicitSpecifier(Specialization);
3882 Expr *ExplicitExpr = ES.getExpr();
3883 if (!ExplicitExpr)
3885 if (!ExplicitExpr->isValueDependent())
3887
3889 S, Info.getLocation(), FunctionTemplate, DeducedArgs,
3891 if (Inst.isInvalid())
3893 Sema::SFINAETrap Trap(S);
3894 const ExplicitSpecifier InstantiatedES =
3895 S.instantiateExplicitSpecifier(SubstArgs, ES);
3896 if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) {
3897 Specialization->setInvalidDecl(true);
3899 }
3900 SetExplicitSpecifier(Specialization, InstantiatedES);
3902}
3903
3905 FunctionTemplateDecl *FunctionTemplate,
3907 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3909 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3910 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
3911 // Unevaluated SFINAE context.
3914 SFINAETrap Trap(*this);
3915
3916 // Enter a new template instantiation context while we instantiate the
3917 // actual function declaration.
3918 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3920 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3922 if (Inst.isInvalid())
3924
3925 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3926
3927 // C++ [temp.deduct.type]p2:
3928 // [...] or if any template argument remains neither deduced nor
3929 // explicitly specified, template argument deduction fails.
3930 bool IsIncomplete = false;
3931 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3933 *this, FunctionTemplate, /*IsDeduced*/ true, Deduced, Info,
3934 SugaredBuilder, CanonicalBuilder, CurrentInstantiationScope,
3935 NumExplicitlySpecified, PartialOverloading ? &IsIncomplete : nullptr);
3937 return Result;
3938
3939 // Form the template argument list from the deduced template arguments.
3940 TemplateArgumentList *SugaredDeducedArgumentList =
3942 TemplateArgumentList *CanonicalDeducedArgumentList =
3943 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3944 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3945
3946 // Substitute the deduced template arguments into the function template
3947 // declaration to produce the function template specialization.
3948 DeclContext *Owner = FunctionTemplate->getDeclContext();
3949 if (FunctionTemplate->getFriendObjectKind())
3950 Owner = FunctionTemplate->getLexicalDeclContext();
3951 FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
3952 // additional check for inline friend,
3953 // ```
3954 // template <class F1> int foo(F1 X);
3955 // template <int A1> struct A {
3956 // template <class F1> friend int foo(F1 X) { return A1; }
3957 // };
3958 // template struct A<1>;
3959 // int a = foo(1.0);
3960 // ```
3961 const FunctionDecl *FDFriend;
3963 FD->isDefined(FDFriend, /*CheckForPendingFriendDefinition*/ true) &&
3965 FD = const_cast<FunctionDecl *>(FDFriend);
3966 Owner = FD->getLexicalDeclContext();
3967 }
3968 // C++20 [temp.deduct.general]p5: [CWG2369]
3969 // If the function template has associated constraints, those constraints
3970 // are checked for satisfaction. If the constraints are not satisfied, type
3971 // deduction fails.
3972 //
3973 // FIXME: We haven't implemented CWG2369 for lambdas yet, because we need
3974 // to figure out how to instantiate lambda captures to the scope without
3975 // first instantiating the lambda.
3976 bool IsLambda = isLambdaCallOperator(FD) || isLambdaConversionOperator(FD);
3977 if (!IsLambda && !IsIncomplete) {
3979 Info.getLocation(),
3980 FunctionTemplate->getCanonicalDecl()->getTemplatedDecl(),
3981 CanonicalBuilder, Info.AssociatedConstraintsSatisfaction))
3984 Info.reset(Info.takeSugared(),
3985 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder));
3987 }
3988 }
3989 // C++ [temp.deduct.call]p10: [CWG1391]
3990 // If deduction succeeds for all parameters that contain
3991 // template-parameters that participate in template argument deduction,
3992 // and all template arguments are explicitly specified, deduced, or
3993 // obtained from default template arguments, remaining parameters are then
3994 // compared with the corresponding arguments. For each remaining parameter
3995 // P with a type that was non-dependent before substitution of any
3996 // explicitly-specified template arguments, if the corresponding argument
3997 // A cannot be implicitly converted to P, deduction fails.
3998 if (CheckNonDependent())
4000
4002 FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
4003 /*Final=*/false);
4004 Specialization = cast_or_null<FunctionDecl>(
4005 SubstDecl(FD, Owner, SubstArgs));
4006 if (!Specialization || Specialization->isInvalidDecl())
4008
4009 assert(isSameDeclaration(Specialization->getPrimaryTemplate(),
4011
4012 // If the template argument list is owned by the function template
4013 // specialization, release it.
4014 if (Specialization->getTemplateSpecializationArgs() ==
4015 CanonicalDeducedArgumentList &&
4016 !Trap.hasErrorOccurred())
4017 Info.takeCanonical();
4018
4019 // There may have been an error that did not prevent us from constructing a
4020 // declaration. Mark the declaration invalid and return with a substitution
4021 // failure.
4022 if (Trap.hasErrorOccurred()) {
4023 Specialization->setInvalidDecl(true);
4025 }
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) {
4037 Info.getLocation(), Specialization, CanonicalBuilder,
4040
4042 Info.reset(Info.takeSugared(),
4043 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder));
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.
4051 if (isa<CXXConstructorDecl, CXXConversionDecl>(Specialization)) {
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() ? 1 : 0;
4072 if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset)
4073 // FIXME: This presumably means a pack ended up smaller than we
4074 // expected while deducing. Should this not result in deduction
4075 // failure? Can it even happen?
4076 continue;
4077
4078 QualType DeducedA;
4079 if (!OriginalArg.DecomposedParam) {
4080 // P is one of the function parameters, just look up its substituted
4081 // type.
4082 DeducedA =
4083 Specialization->getParamDecl(ParamIdx + ExplicitOffset)->getType();
4084 } else {
4085 // P is a decomposed element of a parameter corresponding to a
4086 // braced-init-list argument. Substitute back into P to find the
4087 // deduced A.
4088 QualType &CacheEntry =
4089 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
4090 if (CacheEntry.isNull()) {
4092 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
4093 ParamIdx));
4094 CacheEntry =
4095 SubstType(OriginalArg.OriginalParamType, SubstArgs,
4096 Specialization->getTypeSpecStartLoc(),
4097 Specialization->getDeclName());
4098 }
4099 DeducedA = CacheEntry;
4100 }
4101
4102 if (auto TDK =
4103 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
4105 return TDK;
4106 }
4107 }
4108
4109 // If we suppressed any diagnostics while performing template argument
4110 // deduction, and if we haven't already instantiated this declaration,
4111 // keep track of these diagnostics. They'll be emitted if this specialization
4112 // is actually used.
4113 if (Info.diag_begin() != Info.diag_end()) {
4114 auto [Pos, Inserted] =
4115 SuppressedDiagnostics.try_emplace(Specialization->getCanonicalDecl());
4116 if (Inserted)
4117 Pos->second.append(Info.diag_begin(), Info.diag_end());
4118 }
4119
4121}
4122
4123/// Gets the type of a function for template-argument-deducton
4124/// purposes when it's considered as part of an overload set.
4126 FunctionDecl *Fn) {
4127 // We may need to deduce the return type of the function now.
4128 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
4129 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
4130 return {};
4131
4132 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
4133 if (Method->isImplicitObjectMemberFunction()) {
4134 // An instance method that's referenced in a form that doesn't
4135 // look like a member pointer is just invalid.
4137 return {};
4138
4139 return S.Context.getMemberPointerType(Fn->getType(),
4140 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
4141 }
4142
4143 if (!R.IsAddressOfOperand) return Fn->getType();
4144 return S.Context.getPointerType(Fn->getType());
4145}
4146
4147/// Apply the deduction rules for overload sets.
4148///
4149/// \return the null type if this argument should be treated as an
4150/// undeduced context
4151static QualType
4153 Expr *Arg, QualType ParamType,
4154 bool ParamWasReference,
4155 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4156
4158
4159 OverloadExpr *Ovl = R.Expression;
4160
4161 // C++0x [temp.deduct.call]p4
4162 unsigned TDF = 0;
4163 if (ParamWasReference)
4165 if (R.IsAddressOfOperand)
4166 TDF |= TDF_IgnoreQualifiers;
4167
4168 // C++0x [temp.deduct.call]p6:
4169 // When P is a function type, pointer to function type, or pointer
4170 // to member function type:
4171
4172 if (!ParamType->isFunctionType() &&
4173 !ParamType->isFunctionPointerType() &&
4174 !ParamType->isMemberFunctionPointerType()) {
4175 if (Ovl->hasExplicitTemplateArgs()) {
4176 // But we can still look for an explicit specialization.
4177 if (FunctionDecl *ExplicitSpec =
4179 Ovl, /*Complain=*/false,
4180 /*FoundDeclAccessPair=*/nullptr, FailedTSC))
4181 return GetTypeOfFunction(S, R, ExplicitSpec);
4182 }
4183
4184 DeclAccessPair DAP;
4185 if (FunctionDecl *Viable =
4187 return GetTypeOfFunction(S, R, Viable);
4188
4189 return {};
4190 }
4191
4192 // Gather the explicit template arguments, if any.
4193 TemplateArgumentListInfo ExplicitTemplateArgs;
4194 if (Ovl->hasExplicitTemplateArgs())
4195 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4196 QualType Match;
4197 for (UnresolvedSetIterator I = Ovl->decls_begin(),
4198 E = Ovl->decls_end(); I != E; ++I) {
4199 NamedDecl *D = (*I)->getUnderlyingDecl();
4200
4201 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
4202 // - If the argument is an overload set containing one or more
4203 // function templates, the parameter is treated as a
4204 // non-deduced context.
4205 if (!Ovl->hasExplicitTemplateArgs())
4206 return {};
4207
4208 // Otherwise, see if we can resolve a function type
4209 FunctionDecl *Specialization = nullptr;
4210 TemplateDeductionInfo Info(Ovl->getNameLoc());
4211 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
4214 continue;
4215
4216 D = Specialization;
4217 }
4218
4219 FunctionDecl *Fn = cast<FunctionDecl>(D);
4220 QualType ArgType = GetTypeOfFunction(S, R, Fn);
4221 if (ArgType.isNull()) continue;
4222
4223 // Function-to-pointer conversion.
4224 if (!ParamWasReference && ParamType->isPointerType() &&
4225 ArgType->isFunctionType())
4226 ArgType = S.Context.getPointerType(ArgType);
4227
4228 // - If the argument is an overload set (not containing function
4229 // templates), trial argument deduction is attempted using each
4230 // of the members of the set. If deduction succeeds for only one
4231 // of the overload set members, that member is used as the
4232 // argument value for the deduction. If deduction succeeds for
4233 // more than one member of the overload set the parameter is
4234 // treated as a non-deduced context.
4235
4236 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
4237 // Type deduction is done independently for each P/A pair, and
4238 // the deduced template argument values are then combined.
4239 // So we do not reject deductions which were made elsewhere.
4241 Deduced(TemplateParams->size());
4242 TemplateDeductionInfo Info(Ovl->getNameLoc());
4244 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4245 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4246 /*HasDeducedAnyParam=*/nullptr);
4248 continue;
4249 if (!Match.isNull())
4250 return {};
4251 Match = ArgType;
4252 }
4253
4254 return Match;
4255}
4256
4257/// Perform the adjustments to the parameter and argument types
4258/// described in C++ [temp.deduct.call].
4259///
4260/// \returns true if the caller should not attempt to perform any template
4261/// argument deduction based on this P/A pair because the argument is an
4262/// overloaded function set that could not be resolved.
4264 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4265 QualType &ParamType, QualType &ArgType,
4266 Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
4267 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4268 // C++0x [temp.deduct.call]p3:
4269 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
4270 // are ignored for type deduction.
4271 if (ParamType.hasQualifiers())
4272 ParamType = ParamType.getUnqualifiedType();
4273
4274 // [...] If P is a reference type, the type referred to by P is
4275 // used for type deduction.
4276 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
4277 if (ParamRefType)
4278 ParamType = ParamRefType->getPointeeType();
4279
4280 // Overload sets usually make this parameter an undeduced context,
4281 // but there are sometimes special circumstances. Typically
4282 // involving a template-id-expr.
4283 if (ArgType == S.Context.OverloadTy) {
4284 assert(Arg && "expected a non-null arg expression");
4285 ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType,
4286 ParamRefType != nullptr, FailedTSC);
4287 if (ArgType.isNull())
4288 return true;
4289 }
4290
4291 if (ParamRefType) {
4292 // If the argument has incomplete array type, try to complete its type.
4293 if (ArgType->isIncompleteArrayType()) {
4294 assert(Arg && "expected a non-null arg expression");
4295 ArgType = S.getCompletedType(Arg);
4296 }
4297
4298 // C++1z [temp.deduct.call]p3:
4299 // If P is a forwarding reference and the argument is an lvalue, the type
4300 // "lvalue reference to A" is used in place of A for type deduction.
4301 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
4302 ArgClassification.isLValue()) {
4303 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
4304 ArgType = S.Context.getAddrSpaceQualType(
4306 ArgType = S.Context.getLValueReferenceType(ArgType);
4307 }
4308 } else {
4309 // C++ [temp.deduct.call]p2:
4310 // If P is not a reference type:
4311 // - If A is an array type, the pointer type produced by the
4312 // array-to-pointer standard conversion (4.2) is used in place of
4313 // A for type deduction; otherwise,
4314 // - If A is a function type, the pointer type produced by the
4315 // function-to-pointer standard conversion (4.3) is used in place
4316 // of A for type deduction; otherwise,
4317 if (ArgType->canDecayToPointerType())
4318 ArgType = S.Context.getDecayedType(ArgType);
4319 else {
4320 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
4321 // type are ignored for type deduction.
4322 ArgType = ArgType.getUnqualifiedType();
4323 }
4324 }
4325
4326 // C++0x [temp.deduct.call]p4:
4327 // In general, the deduction process attempts to find template argument
4328 // values that will make the deduced A identical to A (after the type A
4329 // is transformed as described above). [...]
4331
4332 // - If the original P is a reference type, the deduced A (i.e., the
4333 // type referred to by the reference) can be more cv-qualified than
4334 // the transformed A.
4335 if (ParamRefType)
4337 // - The transformed A can be another pointer or pointer to member
4338 // type that can be converted to the deduced A via a qualification
4339 // conversion (4.4).
4340 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
4341 ArgType->isObjCObjectPointerType())
4342 TDF |= TDF_IgnoreQualifiers;
4343 // - If P is a class and P has the form simple-template-id, then the
4344 // transformed A can be a derived class of the deduced A. Likewise,
4345 // if P is a pointer to a class of the form simple-template-id, the
4346 // transformed A can be a pointer to a derived class pointed to by
4347 // the deduced A.
4348 if (isSimpleTemplateIdType(ParamType) ||
4349 (isa<PointerType>(ParamType) &&
4351 ParamType->castAs<PointerType>()->getPointeeType())))
4352 TDF |= TDF_DerivedClass;
4353
4354 return false;
4355}
4356
4357static bool
4359 QualType T);
4360
4362 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4363 QualType ParamType, QualType ArgType,
4364 Expr::Classification ArgClassification, Expr *Arg,
4368 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4369 TemplateSpecCandidateSet *FailedTSC = nullptr);
4370
4371/// Attempt template argument deduction from an initializer list
4372/// deemed to be an argument in a function call.
4374 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
4377 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
4378 unsigned TDF) {
4379 // C++ [temp.deduct.call]p1: (CWG 1591)
4380 // If removing references and cv-qualifiers from P gives
4381 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
4382 // a non-empty initializer list, then deduction is performed instead for
4383 // each element of the initializer list, taking P0 as a function template
4384 // parameter type and the initializer element as its argument
4385 //
4386 // We've already removed references and cv-qualifiers here.
4387 if (!ILE->getNumInits())
4389
4390 QualType ElTy;
4391 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
4392 if (ArrTy)
4393 ElTy = ArrTy->getElementType();
4394 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
4395 // Otherwise, an initializer list argument causes the parameter to be
4396 // considered a non-deduced context
4398 }
4399
4400 // Resolving a core issue: a braced-init-list containing any designators is
4401 // a non-deduced context.
4402 for (Expr *E : ILE->inits())
4403 if (isa<DesignatedInitExpr>(E))
4405
4406 // Deduction only needs to be done for dependent types.
4407 if (ElTy->isDependentType()) {
4408 for (Expr *E : ILE->inits()) {
4410 S, TemplateParams, 0, ElTy, E->getType(),
4411 E->Classify(S.getASTContext()), E, Info, Deduced,
4412 OriginalCallArgs, true, ArgIdx, TDF);
4414 return Result;
4415 }
4416 }
4417
4418 // in the P0[N] case, if N is a non-type template parameter, N is deduced
4419 // from the length of the initializer list.
4420 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
4421 // Determine the array bound is something we can deduce.
4422 if (const NonTypeTemplateParmDecl *NTTP =
4423 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
4424 // We can perform template argument deduction for the given non-type
4425 // template parameter.
4426 // C++ [temp.deduct.type]p13:
4427 // The type of N in the type T[N] is std::size_t.
4429 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
4431 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
4432 /*ArrayBound=*/true, Info, /*PartialOrdering=*/false, Deduced,
4433 /*HasDeducedAnyParam=*/nullptr);
4435 return Result;
4436 }
4437 }
4438
4440}
4441
4442/// Perform template argument deduction per [temp.deduct.call] for a
4443/// single parameter / argument pair.
4445 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4446 QualType ParamType, QualType ArgType,
4447 Expr::Classification ArgClassification, Expr *Arg,
4451 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4452 TemplateSpecCandidateSet *FailedTSC) {
4453
4454 QualType OrigParamType = ParamType;
4455
4456 // If P is a reference type [...]
4457 // If P is a cv-qualified type [...]
4459 S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
4460 ArgClassification, Arg, TDF, FailedTSC))
4462
4463 // If [...] the argument is a non-empty initializer list [...]
4464 if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
4465 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
4466 Deduced, OriginalCallArgs, ArgIdx, TDF);
4467
4468 // [...] the deduction process attempts to find template argument values
4469 // that will make the deduced A identical to A
4470 //
4471 // Keep track of the argument type and corresponding parameter index,
4472 // so we can check for compatibility between the deduced A and A.
4473 if (Arg)
4474 OriginalCallArgs.push_back(
4475 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
4477 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4478 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4479 /*HasDeducedAnyParam=*/nullptr);
4480}
4481
4483 FunctionTemplateDecl *FunctionTemplate,
4484 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4486 bool PartialOverloading, bool AggregateDeductionCandidate,
4487 QualType ObjectType, Expr::Classification ObjectClassification,
4488 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
4489 if (FunctionTemplate->isInvalidDecl())
4491
4492 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4493 unsigned NumParams = Function->getNumParams();
4494 bool HasExplicitObject = false;
4495 int ExplicitObjectOffset = 0;
4496 if (Function->hasCXXExplicitFunctionObjectParameter()) {
4497 HasExplicitObject = true;
4498 ExplicitObjectOffset = 1;
4499 }
4500
4501 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
4502
4503 // C++ [temp.deduct.call]p1:
4504 // Template argument deduction is done by comparing each function template
4505 // parameter type (call it P) with the type of the corresponding argument
4506 // of the call (call it A) as described below.
4507 if (Args.size() < Function->getMinRequiredExplicitArguments() &&
4508 !PartialOverloading)
4510 else if (TooManyArguments(NumParams, Args.size() + ExplicitObjectOffset,
4511 PartialOverloading)) {
4512 const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
4513 if (Proto->isTemplateVariadic())
4514 /* Do nothing */;
4515 else if (!Proto->isVariadic())
4517 }
4518
4519 // The types of the parameters from which we will perform template argument
4520 // deduction.
4521 LocalInstantiationScope InstScope(*this);
4522 TemplateParameterList *TemplateParams
4523 = FunctionTemplate->getTemplateParameters();
4525 SmallVector<QualType, 8> ParamTypes;
4526 unsigned NumExplicitlySpecified = 0;
4527 if (ExplicitTemplateArgs) {
4530 Result = SubstituteExplicitTemplateArguments(
4531 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4532 Info);
4533 });
4535 return Result;
4536
4537 NumExplicitlySpecified = Deduced.size();
4538 } else {
4539 // Just fill in the parameter types from the function declaration.
4540 for (unsigned I = 0; I != NumParams; ++I)
4541 ParamTypes.push_back(Function->getParamDecl(I)->getType());
4542 }
4543
4544 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
4545
4546 // Deduce an argument of type ParamType from an expression with index ArgIdx.
4547 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx,
4548 bool ExplicitObjectArgument) {
4549 // C++ [demp.deduct.call]p1: (DR1391)
4550 // Template argument deduction is done by comparing each function template
4551 // parameter that contains template-parameters that participate in
4552 // template argument deduction ...
4553 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4555
4556 if (ExplicitObjectArgument) {
4557 // ... with the type of the corresponding argument
4559 *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
4560 ObjectClassification,
4561 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4562 /*Decomposed*/ false, ArgIdx, /*TDF*/ 0);
4563 }
4564
4565 // ... with the type of the corresponding argument
4567 *this, TemplateParams, FirstInnerIndex, ParamType,
4568 Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()),
4569 Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false,
4570 ArgIdx, /*TDF*/ 0);
4571 };
4572
4573 // Deduce template arguments from the function parameters.
4574 Deduced.resize(TemplateParams->size());
4575 SmallVector<QualType, 8> ParamTypesForArgChecking;
4576 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4577 ParamIdx != NumParamTypes; ++ParamIdx) {
4578 QualType ParamType = ParamTypes[ParamIdx];
4579
4580 const PackExpansionType *ParamExpansion =
4581 dyn_cast<PackExpansionType>(ParamType);
4582 if (!ParamExpansion) {
4583 // Simple case: matching a function parameter to a function argument.
4584 if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0))
4585 break;
4586
4587 ParamTypesForArgChecking.push_back(ParamType);
4588
4589 if (ParamIdx == 0 && HasExplicitObject) {
4590 if (ObjectType.isNull())
4592
4593 if (auto Result = DeduceCallArgument(ParamType, 0,
4594 /*ExplicitObjectArgument=*/true);
4596 return Result;
4597 continue;
4598 }
4599
4600 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4601 /*ExplicitObjectArgument=*/false);
4603 return Result;
4604
4605 continue;
4606 }
4607
4608 bool IsTrailingPack = ParamIdx + 1 == NumParamTypes;
4609
4610 QualType ParamPattern = ParamExpansion->getPattern();
4611 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
4612 ParamPattern,
4613 AggregateDeductionCandidate && IsTrailingPack);
4614
4615 // C++0x [temp.deduct.call]p1:
4616 // For a function parameter pack that occurs at the end of the
4617 // parameter-declaration-list, the type A of each remaining argument of
4618 // the call is compared with the type P of the declarator-id of the
4619 // function parameter pack. Each comparison deduces template arguments
4620 // for subsequent positions in the template parameter packs expanded by
4621 // the function parameter pack. When a function parameter pack appears
4622 // in a non-deduced context [not at the end of the list], the type of
4623 // that parameter pack is never deduced.
4624 //
4625 // FIXME: The above rule allows the size of the parameter pack to change
4626 // after we skip it (in the non-deduced case). That makes no sense, so
4627 // we instead notionally deduce the pack against N arguments, where N is
4628 // the length of the explicitly-specified pack if it's expanded by the
4629 // parameter pack and 0 otherwise, and we treat each deduction as a
4630 // non-deduced context.
4631 if (IsTrailingPack || PackScope.hasFixedArity()) {
4632 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4633 PackScope.nextPackElement(), ++ArgIdx) {
4634 ParamTypesForArgChecking.push_back(ParamPattern);
4635 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4636 /*ExplicitObjectArgument=*/false);
4638 return Result;
4639 }
4640 } else {
4641 // If the parameter type contains an explicitly-specified pack that we
4642 // could not expand, skip the number of parameters notionally created
4643 // by the expansion.
4644 std::optional<unsigned> NumExpansions =
4645 ParamExpansion->getNumExpansions();
4646 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4647 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4648 ++I, ++ArgIdx) {
4649 ParamTypesForArgChecking.push_back(ParamPattern);
4650 // FIXME: Should we add OriginalCallArgs for these? What if the
4651 // corresponding argument is a list?
4652 PackScope.nextPackElement();
4653 }
4654 } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4655 PackScope.isDeducedFromEarlierParameter()) {
4656 // [temp.deduct.general#3]
4657 // When all template arguments have been deduced
4658 // or obtained from default template arguments, all uses of template
4659 // parameters in the template parameter list of the template are
4660 // replaced with the corresponding deduced or default argument values
4661 //
4662 // If we have a trailing parameter pack, that has been deduced
4663 // previously we substitute the pack here in a similar fashion as
4664 // above with the trailing parameter packs. The main difference here is
4665 // that, in this case we are not processing all of the remaining
4666 // arguments. We are only process as many arguments as we have in
4667 // the already deduced parameter.
4668 std::optional<unsigned> ArgPosAfterSubstitution =
4669 PackScope.getSavedPackSizeIfAllEqual();
4670 if (!ArgPosAfterSubstitution)
4671 continue;
4672
4673 unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4674 for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4675 ParamTypesForArgChecking.push_back(ParamPattern);
4676 if (auto Result =
4677 DeduceCallArgument(ParamPattern, ArgIdx,
4678 /*ExplicitObjectArgument=*/false);
4680 return Result;
4681
4682 PackScope.nextPackElement();
4683 }
4684 }
4685 }
4686
4687 // Build argument packs for each of the parameter packs expanded by this
4688 // pack expansion.
4689 if (auto Result = PackScope.finish();
4691 return Result;
4692 }
4693
4694 // Capture the context in which the function call is made. This is the context
4695 // that is needed when the accessibility of template arguments is checked.
4696 DeclContext *CallingCtx = CurContext;
4697
4700 Result = FinishTemplateArgumentDeduction(
4701 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4702 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
4703 ContextRAII SavedContext(*this, CallingCtx);
4704 return CheckNonDependent(ParamTypesForArgChecking);
4705 });
4706 });
4707 return Result;
4708}
4709
4712 bool AdjustExceptionSpec) {
4713 if (ArgFunctionType.isNull())
4714 return ArgFunctionType;
4715
4716 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4717 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4718 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4719 bool Rebuild = false;
4720
4721 CallingConv CC = FunctionTypeP->getCallConv();
4722 if (EPI.ExtInfo.getCC() != CC) {
4723 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4724 Rebuild = true;
4725 }
4726
4727 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4728 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4729 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4730 Rebuild = true;
4731 }
4732
4733 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4734 ArgFunctionTypeP->hasExceptionSpec())) {
4735 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4736 Rebuild = true;
4737 }
4738
4739 if (!Rebuild)
4740 return ArgFunctionType;
4741
4742 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4743 ArgFunctionTypeP->getParamTypes(), EPI);
4744}
4745
4747 FunctionTemplateDecl *FunctionTemplate,
4748 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4750 bool IsAddressOfFunction) {
4751 if (FunctionTemplate->isInvalidDecl())
4753
4754 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4755 TemplateParameterList *TemplateParams
4756 = FunctionTemplate->getTemplateParameters();
4757 QualType FunctionType = Function->getType();
4758
4759 // Substitute any explicit template arguments.
4760 LocalInstantiationScope InstScope(*this);
4762 unsigned NumExplicitlySpecified = 0;
4763 SmallVector<QualType, 4> ParamTypes;
4764 if (ExplicitTemplateArgs) {
4767 Result = SubstituteExplicitTemplateArguments(
4768 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4769 &FunctionType, Info);
4770 });
4772 return Result;
4773
4774 NumExplicitlySpecified = Deduced.size();
4775 }
4776
4777 // When taking the address of a function, we require convertibility of
4778 // the resulting function type. Otherwise, we allow arbitrary mismatches
4779 // of calling convention and noreturn.
4780 if (!IsAddressOfFunction)
4781 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4782 /*AdjustExceptionSpec*/false);
4783
4784 // Unevaluated SFINAE context.
4787 SFINAETrap Trap(*this);
4788
4789 Deduced.resize(TemplateParams->size());
4790
4791 // If the function has a deduced return type, substitute it for a dependent
4792 // type so that we treat it as a non-deduced context in what follows.
4793 bool HasDeducedReturnType = false;
4794 if (getLangOpts().CPlusPlus14 &&
4795 Function->getReturnType()->getContainedAutoType()) {
4797 HasDeducedReturnType = true;
4798 }
4799
4800 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
4801 unsigned TDF =
4803 // Deduce template arguments from the function type.
4805 *this, TemplateParams, FunctionType, ArgFunctionType, Info, Deduced,
4806 TDF, PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4807 /*HasDeducedAnyParam=*/nullptr);
4809 return Result;
4810 }
4811
4814 Result = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
4815 NumExplicitlySpecified,
4816 Specialization, Info);
4817 });
4819 return Result;
4820
4821 // If the function has a deduced return type, deduce it now, so we can check
4822 // that the deduced function type matches the requested type.
4823 if (HasDeducedReturnType && IsAddressOfFunction &&
4824 Specialization->getReturnType()->isUndeducedType() &&
4827
4828 // [C++26][expr.const]/p17
4829 // An expression or conversion is immediate-escalating if it is not initially
4830 // in an immediate function context and it is [...]
4831 // a potentially-evaluated id-expression that denotes an immediate function.
4832 if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
4833 Specialization->isImmediateEscalating() &&
4834 parentEvaluationContext().isPotentiallyEvaluated() &&
4836 Info.getLocation()))
4838
4839 // Adjust the exception specification of the argument to match the
4840 // substituted and resolved type we just formed. (Calling convention and
4841 // noreturn can't be dependent, so we don't actually need this for them
4842 // right now.)
4843 QualType SpecializationType = Specialization->getType();
4844 if (!IsAddressOfFunction) {
4845 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4846 /*AdjustExceptionSpec*/true);
4847
4848 // Revert placeholder types in the return type back to undeduced types so
4849 // that the comparison below compares the declared return types.
4850 if (HasDeducedReturnType) {
4851 SpecializationType = SubstAutoType(SpecializationType, QualType());
4852 ArgFunctionType = SubstAutoType(ArgFunctionType, QualType());
4853 }
4854 }
4855
4856 // If the requested function type does not match the actual type of the
4857 // specialization with respect to arguments of compatible pointer to function
4858 // types, template argument deduction fails.
4859 if (!ArgFunctionType.isNull()) {
4860 if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
4861 SpecializationType, ArgFunctionType)
4863 SpecializationType, ArgFunctionType)) {
4864 Info.FirstArg = TemplateArgument(SpecializationType);
4865 Info.SecondArg = TemplateArgument(ArgFunctionType);
4867 }
4868 }