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