clang 19.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 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
507 TemplateArgument New(D, T);
509 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
510}
511
512/// Create a shallow copy of a given template parameter declaration, with
513/// empty source locations and using the given TemplateArgument as it's
514/// default argument.
515///
516/// \returns The new template parameter declaration.
519 switch (A->getKind()) {
520 case Decl::TemplateTypeParm: {
521 auto *T = cast<TemplateTypeParmDecl>(A);
524 T->getDepth(), T->getIndex(), T->getIdentifier(),
525 T->wasDeclaredWithTypename(), T->isParameterPack(),
526 T->hasTypeConstraint());
527 R->setDefaultArgument(
528 S.Context,
530 if (R->hasTypeConstraint()) {
531 auto *C = R->getTypeConstraint();
532 R->setTypeConstraint(C->getConceptReference(),
533 C->getImmediatelyDeclaredConstraint());
534 }
535 return R;
536 }
537 case Decl::NonTypeTemplateParm: {
538 auto *T = cast<NonTypeTemplateParmDecl>(A);
541 T->getDepth(), T->getIndex(), T->getIdentifier(), T->getType(),
542 T->isParameterPack(), T->getTypeSourceInfo());
543 R->setDefaultArgument(S.Context,
545 Default, Default.getNonTypeTemplateArgumentType(),
546 SourceLocation()));
547 if (auto *PTC = T->getPlaceholderTypeConstraint())
548 R->setPlaceholderTypeConstraint(PTC);
549 return R;
550 }
551 case Decl::TemplateTemplateParm: {
552 auto *T = cast<TemplateTemplateParmDecl>(A);
554 S.Context, A->getDeclContext(), SourceLocation(), T->getDepth(),
555 T->getIndex(), T->isParameterPack(), T->getIdentifier(),
556 T->wasDeclaredWithTypename(), T->getTemplateParameters());
557 R->setDefaultArgument(
558 S.Context,
560 return R;
561 }
562 default:
563 llvm_unreachable("Unexpected Decl Kind");
564 }
565}
566
569 TemplateName Param, TemplateName Arg,
571 ArrayRef<TemplateArgument> DefaultArguments,
573 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
574 if (!ParamDecl) {
575 // The parameter type is dependent and is not a template template parameter,
576 // so there is nothing that we can deduce.
577 return TemplateDeductionResult::Success;
578 }
579
580 if (auto *TempParam = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
581 // If we're not deducing at this depth, there's nothing to deduce.
582 if (TempParam->getDepth() != Info.getDeducedDepth())
583 return TemplateDeductionResult::Success;
584
585 auto NewDeduced = DeducedTemplateArgument(Arg);
586 // Provisional resolution for CWG2398: If Arg is also a template template
587 // param, and it names a template specialization, then we deduce a
588 // synthesized template template parameter based on A, but using the TS's
589 // arguments as defaults.
590 if (auto *TempArg = dyn_cast_or_null<TemplateTemplateParmDecl>(
591 Arg.getAsTemplateDecl())) {
592 assert(!TempArg->isExpandedParameterPack());
593
594 TemplateParameterList *As = TempArg->getTemplateParameters();
595 if (DefaultArguments.size() != 0) {
596 assert(DefaultArguments.size() <= As->size());
597 SmallVector<NamedDecl *, 4> Params(As->size());
598 for (unsigned I = 0; I < DefaultArguments.size(); ++I)
599 Params[I] = getTemplateParameterWithDefault(S, As->getParam(I),
600 DefaultArguments[I]);
601 for (unsigned I = DefaultArguments.size(); I < As->size(); ++I)
602 Params[I] = As->getParam(I);
603 // FIXME: We could unique these, and also the parameters, but we don't
604 // expect programs to contain a large enough amount of these deductions
605 // for that to be worthwhile.
606 auto *TPL = TemplateParameterList::Create(
607 S.Context, SourceLocation(), SourceLocation(), Params,
609 NewDeduced = DeducedTemplateArgument(
611 S.Context, TempArg->getDeclContext(), SourceLocation(),
612 TempArg->getDepth(), TempArg->getPosition(),
613 TempArg->isParameterPack(), TempArg->getIdentifier(),
614 TempArg->wasDeclaredWithTypename(), TPL)));
615 }
616 }
617
619 Deduced[TempParam->getIndex()],
620 NewDeduced);
621 if (Result.isNull()) {
622 Info.Param = TempParam;
623 Info.FirstArg = Deduced[TempParam->getIndex()];
624 Info.SecondArg = NewDeduced;
625 return TemplateDeductionResult::Inconsistent;
626 }
627
628 Deduced[TempParam->getIndex()] = Result;
629 return TemplateDeductionResult::Success;
630 }
631
632 // Verify that the two template names are equivalent.
633 if (S.Context.hasSameTemplateName(Param, Arg))
634 return TemplateDeductionResult::Success;
635
636 // Mismatch of non-dependent template parameter to argument.
637 Info.FirstArg = TemplateArgument(Param);
638 Info.SecondArg = TemplateArgument(Arg);
639 return TemplateDeductionResult::NonDeducedMismatch;
640}
641
642/// Deduce the template arguments by comparing the template parameter
643/// type (which is a template-id) with the template argument type.
644///
645/// \param S the Sema
646///
647/// \param TemplateParams the template parameters that we are deducing
648///
649/// \param P the parameter type
650///
651/// \param A the argument type
652///
653/// \param Info information about the template argument deduction itself
654///
655/// \param Deduced the deduced template arguments
656///
657/// \returns the result of template argument deduction so far. Note that a
658/// "success" result means that template argument deduction has not yet failed,
659/// but it may still fail, later, for other reasons.
660
662 for (const Type *T = QT.getTypePtr(); /**/; /**/) {
663 const TemplateSpecializationType *TST =
665 assert(TST && "Expected a TemplateSpecializationType");
666 if (!TST->isSugared())
667 return TST;
668 T = TST->desugar().getTypePtr();
669 }
670}
671
674 const QualType P, QualType A,
677 QualType UP = P;
678 if (const auto *IP = P->getAs<InjectedClassNameType>())
679 UP = IP->getInjectedSpecializationType();
680
681 assert(isa<TemplateSpecializationType>(UP.getCanonicalType()));
683 TemplateName TNP = TP->getTemplateName();
684
685 // If the parameter is an alias template, there is nothing to deduce.
686 if (const auto *TD = TNP.getAsTemplateDecl(); TD && TD->isTypeAlias())
687 return TemplateDeductionResult::Success;
688
689 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
690 // arguments.
694 ->template_arguments();
695
696 QualType UA = A;
697 std::optional<NestedNameSpecifier *> NNS;
698 // Treat an injected-class-name as its underlying template-id.
699 if (const auto *Elaborated = A->getAs<ElaboratedType>()) {
700 NNS = Elaborated->getQualifier();
701 } else if (const auto *Injected = A->getAs<InjectedClassNameType>()) {
702 UA = Injected->getInjectedSpecializationType();
703 NNS = nullptr;
704 }
705
706 // Check whether the template argument is a dependent template-id.
707 if (isa<TemplateSpecializationType>(UA.getCanonicalType())) {
709 TemplateName TNA = SA->getTemplateName();
710
711 // If the argument is an alias template, there is nothing to deduce.
712 if (const auto *TD = TNA.getAsTemplateDecl(); TD && TD->isTypeAlias())
713 return TemplateDeductionResult::Success;
714
715 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
716 // arguments.
720 ->template_arguments();
721
722 // Perform template argument deduction for the template name.
723 if (auto Result = DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
724 AResolved, Deduced);
725 Result != TemplateDeductionResult::Success)
726 return Result;
727
728 // Perform template argument deduction on each template
729 // argument. Ignore any missing/extra arguments, since they could be
730 // filled in by default arguments.
731 return DeduceTemplateArguments(S, TemplateParams, PResolved, AResolved,
732 Info, Deduced,
733 /*NumberOfArgumentsMustMatch=*/false);
734 }
735
736 // If the argument type is a class template specialization, we
737 // perform template argument deduction using its template
738 // arguments.
739 const auto *RA = UA->getAs<RecordType>();
740 const auto *SA =
741 RA ? dyn_cast<ClassTemplateSpecializationDecl>(RA->getDecl()) : nullptr;
742 if (!SA) {
744 Info.SecondArg = TemplateArgument(A);
745 return TemplateDeductionResult::NonDeducedMismatch;
746 }
747
748 TemplateName TNA = TemplateName(SA->getSpecializedTemplate());
749 if (NNS)
751 *NNS, false, TemplateName(SA->getSpecializedTemplate()));
752
753 // Perform template argument deduction for the template name.
754 if (auto Result =
755 DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
756 SA->getTemplateArgs().asArray(), Deduced);
757 Result != TemplateDeductionResult::Success)
758 return Result;
759
760 // Perform template argument deduction for the template arguments.
761 return DeduceTemplateArguments(S, TemplateParams, PResolved,
762 SA->getTemplateArgs().asArray(), Info, Deduced,
763 /*NumberOfArgumentsMustMatch=*/true);
764}
765
767 assert(T->isCanonicalUnqualified());
768
769 switch (T->getTypeClass()) {
770 case Type::TypeOfExpr:
771 case Type::TypeOf:
772 case Type::DependentName:
773 case Type::Decltype:
774 case Type::PackIndexing:
775 case Type::UnresolvedUsing:
776 case Type::TemplateTypeParm:
777 case Type::Auto:
778 return true;
779
780 case Type::ConstantArray:
781 case Type::IncompleteArray:
782 case Type::VariableArray:
783 case Type::DependentSizedArray:
785 cast<ArrayType>(T)->getElementType().getTypePtr());
786
787 default:
788 return false;
789 }
790}
791
792/// Determines whether the given type is an opaque type that
793/// might be more qualified when instantiated.
797}
798
799/// Helper function to build a TemplateParameter when we don't
800/// know its type statically.
802 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
803 return TemplateParameter(TTP);
804 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
805 return TemplateParameter(NTTP);
806
807 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
808}
809
810/// A pack that we're currently deducing.
812 // The index of the pack.
813 unsigned Index;
814
815 // The old value of the pack before we started deducing it.
817
818 // A deferred value of this pack from an inner deduction, that couldn't be
819 // deduced because this deduction hadn't happened yet.
821
822 // The new value of the pack.
824
825 // The outer deduction for this pack, if any.
826 DeducedPack *Outer = nullptr;
827
828 DeducedPack(unsigned Index) : Index(Index) {}
829};
830
831namespace {
832
833/// A scope in which we're performing pack deduction.
834class PackDeductionScope {
835public:
836 /// Prepare to deduce the packs named within Pattern.
837 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
840 bool DeducePackIfNotAlreadyDeduced = false)
841 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info),
842 DeducePackIfNotAlreadyDeduced(DeducePackIfNotAlreadyDeduced){
843 unsigned NumNamedPacks = addPacks(Pattern);
844 finishConstruction(NumNamedPacks);
845 }
846
847 /// Prepare to directly deduce arguments of the parameter with index \p Index.
848 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
850 TemplateDeductionInfo &Info, unsigned Index)
851 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
852 addPack(Index);
853 finishConstruction(1);
854 }
855
856private:
857 void addPack(unsigned Index) {
858 // Save the deduced template argument for the parameter pack expanded
859 // by this pack expansion, then clear out the deduction.
860 DeducedFromEarlierParameter = !Deduced[Index].isNull();
861 DeducedPack Pack(Index);
862 Pack.Saved = Deduced[Index];
863 Deduced[Index] = TemplateArgument();
864
865 // FIXME: What if we encounter multiple packs with different numbers of
866 // pre-expanded expansions? (This should already have been diagnosed
867 // during substitution.)
868 if (std::optional<unsigned> ExpandedPackExpansions =
869 getExpandedPackSize(TemplateParams->getParam(Index)))
870 FixedNumExpansions = ExpandedPackExpansions;
871
872 Packs.push_back(Pack);
873 }
874
875 unsigned addPacks(TemplateArgument Pattern) {
876 // Compute the set of template parameter indices that correspond to
877 // parameter packs expanded by the pack expansion.
878 llvm::SmallBitVector SawIndices(TemplateParams->size());
880
881 auto AddPack = [&](unsigned Index) {
882 if (SawIndices[Index])
883 return;
884 SawIndices[Index] = true;
885 addPack(Index);
886
887 // Deducing a parameter pack that is a pack expansion also constrains the
888 // packs appearing in that parameter to have the same deduced arity. Also,
889 // in C++17 onwards, deducing a non-type template parameter deduces its
890 // type, so we need to collect the pending deduced values for those packs.
891 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
892 TemplateParams->getParam(Index))) {
893 if (!NTTP->isExpandedParameterPack())
894 if (auto *Expansion = dyn_cast<PackExpansionType>(NTTP->getType()))
895 ExtraDeductions.push_back(Expansion->getPattern());
896 }
897 // FIXME: Also collect the unexpanded packs in any type and template
898 // parameter packs that are pack expansions.
899 };
900
901 auto Collect = [&](TemplateArgument Pattern) {
903 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
904 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
905 unsigned Depth, Index;
906 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
907 if (Depth == Info.getDeducedDepth())
908 AddPack(Index);
909 }
910 };
911
912 // Look for unexpanded packs in the pattern.
913 Collect(Pattern);
914 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
915
916 unsigned NumNamedPacks = Packs.size();
917
918 // Also look for unexpanded packs that are indirectly deduced by deducing
919 // the sizes of the packs in this pattern.
920 while (!ExtraDeductions.empty())
921 Collect(ExtraDeductions.pop_back_val());
922
923 return NumNamedPacks;
924 }
925
926 void finishConstruction(unsigned NumNamedPacks) {
927 // Dig out the partially-substituted pack, if there is one.
928 const TemplateArgument *PartialPackArgs = nullptr;
929 unsigned NumPartialPackArgs = 0;
930 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
931 if (auto *Scope = S.CurrentInstantiationScope)
932 if (auto *Partial = Scope->getPartiallySubstitutedPack(
933 &PartialPackArgs, &NumPartialPackArgs))
934 PartialPackDepthIndex = getDepthAndIndex(Partial);
935
936 // This pack expansion will have been partially or fully expanded if
937 // it only names explicitly-specified parameter packs (including the
938 // partially-substituted one, if any).
939 bool IsExpanded = true;
940 for (unsigned I = 0; I != NumNamedPacks; ++I) {
941 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
942 IsExpanded = false;
943 IsPartiallyExpanded = false;
944 break;
945 }
946 if (PartialPackDepthIndex ==
947 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
948 IsPartiallyExpanded = true;
949 }
950 }
951
952 // Skip over the pack elements that were expanded into separate arguments.
953 // If we partially expanded, this is the number of partial arguments.
954 if (IsPartiallyExpanded)
955 PackElements += NumPartialPackArgs;
956 else if (IsExpanded)
957 PackElements += *FixedNumExpansions;
958
959 for (auto &Pack : Packs) {
960 if (Info.PendingDeducedPacks.size() > Pack.Index)
961 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
962 else
963 Info.PendingDeducedPacks.resize(Pack.Index + 1);
964 Info.PendingDeducedPacks[Pack.Index] = &Pack;
965
966 if (PartialPackDepthIndex ==
967 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
968 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
969 // We pre-populate the deduced value of the partially-substituted
970 // pack with the specified value. This is not entirely correct: the
971 // value is supposed to have been substituted, not deduced, but the
972 // cases where this is observable require an exact type match anyway.
973 //
974 // FIXME: If we could represent a "depth i, index j, pack elem k"
975 // parameter, we could substitute the partially-substituted pack
976 // everywhere and avoid this.
977 if (!IsPartiallyExpanded)
978 Deduced[Pack.Index] = Pack.New[PackElements];
979 }
980 }
981 }
982
983public:
984 ~PackDeductionScope() {
985 for (auto &Pack : Packs)
986 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
987 }
988
989 // Return the size of the saved packs if all of them has the same size.
990 std::optional<unsigned> getSavedPackSizeIfAllEqual() const {
991 unsigned PackSize = Packs[0].Saved.pack_size();
992
993 if (std::all_of(Packs.begin() + 1, Packs.end(), [&PackSize](const auto &P) {
994 return P.Saved.pack_size() == PackSize;
995 }))
996 return PackSize;
997 return {};
998 }
999
1000 /// Determine whether this pack has already been deduced from a previous
1001 /// argument.
1002 bool isDeducedFromEarlierParameter() const {
1003 return DeducedFromEarlierParameter;
1004 }
1005
1006 /// Determine whether this pack has already been partially expanded into a
1007 /// sequence of (prior) function parameters / template arguments.
1008 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
1009
1010 /// Determine whether this pack expansion scope has a known, fixed arity.
1011 /// This happens if it involves a pack from an outer template that has
1012 /// (notionally) already been expanded.
1013 bool hasFixedArity() { return FixedNumExpansions.has_value(); }
1014
1015 /// Determine whether the next element of the argument is still part of this
1016 /// pack. This is the case unless the pack is already expanded to a fixed
1017 /// length.
1018 bool hasNextElement() {
1019 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
1020 }
1021
1022 /// Move to deducing the next element in each pack that is being deduced.
1023 void nextPackElement() {
1024 // Capture the deduced template arguments for each parameter pack expanded
1025 // by this pack expansion, add them to the list of arguments we've deduced
1026 // for that pack, then clear out the deduced argument.
1027 for (auto &Pack : Packs) {
1028 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
1029 if (!Pack.New.empty() || !DeducedArg.isNull()) {
1030 while (Pack.New.size() < PackElements)
1031 Pack.New.push_back(DeducedTemplateArgument());
1032 if (Pack.New.size() == PackElements)
1033 Pack.New.push_back(DeducedArg);
1034 else
1035 Pack.New[PackElements] = DeducedArg;
1036 DeducedArg = Pack.New.size() > PackElements + 1
1037 ? Pack.New[PackElements + 1]
1039 }
1040 }
1041 ++PackElements;
1042 }
1043
1044 /// Finish template argument deduction for a set of argument packs,
1045 /// producing the argument packs and checking for consistency with prior
1046 /// deductions.
1047 TemplateDeductionResult finish() {
1048 // Build argument packs for each of the parameter packs expanded by this
1049 // pack expansion.
1050 for (auto &Pack : Packs) {
1051 // Put back the old value for this pack.
1052 Deduced[Pack.Index] = Pack.Saved;
1053
1054 // Always make sure the size of this pack is correct, even if we didn't
1055 // deduce any values for it.
1056 //
1057 // FIXME: This isn't required by the normative wording, but substitution
1058 // and post-substitution checking will always fail if the arity of any
1059 // pack is not equal to the number of elements we processed. (Either that
1060 // or something else has gone *very* wrong.) We're permitted to skip any
1061 // hard errors from those follow-on steps by the intent (but not the
1062 // wording) of C++ [temp.inst]p8:
1063 //
1064 // If the function selected by overload resolution can be determined
1065 // without instantiating a class template definition, it is unspecified
1066 // whether that instantiation actually takes place
1067 Pack.New.resize(PackElements);
1068
1069 // Build or find a new value for this pack.
1071 if (Pack.New.empty()) {
1072 // If we deduced an empty argument pack, create it now.
1074 } else {
1075 TemplateArgument *ArgumentPack =
1076 new (S.Context) TemplateArgument[Pack.New.size()];
1077 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
1078 NewPack = DeducedTemplateArgument(
1079 TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())),
1080 // FIXME: This is wrong, it's possible that some pack elements are
1081 // deduced from an array bound and others are not:
1082 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
1083 // g({1, 2, 3}, {{}, {}});
1084 // ... should deduce T = {int, size_t (from array bound)}.
1085 Pack.New[0].wasDeducedFromArrayBound());
1086 }
1087
1088 // Pick where we're going to put the merged pack.
1090 if (Pack.Outer) {
1091 if (Pack.Outer->DeferredDeduction.isNull()) {
1092 // Defer checking this pack until we have a complete pack to compare
1093 // it against.
1094 Pack.Outer->DeferredDeduction = NewPack;
1095 continue;
1096 }
1097 Loc = &Pack.Outer->DeferredDeduction;
1098 } else {
1099 Loc = &Deduced[Pack.Index];
1100 }
1101
1102 // Check the new pack matches any previous value.
1103 DeducedTemplateArgument OldPack = *Loc;
1105 S.Context, OldPack, NewPack, DeducePackIfNotAlreadyDeduced);
1106
1107 Info.AggregateDeductionCandidateHasMismatchedArity =
1108 OldPack.getKind() == TemplateArgument::Pack &&
1109 NewPack.getKind() == TemplateArgument::Pack &&
1110 OldPack.pack_size() != NewPack.pack_size() && !Result.isNull();
1111
1112 // If we deferred a deduction of this pack, check that one now too.
1113 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
1114 OldPack = Result;
1115 NewPack = Pack.DeferredDeduction;
1116 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
1117 }
1118
1119 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
1120 if (Result.isNull()) {
1121 Info.Param = makeTemplateParameter(Param);
1122 Info.FirstArg = OldPack;
1123 Info.SecondArg = NewPack;
1124 return TemplateDeductionResult::Inconsistent;
1125 }
1126
1127 // If we have a pre-expanded pack and we didn't deduce enough elements
1128 // for it, fail deduction.
1129 if (std::optional<unsigned> Expansions = getExpandedPackSize(Param)) {
1130 if (*Expansions != PackElements) {
1131 Info.Param = makeTemplateParameter(Param);
1132 Info.FirstArg = Result;
1133 return TemplateDeductionResult::IncompletePack;
1134 }
1135 }
1136
1137 *Loc = Result;
1138 }
1139
1140 return TemplateDeductionResult::Success;
1141 }
1142
1143private:
1144 Sema &S;
1145 TemplateParameterList *TemplateParams;
1148 unsigned PackElements = 0;
1149 bool IsPartiallyExpanded = false;
1150 bool DeducePackIfNotAlreadyDeduced = false;
1151 bool DeducedFromEarlierParameter = false;
1152 /// The number of expansions, if we have a fully-expanded pack in this scope.
1153 std::optional<unsigned> FixedNumExpansions;
1154
1156};
1157
1158} // namespace
1159
1160/// Deduce the template arguments by comparing the list of parameter
1161/// types to the list of argument types, as in the parameter-type-lists of
1162/// function types (C++ [temp.deduct.type]p10).
1163///
1164/// \param S The semantic analysis object within which we are deducing
1165///
1166/// \param TemplateParams The template parameters that we are deducing
1167///
1168/// \param Params The list of parameter types
1169///
1170/// \param NumParams The number of types in \c Params
1171///
1172/// \param Args The list of argument types
1173///
1174/// \param NumArgs The number of types in \c Args
1175///
1176/// \param Info information about the template argument deduction itself
1177///
1178/// \param Deduced the deduced template arguments
1179///
1180/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1181/// how template argument deduction is performed.
1182///
1183/// \param PartialOrdering If true, we are performing template argument
1184/// deduction for during partial ordering for a call
1185/// (C++0x [temp.deduct.partial]).
1186///
1187/// \returns the result of template argument deduction so far. Note that a
1188/// "success" result means that template argument deduction has not yet failed,
1189/// but it may still fail, later, for other reasons.
1192 const QualType *Params, unsigned NumParams,
1193 const QualType *Args, unsigned NumArgs,
1196 unsigned TDF, bool PartialOrdering = false) {
1197 // C++0x [temp.deduct.type]p10:
1198 // Similarly, if P has a form that contains (T), then each parameter type
1199 // Pi of the respective parameter-type- list of P is compared with the
1200 // corresponding parameter type Ai of the corresponding parameter-type-list
1201 // of A. [...]
1202 unsigned ArgIdx = 0, ParamIdx = 0;
1203 for (; ParamIdx != NumParams; ++ParamIdx) {
1204 // Check argument types.
1205 const PackExpansionType *Expansion
1206 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1207 if (!Expansion) {
1208 // Simple case: compare the parameter and argument types at this point.
1209
1210 // Make sure we have an argument.
1211 if (ArgIdx >= NumArgs)
1212 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1213
1214 if (isa<PackExpansionType>(Args[ArgIdx])) {
1215 // C++0x [temp.deduct.type]p22:
1216 // If the original function parameter associated with A is a function
1217 // parameter pack and the function parameter associated with P is not
1218 // a function parameter pack, then template argument deduction fails.
1219 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1220 }
1221
1223 S, TemplateParams, Params[ParamIdx].getUnqualifiedType(),
1224 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, TDF,
1226 /*DeducedFromArrayBound=*/false);
1227 Result != TemplateDeductionResult::Success)
1228 return Result;
1229
1230 ++ArgIdx;
1231 continue;
1232 }
1233
1234 // C++0x [temp.deduct.type]p10:
1235 // If the parameter-declaration corresponding to Pi is a function
1236 // parameter pack, then the type of its declarator- id is compared with
1237 // each remaining parameter type in the parameter-type-list of A. Each
1238 // comparison deduces template arguments for subsequent positions in the
1239 // template parameter packs expanded by the function parameter pack.
1240
1241 QualType Pattern = Expansion->getPattern();
1242 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
1243
1244 // A pack scope with fixed arity is not really a pack any more, so is not
1245 // a non-deduced context.
1246 if (ParamIdx + 1 == NumParams || PackScope.hasFixedArity()) {
1247 for (; ArgIdx < NumArgs && PackScope.hasNextElement(); ++ArgIdx) {
1248 // Deduce template arguments from the pattern.
1250 S, TemplateParams, Pattern.getUnqualifiedType(),
1251 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, TDF,
1252 PartialOrdering, /*DeducedFromArrayBound=*/false);
1253 Result != TemplateDeductionResult::Success)
1254 return Result;
1255
1256 PackScope.nextPackElement();
1257 }
1258 } else {
1259 // C++0x [temp.deduct.type]p5:
1260 // The non-deduced contexts are:
1261 // - A function parameter pack that does not occur at the end of the
1262 // parameter-declaration-clause.
1263 //
1264 // FIXME: There is no wording to say what we should do in this case. We
1265 // choose to resolve this by applying the same rule that is applied for a
1266 // function call: that is, deduce all contained packs to their
1267 // explicitly-specified values (or to <> if there is no such value).
1268 //
1269 // This is seemingly-arbitrarily different from the case of a template-id
1270 // with a non-trailing pack-expansion in its arguments, which renders the
1271 // entire template-argument-list a non-deduced context.
1272
1273 // If the parameter type contains an explicitly-specified pack that we
1274 // could not expand, skip the number of parameters notionally created
1275 // by the expansion.
1276 std::optional<unsigned> NumExpansions = Expansion->getNumExpansions();
1277 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1278 for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs;
1279 ++I, ++ArgIdx)
1280 PackScope.nextPackElement();
1281 }
1282 }
1283
1284 // Build argument packs for each of the parameter packs expanded by this
1285 // pack expansion.
1286 if (auto Result = PackScope.finish();
1287 Result != TemplateDeductionResult::Success)
1288 return Result;
1289 }
1290
1291 // DR692, DR1395
1292 // C++0x [temp.deduct.type]p10:
1293 // If the parameter-declaration corresponding to P_i ...
1294 // During partial ordering, if Ai was originally a function parameter pack:
1295 // - if P does not contain a function parameter type corresponding to Ai then
1296 // Ai is ignored;
1297 if (PartialOrdering && ArgIdx + 1 == NumArgs &&
1298 isa<PackExpansionType>(Args[ArgIdx]))
1299 return TemplateDeductionResult::Success;
1300
1301 // Make sure we don't have any extra arguments.
1302 if (ArgIdx < NumArgs)
1303 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1304
1305 return TemplateDeductionResult::Success;
1306}
1307
1308/// Determine whether the parameter has qualifiers that the argument
1309/// lacks. Put another way, determine whether there is no way to add
1310/// a deduced set of qualifiers to the ParamType that would result in
1311/// its qualifiers matching those of the ArgType.
1313 QualType ArgType) {
1314 Qualifiers ParamQs = ParamType.getQualifiers();
1315 Qualifiers ArgQs = ArgType.getQualifiers();
1316
1317 if (ParamQs == ArgQs)
1318 return false;
1319
1320 // Mismatched (but not missing) Objective-C GC attributes.
1321 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1322 ParamQs.hasObjCGCAttr())
1323 return true;
1324
1325 // Mismatched (but not missing) address spaces.
1326 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1327 ParamQs.hasAddressSpace())
1328 return true;
1329
1330 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1331 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1332 ParamQs.hasObjCLifetime())
1333 return true;
1334
1335 // CVR qualifiers inconsistent or a superset.
1336 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1337}
1338
1340 const FunctionType *PF = P->getAs<FunctionType>(),
1341 *AF = A->getAs<FunctionType>();
1342
1343 // Just compare if not functions.
1344 if (!PF || !AF)
1345 return Context.hasSameType(P, A);
1346
1347 // Noreturn and noexcept adjustment.
1348 if (QualType AdjustedParam; IsFunctionConversion(P, A, AdjustedParam))
1349 P = AdjustedParam;
1350
1351 // FIXME: Compatible calling conventions.
1353}
1354
1355/// Get the index of the first template parameter that was originally from the
1356/// innermost template-parameter-list. This is 0 except when we concatenate
1357/// the template parameter lists of a class template and a constructor template
1358/// when forming an implicit deduction guide.
1360 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1361 if (!Guide || !Guide->isImplicit())
1362 return 0;
1363 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1364}
1365
1366/// Determine whether a type denotes a forwarding reference.
1367static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1368 // C++1z [temp.deduct.call]p3:
1369 // A forwarding reference is an rvalue reference to a cv-unqualified
1370 // template parameter that does not represent a template parameter of a
1371 // class template.
1372 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1373 if (ParamRef->getPointeeType().getQualifiers())
1374 return false;
1375 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1376 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1377 }
1378 return false;
1379}
1380
1382 return cast<CXXRecordDecl>(
1384}
1385
1386/// Attempt to deduce the template arguments by checking the base types
1387/// according to (C++20 [temp.deduct.call] p4b3.
1388///
1389/// \param S the semantic analysis object within which we are deducing.
1390///
1391/// \param RD the top level record object we are deducing against.
1392///
1393/// \param TemplateParams the template parameters that we are deducing.
1394///
1395/// \param P the template specialization parameter type.
1396///
1397/// \param Info information about the template argument deduction itself.
1398///
1399/// \param Deduced the deduced template arguments.
1400///
1401/// \returns the result of template argument deduction with the bases. "invalid"
1402/// means no matches, "success" found a single item, and the
1403/// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
1406 TemplateParameterList *TemplateParams, QualType P,
1409 // C++14 [temp.deduct.call] p4b3:
1410 // If P is a class and P has the form simple-template-id, then the
1411 // transformed A can be a derived class of the deduced A. Likewise if
1412 // P is a pointer to a class of the form simple-template-id, the
1413 // transformed A can be a pointer to a derived class pointed to by the
1414 // deduced A. However, if there is a class C that is a (direct or
1415 // indirect) base class of D and derived (directly or indirectly) from a
1416 // class B and that would be a valid deduced A, the deduced A cannot be
1417 // B or pointer to B, respectively.
1418 //
1419 // These alternatives are considered only if type deduction would
1420 // otherwise fail. If they yield more than one possible deduced A, the
1421 // type deduction fails.
1422
1423 // Use a breadth-first search through the bases to collect the set of
1424 // successful matches. Visited contains the set of nodes we have already
1425 // visited, while ToVisit is our stack of records that we still need to
1426 // visit. Matches contains a list of matches that have yet to be
1427 // disqualified.
1430 // We iterate over this later, so we have to use MapVector to ensure
1431 // determinism.
1432 llvm::MapVector<const CXXRecordDecl *,
1434 Matches;
1435
1436 auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
1437 for (const auto &Base : RD->bases()) {
1438 QualType T = Base.getType();
1439 assert(T->isRecordType() && "Base class that isn't a record?");
1440 if (Visited.insert(::getCanonicalRD(T)).second)
1441 ToVisit.push_back(T);
1442 }
1443 };
1444
1445 // Set up the loop by adding all the bases.
1446 AddBases(RD);
1447
1448 // Search each path of bases until we either run into a successful match
1449 // (where all bases of it are invalid), or we run out of bases.
1450 while (!ToVisit.empty()) {
1451 QualType NextT = ToVisit.pop_back_val();
1452
1453 SmallVector<DeducedTemplateArgument, 8> DeducedCopy(Deduced.begin(),
1454 Deduced.end());
1457 S, TemplateParams, P, NextT, BaseInfo, DeducedCopy);
1458
1459 // If this was a successful deduction, add it to the list of matches,
1460 // otherwise we need to continue searching its bases.
1461 const CXXRecordDecl *RD = ::getCanonicalRD(NextT);
1463 Matches.insert({RD, DeducedCopy});
1464 else
1465 AddBases(RD);
1466 }
1467
1468 // At this point, 'Matches' contains a list of seemingly valid bases, however
1469 // in the event that we have more than 1 match, it is possible that the base
1470 // of one of the matches might be disqualified for being a base of another
1471 // valid match. We can count on cyclical instantiations being invalid to
1472 // simplify the disqualifications. That is, if A & B are both matches, and B
1473 // inherits from A (disqualifying A), we know that A cannot inherit from B.
1474 if (Matches.size() > 1) {
1475 Visited.clear();
1476 for (const auto &Match : Matches)
1477 AddBases(Match.first);
1478
1479 // We can give up once we have a single item (or have run out of things to
1480 // search) since cyclical inheritance isn't valid.
1481 while (Matches.size() > 1 && !ToVisit.empty()) {
1482 const CXXRecordDecl *RD = ::getCanonicalRD(ToVisit.pop_back_val());
1483 Matches.erase(RD);
1484
1485 // Always add all bases, since the inheritance tree can contain
1486 // disqualifications for multiple matches.
1487 AddBases(RD);
1488 }
1489 }
1490
1491 if (Matches.empty())
1493 if (Matches.size() > 1)
1495
1496 std::swap(Matches.front().second, Deduced);
1498}
1499
1500/// Deduce the template arguments by comparing the parameter type and
1501/// the argument type (C++ [temp.deduct.type]).
1502///
1503/// \param S the semantic analysis object within which we are deducing
1504///
1505/// \param TemplateParams the template parameters that we are deducing
1506///
1507/// \param P the parameter type
1508///
1509/// \param A the argument type
1510///
1511/// \param Info information about the template argument deduction itself
1512///
1513/// \param Deduced the deduced template arguments
1514///
1515/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1516/// how template argument deduction is performed.
1517///
1518/// \param PartialOrdering Whether we're performing template argument deduction
1519/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1520///
1521/// \returns the result of template argument deduction so far. Note that a
1522/// "success" result means that template argument deduction has not yet failed,
1523/// but it may still fail, later, for other reasons.
1525 Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
1527 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1528 bool PartialOrdering, bool DeducedFromArrayBound) {
1529
1530 // If the argument type is a pack expansion, look at its pattern.
1531 // This isn't explicitly called out
1532 if (const auto *AExp = dyn_cast<PackExpansionType>(A))
1533 A = AExp->getPattern();
1534 assert(!isa<PackExpansionType>(A.getCanonicalType()));
1535
1536 if (PartialOrdering) {
1537 // C++11 [temp.deduct.partial]p5:
1538 // Before the partial ordering is done, certain transformations are
1539 // performed on the types used for partial ordering:
1540 // - If P is a reference type, P is replaced by the type referred to.
1541 const ReferenceType *PRef = P->getAs<ReferenceType>();
1542 if (PRef)
1543 P = PRef->getPointeeType();
1544
1545 // - If A is a reference type, A is replaced by the type referred to.
1546 const ReferenceType *ARef = A->getAs<ReferenceType>();
1547 if (ARef)
1548 A = A->getPointeeType();
1549
1550 if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
1551 // C++11 [temp.deduct.partial]p9:
1552 // If, for a given type, deduction succeeds in both directions (i.e.,
1553 // the types are identical after the transformations above) and both
1554 // P and A were reference types [...]:
1555 // - if [one type] was an lvalue reference and [the other type] was
1556 // not, [the other type] is not considered to be at least as
1557 // specialized as [the first type]
1558 // - if [one type] is more cv-qualified than [the other type],
1559 // [the other type] is not considered to be at least as specialized
1560 // as [the first type]
1561 // Objective-C ARC adds:
1562 // - [one type] has non-trivial lifetime, [the other type] has
1563 // __unsafe_unretained lifetime, and the types are otherwise
1564 // identical
1565 //
1566 // A is "considered to be at least as specialized" as P iff deduction
1567 // succeeds, so we model this as a deduction failure. Note that
1568 // [the first type] is P and [the other type] is A here; the standard
1569 // gets this backwards.
1570 Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
1571 if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
1572 PQuals.isStrictSupersetOf(AQuals) ||
1573 (PQuals.hasNonTrivialObjCLifetime() &&
1574 AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1575 PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
1576 Info.FirstArg = TemplateArgument(P);
1577 Info.SecondArg = TemplateArgument(A);
1579 }
1580 }
1581 Qualifiers DiscardedQuals;
1582 // C++11 [temp.deduct.partial]p7:
1583 // Remove any top-level cv-qualifiers:
1584 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1585 // version of P.
1586 P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
1587 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1588 // version of A.
1589 A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
1590 } else {
1591 // C++0x [temp.deduct.call]p4 bullet 1:
1592 // - If the original P is a reference type, the deduced A (i.e., the type
1593 // referred to by the reference) can be more cv-qualified than the
1594 // transformed A.
1595 if (TDF & TDF_ParamWithReferenceType) {
1596 Qualifiers Quals;
1597 QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
1599 P = S.Context.getQualifiedType(UnqualP, Quals);
1600 }
1601
1602 if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
1603 // C++0x [temp.deduct.type]p10:
1604 // If P and A are function types that originated from deduction when
1605 // taking the address of a function template (14.8.2.2) or when deducing
1606 // template arguments from a function declaration (14.8.2.6) and Pi and
1607 // Ai are parameters of the top-level parameter-type-list of P and A,
1608 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1609 // is an lvalue reference, in
1610 // which case the type of Pi is changed to be the template parameter
1611 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1612 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1613 // deduced as X&. - end note ]
1614 TDF &= ~TDF_TopLevelParameterTypeList;
1615 if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
1617 P = P->getPointeeType();
1618 }
1619 }
1620
1621 // C++ [temp.deduct.type]p9:
1622 // A template type argument T, a template template argument TT or a
1623 // template non-type argument i can be deduced if P and A have one of
1624 // the following forms:
1625 //
1626 // T
1627 // cv-list T
1628 if (const auto *TTP = P->getAs<TemplateTypeParmType>()) {
1629 // Just skip any attempts to deduce from a placeholder type or a parameter
1630 // at a different depth.
1631 if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
1633
1634 unsigned Index = TTP->getIndex();
1635
1636 // If the argument type is an array type, move the qualifiers up to the
1637 // top level, so they can be matched with the qualifiers on the parameter.
1638 if (A->isArrayType()) {
1639 Qualifiers Quals;
1640 A = S.Context.getUnqualifiedArrayType(A, Quals);
1641 if (Quals)
1642 A = S.Context.getQualifiedType(A, Quals);
1643 }
1644
1645 // The argument type can not be less qualified than the parameter
1646 // type.
1647 if (!(TDF & TDF_IgnoreQualifiers) &&
1649 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1650 Info.FirstArg = TemplateArgument(P);
1651 Info.SecondArg = TemplateArgument(A);
1653 }
1654
1655 // Do not match a function type with a cv-qualified type.
1656 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1657 if (A->isFunctionType() && P.hasQualifiers())
1659
1660 assert(TTP->getDepth() == Info.getDeducedDepth() &&
1661 "saw template type parameter with wrong depth");
1662 assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&
1663 "Unresolved overloaded function");
1665
1666 // Remove any qualifiers on the parameter from the deduced type.
1667 // We checked the qualifiers for consistency above.
1668 Qualifiers DeducedQs = DeducedType.getQualifiers();
1669 Qualifiers ParamQs = P.getQualifiers();
1670 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1671 if (ParamQs.hasObjCGCAttr())
1672 DeducedQs.removeObjCGCAttr();
1673 if (ParamQs.hasAddressSpace())
1674 DeducedQs.removeAddressSpace();
1675 if (ParamQs.hasObjCLifetime())
1676 DeducedQs.removeObjCLifetime();
1677
1678 // Objective-C ARC:
1679 // If template deduction would produce a lifetime qualifier on a type
1680 // that is not a lifetime type, template argument deduction fails.
1681 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1683 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1684 Info.FirstArg = TemplateArgument(P);
1685 Info.SecondArg = TemplateArgument(A);
1687 }
1688
1689 // Objective-C ARC:
1690 // If template deduction would produce an argument type with lifetime type
1691 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1692 if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
1693 !DeducedQs.hasObjCLifetime())
1695
1696 DeducedType =
1697 S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
1698
1699 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1701 checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
1702 if (Result.isNull()) {
1703 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1704 Info.FirstArg = Deduced[Index];
1705 Info.SecondArg = NewDeduced;
1707 }
1708
1709 Deduced[Index] = Result;
1711 }
1712
1713 // Set up the template argument deduction information for a failure.
1714 Info.FirstArg = TemplateArgument(P);
1715 Info.SecondArg = TemplateArgument(A);
1716
1717 // If the parameter is an already-substituted template parameter
1718 // pack, do nothing: we don't know which of its arguments to look
1719 // at, so we have to wait until all of the parameter packs in this
1720 // expansion have arguments.
1721 if (P->getAs<SubstTemplateTypeParmPackType>())
1723
1724 // Check the cv-qualifiers on the parameter and argument types.
1725 if (!(TDF & TDF_IgnoreQualifiers)) {
1726 if (TDF & TDF_ParamWithReferenceType) {
1729 } else if (TDF & TDF_ArgWithReferenceType) {
1730 // C++ [temp.deduct.conv]p4:
1731 // If the original A is a reference type, A can be more cv-qualified
1732 // than the deduced A
1733 if (!A.getQualifiers().compatiblyIncludes(P.getQualifiers()))
1735
1736 // Strip out all extra qualifiers from the argument to figure out the
1737 // type we're converting to, prior to the qualification conversion.
1738 Qualifiers Quals;
1739 A = S.Context.getUnqualifiedArrayType(A, Quals);
1740 A = S.Context.getQualifiedType(A, P.getQualifiers());
1741 } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
1742 if (P.getCVRQualifiers() != A.getCVRQualifiers())
1744 }
1745 }
1746
1747 // If the parameter type is not dependent, there is nothing to deduce.
1748 if (!P->isDependentType()) {
1749 if (TDF & TDF_SkipNonDependent)
1752 : S.Context.hasSameType(P, A))
1757 if (!(TDF & TDF_IgnoreQualifiers))
1759 // Otherwise, when ignoring qualifiers, the types not having the same
1760 // unqualified type does not mean they do not match, so in this case we
1761 // must keep going and analyze with a non-dependent parameter type.
1762 }
1763
1764 switch (P.getCanonicalType()->getTypeClass()) {
1765 // Non-canonical types cannot appear here.
1766#define NON_CANONICAL_TYPE(Class, Base) \
1767 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1768#define TYPE(Class, Base)
1769#include "clang/AST/TypeNodes.inc"
1770
1771 case Type::TemplateTypeParm:
1772 case Type::SubstTemplateTypeParmPack:
1773 llvm_unreachable("Type nodes handled above");
1774
1775 case Type::Auto:
1776 // C++23 [temp.deduct.funcaddr]/3:
1777 // A placeholder type in the return type of a function template is a
1778 // non-deduced context.
1779 // There's no corresponding wording for [temp.deduct.decl], but we treat
1780 // it the same to match other compilers.
1781 if (P->isDependentType())
1783 [[fallthrough]];
1784 case Type::Builtin:
1785 case Type::VariableArray:
1786 case Type::Vector:
1787 case Type::FunctionNoProto:
1788 case Type::Record:
1789 case Type::Enum:
1790 case Type::ObjCObject:
1791 case Type::ObjCInterface:
1792 case Type::ObjCObjectPointer:
1793 case Type::BitInt:
1794 return (TDF & TDF_SkipNonDependent) ||
1795 ((TDF & TDF_IgnoreQualifiers)
1797 : S.Context.hasSameType(P, A))
1800
1801 // _Complex T [placeholder extension]
1802 case Type::Complex: {
1803 const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
1804 if (!CA)
1807 S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
1808 Deduced, TDF);
1809 }
1810
1811 // _Atomic T [extension]
1812 case Type::Atomic: {
1813 const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
1814 if (!AA)
1817 S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
1818 Deduced, TDF);
1819 }
1820
1821 // T *
1822 case Type::Pointer: {
1823 QualType PointeeType;
1824 if (const auto *PA = A->getAs<PointerType>()) {
1825 PointeeType = PA->getPointeeType();
1826 } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
1827 PointeeType = PA->getPointeeType();
1828 } else {
1830 }
1832 S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
1833 PointeeType, Info, Deduced,
1835 }
1836
1837 // T &
1838 case Type::LValueReference: {
1839 const auto *RP = P->castAs<LValueReferenceType>(),
1840 *RA = A->getAs<LValueReferenceType>();
1841 if (!RA)
1843
1845 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1846 Deduced, 0);
1847 }
1848
1849 // T && [C++0x]
1850 case Type::RValueReference: {
1851 const auto *RP = P->castAs<RValueReferenceType>(),
1852 *RA = A->getAs<RValueReferenceType>();
1853 if (!RA)
1855
1857 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1858 Deduced, 0);
1859 }
1860
1861 // T [] (implied, but not stated explicitly)
1862 case Type::IncompleteArray: {
1863 const auto *IAA = S.Context.getAsIncompleteArrayType(A);
1864 if (!IAA)
1866
1867 const auto *IAP = S.Context.getAsIncompleteArrayType(P);
1868 assert(IAP && "Template parameter not of incomplete array type");
1869
1871 S, TemplateParams, IAP->getElementType(), IAA->getElementType(), Info,
1872 Deduced, TDF & TDF_IgnoreQualifiers);
1873 }
1874
1875 // T [integer-constant]
1876 case Type::ConstantArray: {
1877 const auto *CAA = S.Context.getAsConstantArrayType(A),
1879 assert(CAP);
1880 if (!CAA || CAA->getSize() != CAP->getSize())
1882
1884 S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
1885 Deduced, TDF & TDF_IgnoreQualifiers);
1886 }
1887
1888 // type [i]
1889 case Type::DependentSizedArray: {
1890 const auto *AA = S.Context.getAsArrayType(A);
1891 if (!AA)
1893
1894 // Check the element type of the arrays
1895 const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
1896 assert(DAP);
1898 S, TemplateParams, DAP->getElementType(), AA->getElementType(),
1899 Info, Deduced, TDF & TDF_IgnoreQualifiers);
1901 return Result;
1902
1903 // Determine the array bound is something we can deduce.
1904 const NonTypeTemplateParmDecl *NTTP =
1905 getDeducedParameterFromExpr(Info, DAP->getSizeExpr());
1906 if (!NTTP)
1908
1909 // We can perform template argument deduction for the given non-type
1910 // template parameter.
1911 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1912 "saw non-type template parameter with wrong depth");
1913 if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
1914 llvm::APSInt Size(CAA->getSize());
1916 S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
1917 /*ArrayBound=*/true, Info, Deduced);
1918 }
1919 if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
1920 if (DAA->getSizeExpr())
1922 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info, Deduced);
1923
1924 // Incomplete type does not match a dependently-sized array type
1926 }
1927
1928 // type(*)(T)
1929 // T(*)()
1930 // T(*)(T)
1931 case Type::FunctionProto: {
1932 const auto *FPP = P->castAs<FunctionProtoType>(),
1933 *FPA = A->getAs<FunctionProtoType>();
1934 if (!FPA)
1936
1937 if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
1938 FPP->getRefQualifier() != FPA->getRefQualifier() ||
1939 FPP->isVariadic() != FPA->isVariadic())
1941
1942 // Check return types.
1944 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
1945 Info, Deduced, 0,
1946 /*PartialOrdering=*/false,
1947 /*DeducedFromArrayBound=*/false);
1949 return Result;
1950
1951 // Check parameter types.
1953 S, TemplateParams, FPP->param_type_begin(), FPP->getNumParams(),
1954 FPA->param_type_begin(), FPA->getNumParams(), Info, Deduced,
1957 return Result;
1958
1961
1962 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1963 // deducing through the noexcept-specifier if it's part of the canonical
1964 // type. libstdc++ relies on this.
1965 Expr *NoexceptExpr = FPP->getNoexceptExpr();
1966 if (const NonTypeTemplateParmDecl *NTTP =
1967 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
1968 : nullptr) {
1969 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1970 "saw non-type template parameter with wrong depth");
1971
1972 llvm::APSInt Noexcept(1);
1973 switch (FPA->canThrow()) {
1974 case CT_Cannot:
1975 Noexcept = 1;
1976 [[fallthrough]];
1977
1978 case CT_Can:
1979 // We give E in noexcept(E) the "deduced from array bound" treatment.
1980 // FIXME: Should we?
1982 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
1983 /*DeducedFromArrayBound=*/true, Info, Deduced);
1984
1985 case CT_Dependent:
1986 if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
1988 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
1989 // Can't deduce anything from throw(T...).
1990 break;
1991 }
1992 }
1993 // FIXME: Detect non-deduced exception specification mismatches?
1994 //
1995 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
1996 // top-level differences in noexcept-specifications.
1997
1999 }
2000
2001 case Type::InjectedClassName:
2002 // Treat a template's injected-class-name as if the template
2003 // specialization type had been used.
2004
2005 // template-name<T> (where template-name refers to a class template)
2006 // template-name<i>
2007 // TT<T>
2008 // TT<i>
2009 // TT<>
2010 case Type::TemplateSpecialization: {
2011 // When Arg cannot be a derived class, we can just try to deduce template
2012 // arguments from the template-id.
2013 if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
2014 return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
2015 Deduced);
2016
2017 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
2018 Deduced.end());
2019
2020 auto Result =
2021 DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info, Deduced);
2023 return Result;
2024
2025 // We cannot inspect base classes as part of deduction when the type
2026 // is incomplete, so either instantiate any templates necessary to
2027 // complete the type, or skip over it if it cannot be completed.
2028 if (!S.isCompleteType(Info.getLocation(), A))
2029 return Result;
2030
2031 if (getCanonicalRD(A)->isInvalidDecl())
2032 return Result;
2033
2034 // Reset the incorrectly deduced argument from above.
2035 Deduced = DeducedOrig;
2036
2037 // Check bases according to C++14 [temp.deduct.call] p4b3:
2039 TemplateParams, P, Info, Deduced);
2041 : Result;
2042 }
2043
2044 // T type::*
2045 // T T::*
2046 // T (type::*)()
2047 // type (T::*)()
2048 // type (type::*)(T)
2049 // type (T::*)(T)
2050 // T (type::*)(T)
2051 // T (T::*)()
2052 // T (T::*)(T)
2053 case Type::MemberPointer: {
2054 const auto *MPP = P->castAs<MemberPointerType>(),
2055 *MPA = A->getAs<MemberPointerType>();
2056 if (!MPA)
2058
2059 QualType PPT = MPP->getPointeeType();
2060 if (PPT->isFunctionType())
2061 S.adjustMemberFunctionCC(PPT, /*HasThisPointer=*/false,
2062 /*IsCtorOrDtor=*/false, Info.getLocation());
2063 QualType APT = MPA->getPointeeType();
2064 if (APT->isFunctionType())
2065 S.adjustMemberFunctionCC(APT, /*HasThisPointer=*/false,
2066 /*IsCtorOrDtor=*/false, Info.getLocation());
2067
2068 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
2070 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF);
2072 return Result;
2074 S, TemplateParams, QualType(MPP->getClass(), 0),
2075 QualType(MPA->getClass(), 0), Info, Deduced, SubTDF);
2076 }
2077
2078 // (clang extension)
2079 //
2080 // type(^)(T)
2081 // T(^)()
2082 // T(^)(T)
2083 case Type::BlockPointer: {
2084 const auto *BPP = P->castAs<BlockPointerType>(),
2085 *BPA = A->getAs<BlockPointerType>();
2086 if (!BPA)
2089 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
2090 Deduced, 0);
2091 }
2092
2093 // (clang extension)
2094 //
2095 // T __attribute__(((ext_vector_type(<integral constant>))))
2096 case Type::ExtVector: {
2097 const auto *VP = P->castAs<ExtVectorType>();
2098 QualType ElementType;
2099 if (const auto *VA = A->getAs<ExtVectorType>()) {
2100 // Make sure that the vectors have the same number of elements.
2101 if (VP->getNumElements() != VA->getNumElements())
2103 ElementType = VA->getElementType();
2104 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2105 // We can't check the number of elements, since the argument has a
2106 // dependent number of elements. This can only occur during partial
2107 // ordering.
2108 ElementType = VA->getElementType();
2109 } else {
2111 }
2112 // Perform deduction on the element types.
2114 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
2115 TDF);
2116 }
2117
2118 case Type::DependentVector: {
2119 const auto *VP = P->castAs<DependentVectorType>();
2120
2121 if (const auto *VA = A->getAs<VectorType>()) {
2122 // Perform deduction on the element types.
2124 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2125 Info, Deduced, TDF);
2127 return Result;
2128
2129 // Perform deduction on the vector size, if we can.
2130 const NonTypeTemplateParmDecl *NTTP =
2131 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2132 if (!NTTP)
2134
2135 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2136 ArgSize = VA->getNumElements();
2137 // Note that we use the "array bound" rules here; just like in that
2138 // case, we don't have any particular type for the vector size, but
2139 // we can provide one if necessary.
2140 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2141 S.Context.UnsignedIntTy, true,
2142 Info, Deduced);
2143 }
2144
2145 if (const auto *VA = A->getAs<DependentVectorType>()) {
2146 // Perform deduction on the element types.
2148 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2149 Info, Deduced, TDF);
2151 return Result;
2152
2153 // Perform deduction on the vector size, if we can.
2154 const NonTypeTemplateParmDecl *NTTP =
2155 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2156 if (!NTTP)
2158
2159 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2160 VA->getSizeExpr(), Info, Deduced);
2161 }
2162
2164 }
2165
2166 // (clang extension)
2167 //
2168 // T __attribute__(((ext_vector_type(N))))
2169 case Type::DependentSizedExtVector: {
2170 const auto *VP = P->castAs<DependentSizedExtVectorType>();
2171
2172 if (const auto *VA = A->getAs<ExtVectorType>()) {
2173 // Perform deduction on the element types.
2175 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2176 Info, Deduced, TDF);
2178 return Result;
2179
2180 // Perform deduction on the vector size, if we can.
2181 const NonTypeTemplateParmDecl *NTTP =
2182 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2183 if (!NTTP)
2185
2186 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2187 ArgSize = VA->getNumElements();
2188 // Note that we use the "array bound" rules here; just like in that
2189 // case, we don't have any particular type for the vector size, but
2190 // we can provide one if necessary.
2191 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2192 S.Context.IntTy, true, Info,
2193 Deduced);
2194 }
2195
2196 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2197 // Perform deduction on the element types.
2199 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2200 Info, Deduced, TDF);
2202 return Result;
2203
2204 // Perform deduction on the vector size, if we can.
2205 const NonTypeTemplateParmDecl *NTTP =
2206 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2207 if (!NTTP)
2209
2210 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2211 VA->getSizeExpr(), Info, Deduced);
2212 }
2213
2215 }
2216
2217 // (clang extension)
2218 //
2219 // T __attribute__((matrix_type(<integral constant>,
2220 // <integral constant>)))
2221 case Type::ConstantMatrix: {
2222 const auto *MP = P->castAs<ConstantMatrixType>(),
2223 *MA = A->getAs<ConstantMatrixType>();
2224 if (!MA)
2226
2227 // Check that the dimensions are the same
2228 if (MP->getNumRows() != MA->getNumRows() ||
2229 MP->getNumColumns() != MA->getNumColumns()) {
2231 }
2232 // Perform deduction on element types.
2234 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2235 Deduced, TDF);
2236 }
2237
2238 case Type::DependentSizedMatrix: {
2239 const auto *MP = P->castAs<DependentSizedMatrixType>();
2240 const auto *MA = A->getAs<MatrixType>();
2241 if (!MA)
2243
2244 // Check the element type of the matrixes.
2246 S, TemplateParams, MP->getElementType(), MA->getElementType(),
2247 Info, Deduced, TDF);
2249 return Result;
2250
2251 // Try to deduce a matrix dimension.
2252 auto DeduceMatrixArg =
2253 [&S, &Info, &Deduced, &TemplateParams](
2254 Expr *ParamExpr, const MatrixType *A,
2255 unsigned (ConstantMatrixType::*GetArgDimension)() const,
2256 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2257 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2258 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
2259 if (!ParamExpr->isValueDependent()) {
2260 std::optional<llvm::APSInt> ParamConst =
2261 ParamExpr->getIntegerConstantExpr(S.Context);
2262 if (!ParamConst)
2264
2265 if (ACM) {
2266 if ((ACM->*GetArgDimension)() == *ParamConst)
2269 }
2270
2271 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2272 if (std::optional<llvm::APSInt> ArgConst =
2273 ArgExpr->getIntegerConstantExpr(S.Context))
2274 if (*ArgConst == *ParamConst)
2277 }
2278
2279 const NonTypeTemplateParmDecl *NTTP =
2280 getDeducedParameterFromExpr(Info, ParamExpr);
2281 if (!NTTP)
2283
2284 if (ACM) {
2285 llvm::APSInt ArgConst(
2287 ArgConst = (ACM->*GetArgDimension)();
2289 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
2290 /*ArrayBound=*/true, Info, Deduced);
2291 }
2292
2293 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2294 (ADM->*GetArgDimensionExpr)(),
2295 Info, Deduced);
2296 };
2297
2298 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
2302 return Result;
2303
2304 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2307 }
2308
2309 // (clang extension)
2310 //
2311 // T __attribute__(((address_space(N))))
2312 case Type::DependentAddressSpace: {
2313 const auto *ASP = P->castAs<DependentAddressSpaceType>();
2314
2315 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
2316 // Perform deduction on the pointer type.
2318 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2319 Info, Deduced, TDF);
2321 return Result;
2322
2323 // Perform deduction on the address space, if we can.
2324 const NonTypeTemplateParmDecl *NTTP =
2325 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2326 if (!NTTP)
2328
2330 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info, Deduced);
2331 }
2332
2334 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2335 false);
2336 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
2337
2338 // Perform deduction on the pointer types.
2340 S, TemplateParams, ASP->getPointeeType(),
2341 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF);
2343 return Result;
2344
2345 // Perform deduction on the address space, if we can.
2346 const NonTypeTemplateParmDecl *NTTP =
2347 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2348 if (!NTTP)
2350
2351 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2352 ArgAddressSpace, S.Context.IntTy,
2353 true, Info, Deduced);
2354 }
2355
2357 }
2358 case Type::DependentBitInt: {
2359 const auto *IP = P->castAs<DependentBitIntType>();
2360
2361 if (const auto *IA = A->getAs<BitIntType>()) {
2362 if (IP->isUnsigned() != IA->isUnsigned())
2364
2365 const NonTypeTemplateParmDecl *NTTP =
2366 getDeducedParameterFromExpr(Info, IP->getNumBitsExpr());
2367 if (!NTTP)
2369
2370 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2371 ArgSize = IA->getNumBits();
2372
2373 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2374 S.Context.IntTy, true, Info,
2375 Deduced);
2376 }
2377
2378 if (const auto *IA = A->getAs<DependentBitIntType>()) {
2379 if (IP->isUnsigned() != IA->isUnsigned())
2382 }
2383
2385 }
2386
2387 case Type::TypeOfExpr:
2388 case Type::TypeOf:
2389 case Type::DependentName:
2390 case Type::UnresolvedUsing:
2391 case Type::Decltype:
2392 case Type::UnaryTransform:
2393 case Type::DeducedTemplateSpecialization:
2394 case Type::DependentTemplateSpecialization:
2395 case Type::PackExpansion:
2396 case Type::Pipe:
2397 case Type::ArrayParameter:
2398 // No template argument deduction for these types
2400
2401 case Type::PackIndexing: {
2402 const PackIndexingType *PIT = P->getAs<PackIndexingType>();
2403 if (PIT->hasSelectedType()) {
2405 S, TemplateParams, PIT->getSelectedType(), A, Info, Deduced, TDF);
2406 }
2408 }
2409 }
2410
2411 llvm_unreachable("Invalid Type Class!");
2412}
2413
2419 // If the template argument is a pack expansion, perform template argument
2420 // deduction against the pattern of that expansion. This only occurs during
2421 // partial ordering.
2422 if (A.isPackExpansion())
2424
2425 switch (P.getKind()) {
2427 llvm_unreachable("Null template argument in parameter list");
2428
2432 S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0);
2433 Info.FirstArg = P;
2434 Info.SecondArg = A;
2436
2439 return DeduceTemplateArguments(S, TemplateParams, P.getAsTemplate(),
2440 A.getAsTemplate(), Info,
2441 /*DefaultArguments=*/{}, Deduced);
2442 Info.FirstArg = P;
2443 Info.SecondArg = A;
2445
2447 llvm_unreachable("caller should handle pack expansions");
2448
2451 isSameDeclaration(P.getAsDecl(), A.getAsDecl()))
2453
2454 Info.FirstArg = P;
2455 Info.SecondArg = A;
2457
2460 S.Context.hasSameType(P.getNullPtrType(), A.getNullPtrType()))
2462
2463 Info.FirstArg = P;
2464 Info.SecondArg = A;
2466
2469 if (hasSameExtendedValue(P.getAsIntegral(), A.getAsIntegral()))
2471 }
2472 Info.FirstArg = P;
2473 Info.SecondArg = A;
2475
2480
2481 Info.FirstArg = P;
2482 Info.SecondArg = A;
2484
2486 if (const NonTypeTemplateParmDecl *NTTP =
2487 getDeducedParameterFromExpr(Info, P.getAsExpr())) {
2488 switch (A.getKind()) {
2493 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2494 A.getNonTypeTemplateArgumentType(), Info, Deduced);
2495
2497 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
2498 A.getNullPtrType(), Info, Deduced);
2499
2502 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
2503 Info, Deduced);
2504
2510 Info.FirstArg = P;
2511 Info.SecondArg = A;
2513 }
2514 llvm_unreachable("Unknown template argument kind");
2515 }
2516
2517 // Can't deduce anything, but that's okay.
2520 llvm_unreachable("Argument packs should be expanded by the caller!");
2521 }
2522
2523 llvm_unreachable("Invalid TemplateArgument Kind!");
2524}
2525
2526/// Determine whether there is a template argument to be used for
2527/// deduction.
2528///
2529/// This routine "expands" argument packs in-place, overriding its input
2530/// parameters so that \c Args[ArgIdx] will be the available template argument.
2531///
2532/// \returns true if there is another template argument (which will be at
2533/// \c Args[ArgIdx]), false otherwise.
2535 unsigned &ArgIdx) {
2536 if (ArgIdx == Args.size())
2537 return false;
2538
2539 const TemplateArgument &Arg = Args[ArgIdx];
2540 if (Arg.getKind() != TemplateArgument::Pack)
2541 return true;
2542
2543 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2544 Args = Arg.pack_elements();
2545 ArgIdx = 0;
2546 return ArgIdx < Args.size();
2547}
2548
2549/// Determine whether the given set of template arguments has a pack
2550/// expansion that is not the last template argument.
2552 bool FoundPackExpansion = false;
2553 for (const auto &A : Args) {
2554 if (FoundPackExpansion)
2555 return true;
2556
2557 if (A.getKind() == TemplateArgument::Pack)
2558 return hasPackExpansionBeforeEnd(A.pack_elements());
2559
2560 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2561 // templates, it should not be treated as a pack expansion.
2562 if (A.isPackExpansion())
2563 FoundPackExpansion = true;
2564 }
2565
2566 return false;
2567}
2568
2575 bool NumberOfArgumentsMustMatch, PackFold PackFold) {
2576 if (PackFold == PackFold::ArgumentToParameter)
2577 std::swap(Ps, As);
2578 // C++0x [temp.deduct.type]p9:
2579 // If the template argument list of P contains a pack expansion that is not
2580 // the last template argument, the entire template argument list is a
2581 // non-deduced context.
2584
2585 // C++0x [temp.deduct.type]p9:
2586 // If P has a form that contains <T> or <i>, then each argument Pi of the
2587 // respective template argument list P is compared with the corresponding
2588 // argument Ai of the corresponding template argument list of A.
2589 unsigned ArgIdx = 0, ParamIdx = 0;
2591 const TemplateArgument &P = Ps[ParamIdx];
2592 if (!P.isPackExpansion()) {
2593 // The simple case: deduce template arguments by matching Pi and Ai.
2594
2595 // Check whether we have enough arguments.
2596 if (!hasTemplateArgumentForDeduction(As, ArgIdx))
2597 return NumberOfArgumentsMustMatch
2600
2601 // C++1z [temp.deduct.type]p9:
2602 // During partial ordering, if Ai was originally a pack expansion [and]
2603 // Pi is not a pack expansion, template argument deduction fails.
2604 if (As[ArgIdx].isPackExpansion())
2606
2607 // Perform deduction for this Pi/Ai pair.
2608 TemplateArgument Pi = P, Ai = As[ArgIdx];
2609 if (PackFold == PackFold::ArgumentToParameter)
2610 std::swap(Pi, Ai);
2611 if (auto Result =
2612 DeduceTemplateArguments(S, TemplateParams, Pi, Ai, Info, Deduced);
2614 return Result;
2615
2616 // Move to the next argument.
2617 ++ArgIdx;
2618 continue;
2619 }
2620
2621 // The parameter is a pack expansion.
2622
2623 // C++0x [temp.deduct.type]p9:
2624 // If Pi is a pack expansion, then the pattern of Pi is compared with
2625 // each remaining argument in the template argument list of A. Each
2626 // comparison deduces template arguments for subsequent positions in the
2627 // template parameter packs expanded by Pi.
2628 TemplateArgument Pattern = P.getPackExpansionPattern();
2629
2630 // Prepare to deduce the packs within the pattern.
2631 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2632
2633 // Keep track of the deduced template arguments for each parameter pack
2634 // expanded by this pack expansion (the outer index) and for each
2635 // template argument (the inner SmallVectors).
2636 for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
2637 PackScope.hasNextElement();
2638 ++ArgIdx) {
2639 TemplateArgument Pi = Pattern, Ai = As[ArgIdx];
2640 if (PackFold == PackFold::ArgumentToParameter)
2641 std::swap(Pi, Ai);
2642 // Deduce template arguments from the pattern.
2643 if (auto Result =
2644 DeduceTemplateArguments(S, TemplateParams, Pi, Ai, Info, Deduced);
2646 return Result;
2647
2648 PackScope.nextPackElement();
2649 }
2650
2651 // Build argument packs for each of the parameter packs expanded by this
2652 // pack expansion.
2653 if (auto Result = PackScope.finish();
2655 return Result;
2656 }
2657
2659}
2660
2665 bool NumberOfArgumentsMustMatch) {
2666 return ::DeduceTemplateArguments(*this, TemplateParams, Ps, As, Info, Deduced,
2667 NumberOfArgumentsMustMatch);
2668}
2669
2670/// Determine whether two template arguments are the same.
2671static bool isSameTemplateArg(ASTContext &Context,
2673 const TemplateArgument &Y,
2674 bool PartialOrdering,
2675 bool PackExpansionMatchesPack = false) {
2676 // If we're checking deduced arguments (X) against original arguments (Y),
2677 // we will have flattened packs to non-expansions in X.
2678 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2679 X = X.getPackExpansionPattern();
2680
2681 if (X.getKind() != Y.getKind())
2682 return false;
2683
2684 switch (X.getKind()) {
2686 llvm_unreachable("Comparing NULL template argument");
2687
2689 return Context.getCanonicalType(X.getAsType()) ==
2690 Context.getCanonicalType(Y.getAsType());
2691
2693 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
2694
2696 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2697
2700 return Context.getCanonicalTemplateName(
2701 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2704
2706 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2707
2709 return X.structurallyEquals(Y);
2710
2712 llvm::FoldingSetNodeID XID, YID;
2713 X.getAsExpr()->Profile(XID, Context, true);
2714 Y.getAsExpr()->Profile(YID, Context, true);
2715 return XID == YID;
2716 }
2717
2719 unsigned PackIterationSize = X.pack_size();
2720 if (X.pack_size() != Y.pack_size()) {
2721 if (!PartialOrdering)
2722 return false;
2723
2724 // C++0x [temp.deduct.type]p9:
2725 // During partial ordering, if Ai was originally a pack expansion:
2726 // - if P does not contain a template argument corresponding to Ai
2727 // then Ai is ignored;
2728 bool XHasMoreArg = X.pack_size() > Y.pack_size();
2729 if (!(XHasMoreArg && X.pack_elements().back().isPackExpansion()) &&
2730 !(!XHasMoreArg && Y.pack_elements().back().isPackExpansion()))
2731 return false;
2732
2733 if (XHasMoreArg)
2734 PackIterationSize = Y.pack_size();
2735 }
2736
2737 ArrayRef<TemplateArgument> XP = X.pack_elements();
2739 for (unsigned i = 0; i < PackIterationSize; ++i)
2740 if (!isSameTemplateArg(Context, XP[i], YP[i], PartialOrdering,
2741 PackExpansionMatchesPack))
2742 return false;
2743 return true;
2744 }
2745 }
2746
2747 llvm_unreachable("Invalid TemplateArgument Kind!");
2748}
2749
2752 QualType NTTPType, SourceLocation Loc,
2754 switch (Arg.getKind()) {
2756 llvm_unreachable("Can't get a NULL template argument here");
2757
2759 return TemplateArgumentLoc(
2761
2763 if (NTTPType.isNull())
2764 NTTPType = Arg.getParamTypeForDecl();
2767 .getAs<Expr>();
2769 }
2770
2772 if (NTTPType.isNull())
2773 NTTPType = Arg.getNullPtrType();
2775 .getAs<Expr>();
2776 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2777 E);
2778 }
2779
2784 }
2785
2791 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2792 else if (QualifiedTemplateName *QTN =
2793 Template.getAsQualifiedTemplateName())
2794 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2795
2797 return TemplateArgumentLoc(Context, Arg,
2798 Builder.getWithLocInContext(Context), Loc);
2799
2800 return TemplateArgumentLoc(
2801 Context, Arg, Builder.getWithLocInContext(Context), Loc, Loc);
2802 }
2803
2805 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2806
2809 }
2810
2811 llvm_unreachable("Invalid TemplateArgument Kind!");
2812}
2813
2816 SourceLocation Location) {
2818 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2819}
2820
2821/// Convert the given deduced template argument and add it to the set of
2822/// fully-converted template arguments.
2824 Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template,
2825 TemplateDeductionInfo &Info, bool IsDeduced,
2826 SmallVectorImpl<TemplateArgument> &SugaredOutput,
2827 SmallVectorImpl<TemplateArgument> &CanonicalOutput) {
2828 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2829 unsigned ArgumentPackIndex) {
2830 // Convert the deduced template argument into a template
2831 // argument that we can check, almost as if the user had written
2832 // the template argument explicitly.
2834 Arg, QualType(), Info.getLocation(), Param);
2835
2836 // Check the template argument, converting it as necessary.
2837 return S.CheckTemplateArgument(
2838 Param, ArgLoc, Template, Template->getLocation(),
2839 Template->getSourceRange().getEnd(), ArgumentPackIndex, SugaredOutput,
2840 CanonicalOutput,
2841 IsDeduced
2845 };
2846
2847 if (Arg.getKind() == TemplateArgument::Pack) {
2848 // This is a template argument pack, so check each of its arguments against
2849 // the template parameter.
2850 SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
2851 CanonicalPackedArgsBuilder;
2852 for (const auto &P : Arg.pack_elements()) {
2853 // When converting the deduced template argument, append it to the
2854 // general output list. We need to do this so that the template argument
2855 // checking logic has all of the prior template arguments available.
2856 DeducedTemplateArgument InnerArg(P);
2858 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2859 "deduced nested pack");
2860 if (P.isNull()) {
2861 // We deduced arguments for some elements of this pack, but not for
2862 // all of them. This happens if we get a conditionally-non-deduced
2863 // context in a pack expansion (such as an overload set in one of the
2864 // arguments).
2865 S.Diag(Param->getLocation(),
2866 diag::err_template_arg_deduced_incomplete_pack)
2867 << Arg << Param;
2868 return true;
2869 }
2870 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
2871 return true;
2872
2873 // Move the converted template argument into our argument pack.
2874 SugaredPackedArgsBuilder.push_back(SugaredOutput.pop_back_val());
2875 CanonicalPackedArgsBuilder.push_back(CanonicalOutput.pop_back_val());
2876 }
2877
2878 // If the pack is empty, we still need to substitute into the parameter
2879 // itself, in case that substitution fails.
2880 if (SugaredPackedArgsBuilder.empty()) {
2882 MultiLevelTemplateArgumentList Args(Template, SugaredOutput,
2883 /*Final=*/true);
2884
2885 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2886 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2887 NTTP, SugaredOutput,
2888 Template->getSourceRange());
2889 if (Inst.isInvalid() ||
2890 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2891 NTTP->getDeclName()).isNull())
2892 return true;
2893 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2894 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2895 TTP, SugaredOutput,
2896 Template->getSourceRange());
2897 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2898 return true;
2899 }
2900 // For type parameters, no substitution is ever required.
2901 }
2902
2903 // Create the resulting argument pack.
2904 SugaredOutput.push_back(
2905 TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
2906 CanonicalOutput.push_back(TemplateArgument::CreatePackCopy(
2907 S.Context, CanonicalPackedArgsBuilder));
2908 return false;
2909 }
2910
2911 return ConvertArg(Arg, 0);
2912}
2913
2914// FIXME: This should not be a template, but
2915// ClassTemplatePartialSpecializationDecl sadly does not derive from
2916// TemplateDecl.
2917template <typename TemplateDeclT>
2919 Sema &S, TemplateDeclT *Template, bool IsDeduced,
2922 SmallVectorImpl<TemplateArgument> &SugaredBuilder,
2923 SmallVectorImpl<TemplateArgument> &CanonicalBuilder,
2924 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2925 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2926 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2927
2928 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2929 NamedDecl *Param = TemplateParams->getParam(I);
2930
2931 // C++0x [temp.arg.explicit]p3:
2932 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2933 // be deduced to an empty sequence of template arguments.
2934 // FIXME: Where did the word "trailing" come from?
2935 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
2936 if (auto Result =
2937 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish();
2939 return Result;
2940 }
2941
2942 if (!Deduced[I].isNull()) {
2943 if (I < NumAlreadyConverted) {
2944 // We may have had explicitly-specified template arguments for a
2945 // template parameter pack (that may or may not have been extended
2946 // via additional deduced arguments).
2947 if (Param->isParameterPack() && CurrentInstantiationScope &&
2948 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2949 // Forget the partially-substituted pack; its substitution is now
2950 // complete.
2951 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2952 // We still need to check the argument in case it was extended by
2953 // deduction.
2954 } else {
2955 // We have already fully type-checked and converted this
2956 // argument, because it was explicitly-specified. Just record the
2957 // presence of this argument.
2958 SugaredBuilder.push_back(Deduced[I]);
2959 CanonicalBuilder.push_back(
2961 continue;
2962 }
2963 }
2964
2965 // We may have deduced this argument, so it still needs to be
2966 // checked and converted.
2967 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2968 IsDeduced, SugaredBuilder,
2969 CanonicalBuilder)) {
2970 Info.Param = makeTemplateParameter(Param);
2971 // FIXME: These template arguments are temporary. Free them!
2972 Info.reset(
2973 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
2974 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
2976 }
2977
2978 continue;
2979 }
2980
2981 // Substitute into the default template argument, if available.
2982 bool HasDefaultArg = false;
2983 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2984 if (!TD) {
2985 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2986 isa<VarTemplatePartialSpecializationDecl>(Template));
2988 }
2989
2990 TemplateArgumentLoc DefArg;
2991 {
2992 Qualifiers ThisTypeQuals;
2993 CXXRecordDecl *ThisContext = nullptr;
2994 if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
2995 if (Rec->isLambda())
2996 if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
2997 ThisContext = Method->getParent();
2998 ThisTypeQuals = Method->getMethodQualifiers();
2999 }
3000
3001 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
3002 S.getLangOpts().CPlusPlus17);
3003
3005 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param,
3006 SugaredBuilder, CanonicalBuilder, HasDefaultArg);
3007 }
3008
3009 // If there was no default argument, deduction is incomplete.
3010 if (DefArg.getArgument().isNull()) {
3012 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
3013 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3014 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3015 if (PartialOverloading) break;
3016
3019 }
3020
3021 // Check whether we can actually use the default argument.
3023 Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
3024 0, SugaredBuilder, CanonicalBuilder, Sema::CTAK_Specified)) {
3026 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
3027 // FIXME: These template arguments are temporary. Free them!
3028 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3029 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3031 }
3032
3033 // If we get here, we successfully used the default template argument.
3034 }
3035
3037}
3038
3040 if (auto *DC = dyn_cast<DeclContext>(D))
3041 return DC;
3042 return D->getDeclContext();
3043}
3044
3045template<typename T> struct IsPartialSpecialization {
3046 static constexpr bool value = false;
3047};
3048template<>
3050 static constexpr bool value = true;
3051};
3052template<>
3054 static constexpr bool value = true;
3055};
3056template <typename TemplateDeclT>
3057static bool DeducedArgsNeedReplacement(TemplateDeclT *Template) {
3058 return false;
3059}
3060template <>
3063 return !Spec->isClassScopeExplicitSpecialization();
3064}
3065template <>
3068 return !Spec->isClassScopeExplicitSpecialization();
3069}
3070
3071template <typename TemplateDeclT>
3073CheckDeducedArgumentConstraints(Sema &S, TemplateDeclT *Template,
3074 ArrayRef<TemplateArgument> SugaredDeducedArgs,
3075 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
3076 TemplateDeductionInfo &Info) {
3077 llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
3078 Template->getAssociatedConstraints(AssociatedConstraints);
3079
3080 std::optional<ArrayRef<TemplateArgument>> Innermost;
3081 // If we don't need to replace the deduced template arguments,
3082 // we can add them immediately as the inner-most argument list.
3083 if (!DeducedArgsNeedReplacement(Template))
3084 Innermost = CanonicalDeducedArgs;
3085
3087 Template, Template->getDeclContext(), /*Final=*/false, Innermost,
3088 /*RelativeToPrimary=*/true, /*Pattern=*/
3089 nullptr, /*ForConstraintInstantiation=*/true);
3090
3091 // getTemplateInstantiationArgs picks up the non-deduced version of the
3092 // template args when this is a variable template partial specialization and
3093 // not class-scope explicit specialization, so replace with Deduced Args
3094 // instead of adding to inner-most.
3095 if (!Innermost)
3096 MLTAL.replaceInnermostTemplateArguments(Template, CanonicalDeducedArgs);
3097
3098 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
3099 Info.getLocation(),
3102 Info.reset(
3103 TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
3104 TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
3106 }
3108}
3109
3110/// Complete template argument deduction for a partial specialization.
3111template <typename T>
3112static std::enable_if_t<IsPartialSpecialization<T>::value,
3115 Sema &S, T *Partial, bool IsPartialOrdering,
3116 ArrayRef<TemplateArgument> TemplateArgs,
3118 TemplateDeductionInfo &Info) {
3119 // Unevaluated SFINAE context.
3122 Sema::SFINAETrap Trap(S);
3123
3124 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
3125
3126 // C++ [temp.deduct.type]p2:
3127 // [...] or if any template argument remains neither deduced nor
3128 // explicitly specified, template argument deduction fails.
3129 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3131 S, Partial, IsPartialOrdering, Deduced, Info, SugaredBuilder,
3132 CanonicalBuilder);
3134 return Result;
3135
3136 // Form the template argument list from the deduced template arguments.
3137 TemplateArgumentList *SugaredDeducedArgumentList =
3138 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
3139 TemplateArgumentList *CanonicalDeducedArgumentList =
3140 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
3141
3142 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3143
3144 // Substitute the deduced template arguments into the template
3145 // arguments of the class template partial specialization, and
3146 // verify that the instantiated template arguments are both valid
3147 // and are equivalent to the template arguments originally provided
3148 // to the class template.
3149 LocalInstantiationScope InstScope(S);
3150 auto *Template = Partial->getSpecializedTemplate();
3151 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
3152 Partial->getTemplateArgsAsWritten();
3153
3154 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
3155 PartialTemplArgInfo->RAngleLoc);
3156
3157 if (S.SubstTemplateArguments(PartialTemplArgInfo->arguments(),
3159 SugaredBuilder,
3160 /*Final=*/true),
3161 InstArgs)) {
3162 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
3163 if (ParamIdx >= Partial->getTemplateParameters()->size())
3164 ParamIdx = Partial->getTemplateParameters()->size() - 1;
3165
3166 Decl *Param = const_cast<NamedDecl *>(
3167 Partial->getTemplateParameters()->getParam(ParamIdx));
3168 Info.Param = makeTemplateParameter(Param);
3169 Info.FirstArg = (*PartialTemplArgInfo)[ArgIdx].getArgument();
3171 }
3172
3174 SmallVector<TemplateArgument, 4> SugaredConvertedInstArgs,
3175 CanonicalConvertedInstArgs;
3177 Template, Partial->getLocation(), InstArgs, false,
3178 SugaredConvertedInstArgs, CanonicalConvertedInstArgs,
3179 /*UpdateArgsWithConversions=*/true, &ConstraintsNotSatisfied))
3183
3184 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3185 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3186 TemplateArgument InstArg = SugaredConvertedInstArgs.data()[I];
3187 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
3188 IsPartialOrdering)) {
3189 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3190 Info.FirstArg = TemplateArgs[I];
3191 Info.SecondArg = InstArg;
3193 }
3194 }
3195
3196 if (Trap.hasErrorOccurred())
3198
3199 if (auto Result = CheckDeducedArgumentConstraints(S, Partial, SugaredBuilder,
3200 CanonicalBuilder, Info);
3202 return Result;
3203
3205}
3206
3207/// Complete template argument deduction for a class or variable template,
3208/// when partial ordering against a partial specialization.
3209// FIXME: Factor out duplication with partial specialization version above.
3211 Sema &S, TemplateDecl *Template, bool PartialOrdering,
3212 ArrayRef<TemplateArgument> TemplateArgs,
3214 TemplateDeductionInfo &Info) {
3215 // Unevaluated SFINAE context.
3218 Sema::SFINAETrap Trap(S);
3219
3220 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
3221
3222 // C++ [temp.deduct.type]p2:
3223 // [...] or if any template argument remains neither deduced nor
3224 // explicitly specified, template argument deduction fails.
3225 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3227 S, Template, /*IsDeduced*/ PartialOrdering, Deduced, Info,
3228 SugaredBuilder, CanonicalBuilder,
3229 /*CurrentInstantiationScope=*/nullptr,
3230 /*NumAlreadyConverted=*/0U, /*PartialOverloading=*/false);
3232 return Result;
3233
3234 // Check that we produced the correct argument list.
3235 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3236 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3237 TemplateArgument InstArg = CanonicalBuilder[I];
3238 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg, PartialOrdering,
3239 /*PackExpansionMatchesPack=*/true)) {
3240 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3241 Info.FirstArg = TemplateArgs[I];
3242 Info.SecondArg = InstArg;
3244 }
3245 }
3246
3247 if (Trap.hasErrorOccurred())
3249
3250 if (auto Result = CheckDeducedArgumentConstraints(S, Template, SugaredBuilder,
3251 CanonicalBuilder, Info);
3253 return Result;
3254
3256}
3257/// Complete template argument deduction for DeduceTemplateArgumentsFromType.
3258/// FIXME: this is mostly duplicated with the above two versions. Deduplicate
3259/// the three implementations.
3261 Sema &S, TemplateDecl *TD,
3263 TemplateDeductionInfo &Info) {
3264 // Unevaluated SFINAE context.
3267 Sema::SFINAETrap Trap(S);
3268
3270
3271 // C++ [temp.deduct.type]p2:
3272 // [...] or if any template argument remains neither deduced nor
3273 // explicitly specified, template argument deduction fails.
3274 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3276 S, TD, /*IsPartialOrdering=*/false, Deduced, Info, SugaredBuilder,
3277 CanonicalBuilder);
3279 return Result;
3280
3281 if (Trap.hasErrorOccurred())
3283
3284 if (auto Result = CheckDeducedArgumentConstraints(S, TD, SugaredBuilder,
3285 CanonicalBuilder, Info);
3287 return Result;
3288
3290}
3291
3292/// Perform template argument deduction to determine whether the given template
3293/// arguments match the given class or variable template partial specialization
3294/// per C++ [temp.class.spec.match].
3295template <typename T>
3296static std::enable_if_t<IsPartialSpecialization<T>::value,
3299 ArrayRef<TemplateArgument> TemplateArgs,
3300 TemplateDeductionInfo &Info) {
3301 if (Partial->isInvalidDecl())
3303
3304 // C++ [temp.class.spec.match]p2:
3305 // A partial specialization matches a given actual template
3306 // argument list if the template arguments of the partial
3307 // specialization can be deduced from the actual template argument
3308 // list (14.8.2).
3309
3310 // Unevaluated SFINAE context.
3313 Sema::SFINAETrap Trap(S);
3314
3315 // This deduction has no relation to any outer instantiation we might be
3316 // performing.
3317 LocalInstantiationScope InstantiationScope(S);
3318
3320 Deduced.resize(Partial->getTemplateParameters()->size());
3322 S, Partial->getTemplateParameters(),
3323 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3324 /*NumberOfArgumentsMustMatch=*/false);
3326 return Result;
3327
3328 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3329 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs,
3330 Info);
3331 if (Inst.isInvalid())
3333
3334 if (Trap.hasErrorOccurred())
3336
3339 Result = ::FinishTemplateArgumentDeduction(S, Partial,
3340 /*IsPartialOrdering=*/false,
3341 TemplateArgs, Deduced, Info);
3342 });
3343 return Result;
3344}
3345
3348 ArrayRef<TemplateArgument> TemplateArgs,
3349 TemplateDeductionInfo &Info) {
3350 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3351}
3354 ArrayRef<TemplateArgument> TemplateArgs,
3355 TemplateDeductionInfo &Info) {
3356 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3357}
3358
3362 if (TD->isInvalidDecl())
3364
3365 QualType PType;
3366 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
3367 // Use the InjectedClassNameType.
3368 PType = Context.getTypeDeclType(CTD->getTemplatedDecl());
3369 } else if (const auto *AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(TD)) {
3370 PType = AliasTemplate->getTemplatedDecl()
3371 ->getUnderlyingType()
3372 .getCanonicalType();
3373 } else {
3374 assert(false && "Expected a class or alias template");
3375 }
3376
3377 // Unevaluated SFINAE context.
3380 SFINAETrap Trap(*this);
3381
3382 // This deduction has no relation to any outer instantiation we might be
3383 // performing.
3384 LocalInstantiationScope InstantiationScope(*this);
3385
3387 TD->getTemplateParameters()->size());
3390 if (auto DeducedResult = DeduceTemplateArguments(
3391 TD->getTemplateParameters(), PArgs, AArgs, Info, Deduced, false);
3392 DeducedResult != TemplateDeductionResult::Success) {
3393 return DeducedResult;
3394 }
3395
3396 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3397 InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs, Info);
3398 if (Inst.isInvalid())
3400
3401 if (Trap.hasErrorOccurred())
3403
3406 Result = ::FinishTemplateArgumentDeduction(*this, TD, Deduced, Info);
3407 });
3408 return Result;
3409}
3410
3411/// Determine whether the given type T is a simple-template-id type.
3413 if (const TemplateSpecializationType *Spec
3415 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
3416
3417 // C++17 [temp.local]p2:
3418 // the injected-class-name [...] is equivalent to the template-name followed
3419 // by the template-arguments of the class template specialization or partial
3420 // specialization enclosed in <>
3421 // ... which means it's equivalent to a simple-template-id.
3422 //
3423 // This only arises during class template argument deduction for a copy
3424 // deduction candidate, where it permits slicing.
3426 return true;
3427
3428 return false;
3429}
3430
3432 FunctionTemplateDecl *FunctionTemplate,
3433 TemplateArgumentListInfo &ExplicitTemplateArgs,
3436 TemplateDeductionInfo &Info) {
3437 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3438 TemplateParameterList *TemplateParams
3439 = FunctionTemplate->getTemplateParameters();
3440
3441 if (ExplicitTemplateArgs.size() == 0) {
3442 // No arguments to substitute; just copy over the parameter types and
3443 // fill in the function type.
3444 for (auto *P : Function->parameters())
3445 ParamTypes.push_back(P->getType());
3446
3447 if (FunctionType)
3448 *FunctionType = Function->getType();
3450 }
3451
3452 // Unevaluated SFINAE context.
3455 SFINAETrap Trap(*this);
3456
3457 // C++ [temp.arg.explicit]p3:
3458 // Template arguments that are present shall be specified in the
3459 // declaration order of their corresponding template-parameters. The
3460 // template argument list shall not specify more template-arguments than
3461 // there are corresponding template-parameters.
3462 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3463
3464 // Enter a new template instantiation context where we check the
3465 // explicitly-specified template arguments against this function template,
3466 // and then substitute them into the function parameter types.
3469 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3471 if (Inst.isInvalid())
3473
3475 ExplicitTemplateArgs, true, SugaredBuilder,
3476 CanonicalBuilder,
3477 /*UpdateArgsWithConversions=*/false) ||
3478 Trap.hasErrorOccurred()) {
3479 unsigned Index = SugaredBuilder.size();
3480 if (Index >= TemplateParams->size())
3482 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3484 }
3485
3486 // Form the template argument list from the explicitly-specified
3487 // template arguments.
3488 TemplateArgumentList *SugaredExplicitArgumentList =
3490 TemplateArgumentList *CanonicalExplicitArgumentList =
3491 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3492 Info.setExplicitArgs(SugaredExplicitArgumentList,
3493 CanonicalExplicitArgumentList);
3494
3495 // Template argument deduction and the final substitution should be
3496 // done in the context of the templated declaration. Explicit
3497 // argument substitution, on the other hand, needs to happen in the
3498 // calling context.
3499 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3500
3501 // If we deduced template arguments for a template parameter pack,
3502 // note that the template argument pack is partially substituted and record
3503 // the explicit template arguments. They'll be used as part of deduction
3504 // for this template parameter pack.
3505 unsigned PartiallySubstitutedPackIndex = -1u;
3506 if (!CanonicalBuilder.empty()) {
3507 const TemplateArgument &Arg = CanonicalBuilder.back();
3508 if (Arg.getKind() == TemplateArgument::Pack) {
3509 auto *Param = TemplateParams->getParam(CanonicalBuilder.size() - 1);
3510 // If this is a fully-saturated fixed-size pack, it should be
3511 // fully-substituted, not partially-substituted.
3512 std::optional<unsigned> Expansions = getExpandedPackSize(Param);
3513 if (!Expansions || Arg.pack_size() < *Expansions) {
3514 PartiallySubstitutedPackIndex = CanonicalBuilder.size() - 1;
3516 Param, Arg.pack_begin(), Arg.pack_size());
3517 }
3518 }
3519 }
3520
3521 const FunctionProtoType *Proto
3522 = Function->getType()->getAs<FunctionProtoType>();
3523 assert(Proto && "Function template does not have a prototype?");
3524
3525 // Isolate our substituted parameters from our caller.
3526 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3527
3528 ExtParameterInfoBuilder ExtParamInfos;
3529
3531 SugaredExplicitArgumentList->asArray(),
3532 /*Final=*/true);
3533
3534 // Instantiate the types of each of the function parameters given the
3535 // explicitly-specified template arguments. If the function has a trailing
3536 // return type, substitute it after the arguments to ensure we substitute
3537 // in lexical order.
3538 if (Proto->hasTrailingReturn()) {
3539 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3540 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3541 /*params=*/nullptr, ExtParamInfos))
3543 }
3544
3545 // Instantiate the return type.
3546 QualType ResultType;
3547 {
3548 // C++11 [expr.prim.general]p3:
3549 // If a declaration declares a member function or member function
3550 // template of a class X, the expression this is a prvalue of type
3551 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3552 // and the end of the function-definition, member-declarator, or
3553 // declarator.
3554 Qualifiers ThisTypeQuals;
3555 CXXRecordDecl *ThisContext = nullptr;
3556 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3557 ThisContext = Method->getParent();
3558 ThisTypeQuals = Method->getMethodQualifiers();
3559 }
3560
3561 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3563
3564 ResultType =
3565 SubstType(Proto->getReturnType(), MLTAL,
3566 Function->getTypeSpecStartLoc(), Function->getDeclName());
3567 if (ResultType.isNull() || Trap.hasErrorOccurred())
3569 // CUDA: Kernel function must have 'void' return type.
3570 if (getLangOpts().CUDA)
3571 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3572 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3573 << Function->getType() << Function->getSourceRange();
3575 }
3576 }
3577
3578 // Instantiate the types of each of the function parameters given the
3579 // explicitly-specified template arguments if we didn't do so earlier.
3580 if (!Proto->hasTrailingReturn() &&
3581 SubstParmTypes(Function->getLocation(), Function->parameters(),
3582 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3583 /*params*/ nullptr, ExtParamInfos))
3585
3586 if (FunctionType) {
3587 auto EPI = Proto->getExtProtoInfo();
3588 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3589 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3590 Function->getLocation(),
3591 Function->getDeclName(),
3592 EPI);
3593 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3595 }
3596
3597 // C++ [temp.arg.explicit]p2:
3598 // Trailing template arguments that can be deduced (14.8.2) may be
3599 // omitted from the list of explicit template-arguments. If all of the
3600 // template arguments can be deduced, they may all be omitted; in this
3601 // case, the empty template argument list <> itself may also be omitted.
3602 //
3603 // Take all of the explicitly-specified arguments and put them into
3604 // the set of deduced template arguments. The partially-substituted
3605 // parameter pack, however, will be set to NULL since the deduction
3606 // mechanism handles the partially-substituted argument pack directly.
3607 Deduced.reserve(TemplateParams->size());
3608 for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3609 const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
3610 if (I == PartiallySubstitutedPackIndex)
3611 Deduced.push_back(DeducedTemplateArgument());
3612 else
3613 Deduced.push_back(Arg);
3614 }
3615
3617}
3618
3619/// Check whether the deduced argument type for a call to a function
3620/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3623 Sema::OriginalCallArg OriginalArg,
3624 QualType DeducedA) {
3625 ASTContext &Context = S.Context;
3626
3627 auto Failed = [&]() -> TemplateDeductionResult {
3628 Info.FirstArg = TemplateArgument(DeducedA);
3629 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3630 Info.CallArgIndex = OriginalArg.ArgIdx;
3631 return OriginalArg.DecomposedParam
3634 };
3635
3636 QualType A = OriginalArg.OriginalArgType;
3637 QualType OriginalParamType = OriginalArg.OriginalParamType;
3638
3639 // Check for type equality (top-level cv-qualifiers are ignored).
3640 if (Context.hasSameUnqualifiedType(A, DeducedA))
3642
3643 // Strip off references on the argument types; they aren't needed for
3644 // the following checks.
3645 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3646 DeducedA = DeducedARef->getPointeeType();
3647 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3648 A = ARef->getPointeeType();
3649
3650 // C++ [temp.deduct.call]p4:
3651 // [...] However, there are three cases that allow a difference:
3652 // - If the original P is a reference type, the deduced A (i.e., the
3653 // type referred to by the reference) can be more cv-qualified than
3654 // the transformed A.
3655 if (const ReferenceType *OriginalParamRef
3656 = OriginalParamType->getAs<ReferenceType>()) {
3657 // We don't want to keep the reference around any more.
3658 OriginalParamType = OriginalParamRef->getPointeeType();
3659
3660 // FIXME: Resolve core issue (no number yet): if the original P is a
3661 // reference type and the transformed A is function type "noexcept F",
3662 // the deduced A can be F.
3663 QualType Tmp;
3664 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
3666
3667 Qualifiers AQuals = A.getQualifiers();
3668 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3669
3670 // Under Objective-C++ ARC, the deduced type may have implicitly
3671 // been given strong or (when dealing with a const reference)
3672 // unsafe_unretained lifetime. If so, update the original
3673 // qualifiers to include this lifetime.
3674 if (S.getLangOpts().ObjCAutoRefCount &&
3675 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3677 (DeducedAQuals.hasConst() &&
3678 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3679 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3680 }
3681
3682 if (AQuals == DeducedAQuals) {
3683 // Qualifiers match; there's nothing to do.
3684 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
3685 return Failed();
3686 } else {
3687 // Qualifiers are compatible, so have the argument type adopt the
3688 // deduced argument type's qualifiers as if we had performed the
3689 // qualification conversion.
3690 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3691 }
3692 }
3693
3694 // - The transformed A can be another pointer or pointer to member
3695 // type that can be converted to the deduced A via a function pointer
3696 // conversion and/or a qualification conversion.
3697 //
3698 // Also allow conversions which merely strip __attribute__((noreturn)) from
3699 // function types (recursively).
3700 bool ObjCLifetimeConversion = false;
3701 QualType ResultTy;
3702 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3703 (S.IsQualificationConversion(A, DeducedA, false,
3704 ObjCLifetimeConversion) ||
3705 S.IsFunctionConversion(A, DeducedA, ResultTy)))
3707
3708 // - If P is a class and P has the form simple-template-id, then the
3709 // transformed A can be a derived class of the deduced A. [...]
3710 // [...] Likewise, if P is a pointer to a class of the form
3711 // simple-template-id, the transformed A can be a pointer to a
3712 // derived class pointed to by the deduced A.
3713 if (const PointerType *OriginalParamPtr
3714 = OriginalParamType->getAs<PointerType>()) {
3715 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3716 if (const PointerType *APtr = A->getAs<PointerType>()) {
3717 if (A->getPointeeType()->isRecordType()) {
3718 OriginalParamType = OriginalParamPtr->getPointeeType();
3719 DeducedA = DeducedAPtr->getPointeeType();
3720 A = APtr->getPointeeType();
3721 }
3722 }
3723 }
3724 }
3725
3726 if (Context.hasSameUnqualifiedType(A, DeducedA))
3728
3729 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3730 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3732
3733 return Failed();
3734}
3735
3736/// Find the pack index for a particular parameter index in an instantiation of
3737/// a function template with specific arguments.
3738///
3739/// \return The pack index for whichever pack produced this parameter, or -1
3740/// if this was not produced by a parameter. Intended to be used as the
3741/// ArgumentPackSubstitutionIndex for further substitutions.
3742// FIXME: We should track this in OriginalCallArgs so we don't need to
3743// reconstruct it here.
3744static unsigned getPackIndexForParam(Sema &S,
3745 FunctionTemplateDecl *FunctionTemplate,
3747 unsigned ParamIdx) {
3748 unsigned Idx = 0;
3749 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3750 if (PD->isParameterPack()) {
3751 unsigned NumExpansions =
3752 S.getNumArgumentsInExpansion(PD->getType(), Args).value_or(1);
3753 if (Idx + NumExpansions > ParamIdx)
3754 return ParamIdx - Idx;
3755 Idx += NumExpansions;
3756 } else {
3757 if (Idx == ParamIdx)
3758 return -1; // Not a pack expansion
3759 ++Idx;
3760 }
3761 }
3762
3763 llvm_unreachable("parameter index would not be produced from template");
3764}
3765
3766// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`,
3767// we'll try to instantiate and update its explicit specifier after constraint
3768// checking.
3771 const MultiLevelTemplateArgumentList &SubstArgs,
3772 TemplateDeductionInfo &Info, FunctionTemplateDecl *FunctionTemplate,
3773 ArrayRef<TemplateArgument> DeducedArgs) {
3774 auto GetExplicitSpecifier = [](FunctionDecl *D) {
3775 return isa<CXXConstructorDecl>(D)
3776 ? cast<CXXConstructorDecl>(D)->getExplicitSpecifier()
3777 : cast<CXXConversionDecl>(D)->getExplicitSpecifier();
3778 };
3779 auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) {
3780 isa<CXXConstructorDecl>(D)
3781 ? cast<CXXConstructorDecl>(D)->setExplicitSpecifier(ES)
3782 : cast<CXXConversionDecl>(D)->setExplicitSpecifier(ES);
3783 };
3784
3785 ExplicitSpecifier ES = GetExplicitSpecifier(Specialization);
3786 Expr *ExplicitExpr = ES.getExpr();
3787 if (!ExplicitExpr)
3789 if (!ExplicitExpr->isValueDependent())
3791
3793 S, Info.getLocation(), FunctionTemplate, DeducedArgs,
3795 if (Inst.isInvalid())
3797 Sema::SFINAETrap Trap(S);
3798 const ExplicitSpecifier InstantiatedES =
3799 S.instantiateExplicitSpecifier(SubstArgs, ES);
3800 if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) {
3801 Specialization->setInvalidDecl(true);
3803 }
3804 SetExplicitSpecifier(Specialization, InstantiatedES);
3806}
3807
3809 FunctionTemplateDecl *FunctionTemplate,
3811 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3813 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3814 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
3815 // Unevaluated SFINAE context.
3818 SFINAETrap Trap(*this);
3819
3820 // Enter a new template instantiation context while we instantiate the
3821 // actual function declaration.
3822 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3824 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3826 if (Inst.isInvalid())
3828
3829 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3830
3831 // C++ [temp.deduct.type]p2:
3832 // [...] or if any template argument remains neither deduced nor
3833 // explicitly specified, template argument deduction fails.
3834 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3836 *this, FunctionTemplate, /*IsDeduced*/ true, Deduced, Info,
3837 SugaredBuilder, CanonicalBuilder, CurrentInstantiationScope,
3838 NumExplicitlySpecified, PartialOverloading);
3840 return Result;
3841
3842 // C++ [temp.deduct.call]p10: [DR1391]
3843 // If deduction succeeds for all parameters that contain
3844 // template-parameters that participate in template argument deduction,
3845 // and all template arguments are explicitly specified, deduced, or
3846 // obtained from default template arguments, remaining parameters are then
3847 // compared with the corresponding arguments. For each remaining parameter
3848 // P with a type that was non-dependent before substitution of any
3849 // explicitly-specified template arguments, if the corresponding argument
3850 // A cannot be implicitly converted to P, deduction fails.
3851 if (CheckNonDependent())
3853
3854 // Form the template argument list from the deduced template arguments.
3855 TemplateArgumentList *SugaredDeducedArgumentList =
3857 TemplateArgumentList *CanonicalDeducedArgumentList =
3858 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3859 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3860
3861 // Substitute the deduced template arguments into the function template
3862 // declaration to produce the function template specialization.
3863 DeclContext *Owner = FunctionTemplate->getDeclContext();
3864 if (FunctionTemplate->getFriendObjectKind())
3865 Owner = FunctionTemplate->getLexicalDeclContext();
3866 FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
3867 // additional check for inline friend,
3868 // ```
3869 // template <class F1> int foo(F1 X);
3870 // template <int A1> struct A {
3871 // template <class F1> friend int foo(F1 X) { return A1; }
3872 // };
3873 // template struct A<1>;
3874 // int a = foo(1.0);
3875 // ```
3876 const FunctionDecl *FDFriend;
3878 FD->isDefined(FDFriend, /*CheckForPendingFriendDefinition*/ true) &&
3880 FD = const_cast<FunctionDecl *>(FDFriend);
3881 Owner = FD->getLexicalDeclContext();
3882 }
3884 FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
3885 /*Final=*/false);
3886 Specialization = cast_or_null<FunctionDecl>(
3887 SubstDecl(FD, Owner, SubstArgs));
3888 if (!Specialization || Specialization->isInvalidDecl())
3890
3891 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
3892 FunctionTemplate->getCanonicalDecl());
3893
3894 // If the template argument list is owned by the function template
3895 // specialization, release it.
3896 if (Specialization->getTemplateSpecializationArgs() ==
3897 CanonicalDeducedArgumentList &&
3898 !Trap.hasErrorOccurred())
3899 Info.takeCanonical();
3900
3901 // There may have been an error that did not prevent us from constructing a
3902 // declaration. Mark the declaration invalid and return with a substitution
3903 // failure.
3904 if (Trap.hasErrorOccurred()) {
3905 Specialization->setInvalidDecl(true);
3907 }
3908
3909 // C++2a [temp.deduct]p5
3910 // [...] When all template arguments have been deduced [...] all uses of
3911 // template parameters [...] are replaced with the corresponding deduced
3912 // or default argument values.
3913 // [...] If the function template has associated constraints
3914 // ([temp.constr.decl]), those constraints are checked for satisfaction
3915 // ([temp.constr.constr]). If the constraints are not satisfied, type
3916 // deduction fails.
3917 if (!PartialOverloading ||
3918 (CanonicalBuilder.size() ==
3919 FunctionTemplate->getTemplateParameters()->size())) {
3921 Info.getLocation(), Specialization, CanonicalBuilder,
3924
3926 Info.reset(Info.takeSugared(),
3927 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder));
3929 }
3930 }
3931
3932 // We skipped the instantiation of the explicit-specifier during the
3933 // substitution of `FD` before. So, we try to instantiate it back if
3934 // `Specialization` is either a constructor or a conversion function.
3935 if (isa<CXXConstructorDecl, CXXConversionDecl>(Specialization)) {
3938 Info, FunctionTemplate,
3939 DeducedArgs)) {
3941 }
3942 }
3943
3944 if (OriginalCallArgs) {
3945 // C++ [temp.deduct.call]p4:
3946 // In general, the deduction process attempts to find template argument
3947 // values that will make the deduced A identical to A (after the type A
3948 // is transformed as described above). [...]
3949 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
3950 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3951 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
3952
3953 auto ParamIdx = OriginalArg.ArgIdx;
3954 unsigned ExplicitOffset =
3955 Specialization->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
3956 if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset)
3957 // FIXME: This presumably means a pack ended up smaller than we
3958 // expected while deducing. Should this not result in deduction
3959 // failure? Can it even happen?
3960 continue;
3961
3962 QualType DeducedA;
3963 if (!OriginalArg.DecomposedParam) {
3964 // P is one of the function parameters, just look up its substituted
3965 // type.
3966 DeducedA =
3967 Specialization->getParamDecl(ParamIdx + ExplicitOffset)->getType();
3968 } else {
3969 // P is a decomposed element of a parameter corresponding to a
3970 // braced-init-list argument. Substitute back into P to find the
3971 // deduced A.
3972 QualType &CacheEntry =
3973 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3974 if (CacheEntry.isNull()) {
3976 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3977 ParamIdx));
3978 CacheEntry =
3979 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3980 Specialization->getTypeSpecStartLoc(),
3981 Specialization->getDeclName());
3982 }
3983 DeducedA = CacheEntry;
3984 }
3985
3986 if (auto TDK =
3987 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
3989 return TDK;
3990 }
3991 }
3992
3993 // If we suppressed any diagnostics while performing template argument
3994 // deduction, and if we haven't already instantiated this declaration,
3995 // keep track of these diagnostics. They'll be emitted if this specialization
3996 // is actually used.
3997 if (Info.diag_begin() != Info.diag_end()) {
3998 SuppressedDiagnosticsMap::iterator
3999 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
4000 if (Pos == SuppressedDiagnostics.end())
4001 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
4002 .append(Info.diag_begin(), Info.diag_end());
4003 }
4004
4006}
4007
4008/// Gets the type of a function for template-argument-deducton
4009/// purposes when it's considered as part of an overload set.
4011 FunctionDecl *Fn) {
4012 // We may need to deduce the return type of the function now.
4013 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
4014 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
4015 return {};
4016
4017 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
4018 if (Method->isImplicitObjectMemberFunction()) {
4019 // An instance method that's referenced in a form that doesn't
4020 // look like a member pointer is just invalid.
4022 return {};
4023
4024 return S.Context.getMemberPointerType(Fn->getType(),
4025 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
4026 }
4027
4028 if (!R.IsAddressOfOperand) return Fn->getType();
4029 return S.Context.getPointerType(Fn->getType());
4030}
4031
4032/// Apply the deduction rules for overload sets.
4033///
4034/// \return the null type if this argument should be treated as an
4035/// undeduced context
4036static QualType
4038 Expr *Arg, QualType ParamType,
4039 bool ParamWasReference,
4040 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4041
4043
4044 OverloadExpr *Ovl = R.Expression;
4045
4046 // C++0x [temp.deduct.call]p4
4047 unsigned TDF = 0;
4048 if (ParamWasReference)
4050 if (R.IsAddressOfOperand)
4051 TDF |= TDF_IgnoreQualifiers;
4052
4053 // C++0x [temp.deduct.call]p6:
4054 // When P is a function type, pointer to function type, or pointer
4055 // to member function type:
4056
4057 if (!ParamType->isFunctionType() &&
4058 !ParamType->isFunctionPointerType() &&
4059 !ParamType->isMemberFunctionPointerType()) {
4060 if (Ovl->hasExplicitTemplateArgs()) {
4061 // But we can still look for an explicit specialization.
4062 if (FunctionDecl *ExplicitSpec =
4064 Ovl, /*Complain=*/false,
4065 /*FoundDeclAccessPair=*/nullptr, FailedTSC))
4066 return GetTypeOfFunction(S, R, ExplicitSpec);
4067 }
4068
4069 DeclAccessPair DAP;
4070 if (FunctionDecl *Viable =
4072 return GetTypeOfFunction(S, R, Viable);
4073
4074 return {};
4075 }
4076
4077 // Gather the explicit template arguments, if any.
4078 TemplateArgumentListInfo ExplicitTemplateArgs;
4079 if (Ovl->hasExplicitTemplateArgs())
4080 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4081 QualType Match;
4082 for (UnresolvedSetIterator I = Ovl->decls_begin(),
4083 E = Ovl->decls_end(); I != E; ++I) {
4084 NamedDecl *D = (*I)->getUnderlyingDecl();
4085
4086 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
4087 // - If the argument is an overload set containing one or more
4088 // function templates, the parameter is treated as a
4089 // non-deduced context.
4090 if (!Ovl->hasExplicitTemplateArgs())
4091 return {};
4092
4093 // Otherwise, see if we can resolve a function type
4094 FunctionDecl *Specialization = nullptr;
4095 TemplateDeductionInfo Info(Ovl->getNameLoc());
4096 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
4099 continue;
4100
4101 D = Specialization;
4102 }
4103
4104 FunctionDecl *Fn = cast<FunctionDecl>(D);
4105 QualType ArgType = GetTypeOfFunction(S, R, Fn);
4106 if (ArgType.isNull()) continue;
4107
4108 // Function-to-pointer conversion.
4109 if (!ParamWasReference && ParamType->isPointerType() &&
4110 ArgType->isFunctionType())
4111 ArgType = S.Context.getPointerType(ArgType);
4112
4113 // - If the argument is an overload set (not containing function
4114 // templates), trial argument deduction is attempted using each
4115 // of the members of the set. If deduction succeeds for only one
4116 // of the overload set members, that member is used as the
4117 // argument value for the deduction. If deduction succeeds for
4118 // more than one member of the overload set the parameter is
4119 // treated as a non-deduced context.
4120
4121 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
4122 // Type deduction is done independently for each P/A pair, and
4123 // the deduced template argument values are then combined.
4124 // So we do not reject deductions which were made elsewhere.
4126 Deduced(TemplateParams->size());
4127 TemplateDeductionInfo Info(Ovl->getNameLoc());
4129 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF);
4131 continue;
4132 if (!Match.isNull())
4133 return {};
4134 Match = ArgType;
4135 }
4136
4137 return Match;
4138}
4139
4140/// Perform the adjustments to the parameter and argument types
4141/// described in C++ [temp.deduct.call].
4142///
4143/// \returns true if the caller should not attempt to perform any template
4144/// argument deduction based on this P/A pair because the argument is an
4145/// overloaded function set that could not be resolved.
4147 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4148 QualType &ParamType, QualType &ArgType,
4149 Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
4150 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4151 // C++0x [temp.deduct.call]p3:
4152 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
4153 // are ignored for type deduction.
4154 if (ParamType.hasQualifiers())
4155 ParamType = ParamType.getUnqualifiedType();
4156
4157 // [...] If P is a reference type, the type referred to by P is
4158 // used for type deduction.
4159 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
4160 if (ParamRefType)
4161 ParamType = ParamRefType->getPointeeType();
4162
4163 // Overload sets usually make this parameter an undeduced context,
4164 // but there are sometimes special circumstances. Typically
4165 // involving a template-id-expr.
4166 if (ArgType == S.Context.OverloadTy) {
4167 assert(Arg && "expected a non-null arg expression");
4168 ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType,
4169 ParamRefType != nullptr, FailedTSC);
4170 if (ArgType.isNull())
4171 return true;
4172 }
4173
4174 if (ParamRefType) {
4175 // If the argument has incomplete array type, try to complete its type.
4176 if (ArgType->isIncompleteArrayType()) {
4177 assert(Arg && "expected a non-null arg expression");
4178 ArgType = S.getCompletedType(Arg);
4179 }
4180
4181 // C++1z [temp.deduct.call]p3:
4182 // If P is a forwarding reference and the argument is an lvalue, the type
4183 // "lvalue reference to A" is used in place of A for type deduction.
4184 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
4185 ArgClassification.isLValue()) {
4186 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
4187 ArgType = S.Context.getAddrSpaceQualType(
4189 ArgType = S.Context.getLValueReferenceType(ArgType);
4190 }
4191 } else {
4192 // C++ [temp.deduct.call]p2:
4193 // If P is not a reference type:
4194 // - If A is an array type, the pointer type produced by the
4195 // array-to-pointer standard conversion (4.2) is used in place of
4196 // A for type deduction; otherwise,
4197 // - If A is a function type, the pointer type produced by the
4198 // function-to-pointer standard conversion (4.3) is used in place
4199 // of A for type deduction; otherwise,
4200 if (ArgType->canDecayToPointerType())
4201 ArgType = S.Context.getDecayedType(ArgType);
4202 else {
4203 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
4204 // type are ignored for type deduction.
4205 ArgType = ArgType.getUnqualifiedType();
4206 }
4207 }
4208
4209 // C++0x [temp.deduct.call]p4:
4210 // In general, the deduction process attempts to find template argument
4211 // values that will make the deduced A identical to A (after the type A
4212 // is transformed as described above). [...]
4214
4215 // - If the original P is a reference type, the deduced A (i.e., the
4216 // type referred to by the reference) can be more cv-qualified than
4217 // the transformed A.
4218 if (ParamRefType)
4220 // - The transformed A can be another pointer or pointer to member
4221 // type that can be converted to the deduced A via a qualification
4222 // conversion (4.4).
4223 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
4224 ArgType->isObjCObjectPointerType())
4225 TDF |= TDF_IgnoreQualifiers;
4226 // - If P is a class and P has the form simple-template-id, then the
4227 // transformed A can be a derived class of the deduced A. Likewise,
4228 // if P is a pointer to a class of the form simple-template-id, the
4229 // transformed A can be a pointer to a derived class pointed to by
4230 // the deduced A.
4231 if (isSimpleTemplateIdType(ParamType) ||
4232 (isa<PointerType>(ParamType) &&
4234 ParamType->castAs<PointerType>()->getPointeeType())))
4235 TDF |= TDF_DerivedClass;
4236
4237 return false;
4238}
4239
4240static bool
4242 QualType T);
4243
4245 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4246 QualType ParamType, QualType ArgType,
4247 Expr::Classification ArgClassification, Expr *Arg,
4251 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4252 TemplateSpecCandidateSet *FailedTSC = nullptr);
4253
4254/// Attempt template argument deduction from an initializer list
4255/// deemed to be an argument in a function call.
4257 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
4260 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
4261 unsigned TDF) {
4262 // C++ [temp.deduct.call]p1: (CWG 1591)
4263 // If removing references and cv-qualifiers from P gives
4264 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
4265 // a non-empty initializer list, then deduction is performed instead for
4266 // each element of the initializer list, taking P0 as a function template
4267 // parameter type and the initializer element as its argument
4268 //
4269 // We've already removed references and cv-qualifiers here.
4270 if (!ILE->getNumInits())
4272
4273 QualType ElTy;
4274 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
4275 if (ArrTy)
4276 ElTy = ArrTy->getElementType();
4277 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
4278 // Otherwise, an initializer list argument causes the parameter to be
4279 // considered a non-deduced context
4281 }
4282
4283 // Resolving a core issue: a braced-init-list containing any designators is
4284 // a non-deduced context.
4285 for (Expr *E : ILE->inits())
4286 if (isa<DesignatedInitExpr>(E))
4288
4289 // Deduction only needs to be done for dependent types.
4290 if (ElTy->isDependentType()) {
4291 for (Expr *E : ILE->inits()) {
4293 S, TemplateParams, 0, ElTy, E->getType(),
4294 E->Classify(S.getASTContext()), E, Info, Deduced,
4295 OriginalCallArgs, true, ArgIdx, TDF);
4297 return Result;
4298 }
4299 }
4300
4301 // in the P0[N] case, if N is a non-type template parameter, N is deduced
4302 // from the length of the initializer list.
4303 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
4304 // Determine the array bound is something we can deduce.
4305 if (const NonTypeTemplateParmDecl *NTTP =
4306 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
4307 // We can perform template argument deduction for the given non-type
4308 // template parameter.
4309 // C++ [temp.deduct.type]p13:
4310 // The type of N in the type T[N] is std::size_t.
4312 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
4314 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
4315 /*ArrayBound=*/true, Info, Deduced);
4317 return Result;
4318 }
4319 }
4320
4322}
4323
4324/// Perform template argument deduction per [temp.deduct.call] for a
4325/// single parameter / argument pair.
4327 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4328 QualType ParamType, QualType ArgType,
4329 Expr::Classification ArgClassification, Expr *Arg,
4333 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4334 TemplateSpecCandidateSet *FailedTSC) {
4335
4336 QualType OrigParamType = ParamType;
4337
4338 // If P is a reference type [...]
4339 // If P is a cv-qualified type [...]
4341 S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
4342 ArgClassification, Arg, TDF, FailedTSC))
4344
4345 // If [...] the argument is a non-empty initializer list [...]
4346 if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
4347 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
4348 Deduced, OriginalCallArgs, ArgIdx, TDF);
4349
4350 // [...] the deduction process attempts to find template argument values
4351 // that will make the deduced A identical to A
4352 //
4353 // Keep track of the argument type and corresponding parameter index,
4354 // so we can check for compatibility between the deduced A and A.
4355 if (Arg)
4356 OriginalCallArgs.push_back(
4357 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
4358 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
4359 ArgType, Info, Deduced, TDF);
4360}
4361
4363 FunctionTemplateDecl *FunctionTemplate,
4364 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4366 bool PartialOverloading, bool AggregateDeductionCandidate,
4367 QualType ObjectType, Expr::Classification ObjectClassification,
4368 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
4369 if (FunctionTemplate->isInvalidDecl())
4371
4372 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4373 unsigned NumParams = Function->getNumParams();
4374 bool HasExplicitObject = false;
4375 int ExplicitObjectOffset = 0;
4376 if (Function->hasCXXExplicitFunctionObjectParameter()) {
4377 HasExplicitObject = true;
4378 ExplicitObjectOffset = 1;
4379 }
4380
4381 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
4382
4383 // C++ [temp.deduct.call]p1:
4384 // Template argument deduction is done by comparing each function template
4385 // parameter type (call it P) with the type of the corresponding argument
4386 // of the call (call it A) as described below.
4387 if (Args.size() < Function->getMinRequiredExplicitArguments() &&
4388 !PartialOverloading)
4390 else if (TooManyArguments(NumParams, Args.size() + ExplicitObjectOffset,
4391 PartialOverloading)) {
4392 const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
4393 if (Proto->isTemplateVariadic())
4394 /* Do nothing */;
4395 else if (!Proto->isVariadic())
4397 }
4398
4399 // The types of the parameters from which we will perform template argument
4400 // deduction.
4401 LocalInstantiationScope InstScope(*this);
4402 TemplateParameterList *TemplateParams
4403 = FunctionTemplate->getTemplateParameters();
4405 SmallVector<QualType, 8> ParamTypes;
4406 unsigned NumExplicitlySpecified = 0;
4407 if (ExplicitTemplateArgs) {
4410 Result = SubstituteExplicitTemplateArguments(
4411 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4412 Info);
4413 });
4415 return Result;
4416
4417 NumExplicitlySpecified = Deduced.size();
4418 } else {
4419 // Just fill in the parameter types from the function declaration.
4420 for (unsigned I = 0; I != NumParams; ++I)
4421 ParamTypes.push_back(Function->getParamDecl(I)->getType());
4422 }
4423
4424 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
4425
4426 // Deduce an argument of type ParamType from an expression with index ArgIdx.
4427 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx,
4428 bool ExplicitObjectArgument) {
4429 // C++ [demp.deduct.call]p1: (DR1391)
4430 // Template argument deduction is done by comparing each function template
4431 // parameter that contains template-parameters that participate in
4432 // template argument deduction ...
4433 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4435
4436 if (ExplicitObjectArgument) {
4437 // ... with the type of the corresponding argument
4439 *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
4440 ObjectClassification,
4441 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4442 /*Decomposed*/ false, ArgIdx, /*TDF*/ 0);
4443 }
4444
4445 // ... with the type of the corresponding argument
4447 *this, TemplateParams, FirstInnerIndex, ParamType,
4448 Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()),
4449 Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false,
4450 ArgIdx, /*TDF*/ 0);
4451 };
4452
4453 // Deduce template arguments from the function parameters.
4454 Deduced.resize(TemplateParams->size());
4455 SmallVector<QualType, 8> ParamTypesForArgChecking;
4456 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4457 ParamIdx != NumParamTypes; ++ParamIdx) {
4458 QualType ParamType = ParamTypes[ParamIdx];
4459
4460 const PackExpansionType *ParamExpansion =
4461 dyn_cast<PackExpansionType>(ParamType);
4462 if (!ParamExpansion) {
4463 // Simple case: matching a function parameter to a function argument.
4464 if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0))
4465 break;
4466
4467 ParamTypesForArgChecking.push_back(ParamType);
4468
4469 if (ParamIdx == 0 && HasExplicitObject) {
4470 if (auto Result = DeduceCallArgument(ParamType, 0,
4471 /*ExplicitObjectArgument=*/true);
4473 return Result;
4474 continue;
4475 }
4476
4477 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4478 /*ExplicitObjectArgument=*/false);
4480 return Result;
4481
4482 continue;
4483 }
4484
4485 bool IsTrailingPack = ParamIdx + 1 == NumParamTypes;
4486
4487 QualType ParamPattern = ParamExpansion->getPattern();
4488 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
4489 ParamPattern,
4490 AggregateDeductionCandidate && IsTrailingPack);
4491
4492 // C++0x [temp.deduct.call]p1:
4493 // For a function parameter pack that occurs at the end of the
4494 // parameter-declaration-list, the type A of each remaining argument of
4495 // the call is compared with the type P of the declarator-id of the
4496 // function parameter pack. Each comparison deduces template arguments
4497 // for subsequent positions in the template parameter packs expanded by
4498 // the function parameter pack. When a function parameter pack appears
4499 // in a non-deduced context [not at the end of the list], the type of
4500 // that parameter pack is never deduced.
4501 //
4502 // FIXME: The above rule allows the size of the parameter pack to change
4503 // after we skip it (in the non-deduced case). That makes no sense, so
4504 // we instead notionally deduce the pack against N arguments, where N is
4505 // the length of the explicitly-specified pack if it's expanded by the
4506 // parameter pack and 0 otherwise, and we treat each deduction as a
4507 // non-deduced context.
4508 if (IsTrailingPack || PackScope.hasFixedArity()) {
4509 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4510 PackScope.nextPackElement(), ++ArgIdx) {
4511 ParamTypesForArgChecking.push_back(ParamPattern);
4512 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4513 /*ExplicitObjectArgument=*/false);
4515 return Result;
4516 }
4517 } else {
4518 // If the parameter type contains an explicitly-specified pack that we
4519 // could not expand, skip the number of parameters notionally created
4520 // by the expansion.
4521 std::optional<unsigned> NumExpansions =
4522 ParamExpansion->getNumExpansions();
4523 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4524 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4525 ++I, ++ArgIdx) {
4526 ParamTypesForArgChecking.push_back(ParamPattern);
4527 // FIXME: Should we add OriginalCallArgs for these? What if the
4528 // corresponding argument is a list?
4529 PackScope.nextPackElement();
4530 }
4531 } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4532 PackScope.isDeducedFromEarlierParameter()) {
4533 // [temp.deduct.general#3]
4534 // When all template arguments have been deduced
4535 // or obtained from default template arguments, all uses of template
4536 // parameters in the template parameter list of the template are
4537 // replaced with the corresponding deduced or default argument values
4538 //
4539 // If we have a trailing parameter pack, that has been deduced
4540 // previously we substitute the pack here in a similar fashion as
4541 // above with the trailing parameter packs. The main difference here is
4542 // that, in this case we are not processing all of the remaining
4543 // arguments. We are only process as many arguments as we have in
4544 // the already deduced parameter.
4545 std::optional<unsigned> ArgPosAfterSubstitution =
4546 PackScope.getSavedPackSizeIfAllEqual();
4547 if (!ArgPosAfterSubstitution)
4548 continue;
4549
4550 unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4551 for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4552 ParamTypesForArgChecking.push_back(ParamPattern);
4553 if (auto Result =
4554 DeduceCallArgument(ParamPattern, ArgIdx,
4555 /*ExplicitObjectArgument=*/false);
4557 return Result;
4558
4559 PackScope.nextPackElement();
4560 }
4561 }
4562 }
4563
4564 // Build argument packs for each of the parameter packs expanded by this
4565 // pack expansion.
4566 if (auto Result = PackScope.finish();
4568 return Result;
4569 }
4570
4571 // Capture the context in which the function call is made. This is the context
4572 // that is needed when the accessibility of template arguments is checked.
4573 DeclContext *CallingCtx = CurContext;
4574
4577 Result = FinishTemplateArgumentDeduction(
4578 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4579 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
4580 ContextRAII SavedContext(*this, CallingCtx);
4581 return CheckNonDependent(ParamTypesForArgChecking);
4582 });
4583 });
4584 return Result;
4585}
4586
4589 bool AdjustExceptionSpec) {
4590 if (ArgFunctionType.isNull())
4591 return ArgFunctionType;
4592
4593 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4594 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4595 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4596 bool Rebuild = false;
4597
4598 CallingConv CC = FunctionTypeP->getCallConv();
4599 if (EPI.ExtInfo.getCC() != CC) {
4600 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4601 Rebuild = true;
4602 }
4603
4604 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4605 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4606 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4607 Rebuild = true;
4608 }
4609
4610 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4611 ArgFunctionTypeP->hasExceptionSpec())) {
4612 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4613 Rebuild = true;
4614 }
4615
4616 if (!Rebuild)
4617 return ArgFunctionType;
4618
4619 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4620 ArgFunctionTypeP->getParamTypes(), EPI);
4621}
4622
4624 FunctionTemplateDecl *FunctionTemplate,
4625 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4627 bool IsAddressOfFunction) {
4628 if (FunctionTemplate->isInvalidDecl())
4630
4631 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4632 TemplateParameterList *TemplateParams
4633 = FunctionTemplate->getTemplateParameters();
4634 QualType FunctionType = Function->getType();
4635
4636 // Substitute any explicit template arguments.
4637 LocalInstantiationScope InstScope(*this);
4639 unsigned NumExplicitlySpecified = 0;
4640 SmallVector<QualType, 4> ParamTypes;
4641 if (ExplicitTemplateArgs) {
4644 Result = SubstituteExplicitTemplateArguments(
4645 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4646 &FunctionType, Info);
4647 });
4649 return Result;
4650
4651 NumExplicitlySpecified = Deduced.size();
4652 }
4653
4654 // When taking the address of a function, we require convertibility of
4655 // the resulting function type. Otherwise, we allow arbitrary mismatches
4656 // of calling convention and noreturn.
4657 if (!IsAddressOfFunction)
4658 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4659 /*AdjustExceptionSpec*/false);
4660
4661 // Unevaluated SFINAE context.
4664 SFINAETrap Trap(*this);
4665
4666 Deduced.resize(TemplateParams->size());
4667
4668 // If the function has a deduced return type, substitute it for a dependent
4669 // type so that we treat it as a non-deduced context in what follows.
4670 bool HasDeducedReturnType = false;
4671 if (getLangOpts().CPlusPlus14 &&
4672 Function->getReturnType()->getContainedAutoType()) {
4674 HasDeducedReturnType = true;
4675 }
4676
4677 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
4678 unsigned TDF =
4680 // Deduce template arguments from the function type.
4682 *this, TemplateParams, FunctionType, ArgFunctionType, Info, Deduced,
4683 TDF);
4685 return Result;
4686 }
4687
4690 Result = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
4691 NumExplicitlySpecified,
4692 Specialization, Info);
4693 });
4695 return Result;
4696
4697 // If the function has a deduced return type, deduce it now, so we can check
4698 // that the deduced function type matches the requested type.
4699 if (HasDeducedReturnType && IsAddressOfFunction &&
4700 Specialization->getReturnType()->isUndeducedType() &&
4703
4704 // [C++26][expr.const]/p17
4705 // An expression or conversion is immediate-escalating if it is not initially
4706 // in an immediate function context and it is [...]
4707 // a potentially-evaluated id-expression that denotes an immediate function.
4708 if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
4709 Specialization->isImmediateEscalating() &&
4710 parentEvaluationContext().isPotentiallyEvaluated() &&
4712 Info.getLocation()))
4714
4715 // Adjust the exception specification of the argument to match the
4716 // substituted and resolved type we just formed. (Calling convention and
4717 // noreturn can't be dependent, so we don't actually need this for them
4718 // right now.)
4719 QualType SpecializationType = Specialization->getType();
4720 if (!IsAddressOfFunction) {
4721 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4722 /*AdjustExceptionSpec*/true);
4723
4724 // Revert placeholder types in the return type back to undeduced types so
4725 // that the comparison below compares the declared return types.
4726 if (HasDeducedReturnType) {
4727 SpecializationType = SubstAutoType(SpecializationType, QualType());
4728 ArgFunctionType = SubstAutoType(ArgFunctionType, QualType());
4729 }
4730 }
4731
4732 // If the requested function type does not match the actual type of the
4733 // specialization with respect to arguments of compatible pointer to function
4734 // types, template argument deduction fails.
4735 if (!ArgFunctionType.isNull()) {
4736 if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
4737 Context.getCanonicalType(SpecializationType),
4738 Context.getCanonicalType(ArgFunctionType))
4740 SpecializationType, ArgFunctionType)) {
4741 Info.FirstArg = TemplateArgument(SpecializationType);
4742 Info.SecondArg = TemplateArgument(ArgFunctionType);
4744 }
4745 }
4746
4748}
4749
4751 FunctionTemplateDecl *ConversionTemplate, QualType ObjectType,
4752 Expr::Classification ObjectClassification, QualType ToType,
4754 if (ConversionTemplate->isInvalidDecl())
4756
4757 CXXConversionDecl *ConversionGeneric
4758 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4759
4760 QualType FromType = ConversionGeneric->getConversionType();
4761
4762 // Canonicalize the types for deduction.
4763 QualType P = Context.getCanonicalType(FromType);
4764 QualType A = Context.getCanonicalType(ToType);
4765
4766 // C++0x [temp.deduct.conv]p2:
4767 // If P is a reference type, the type referred to by P is used for
4768 // type deduction.
4769 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4770 P = PRef->getPointeeType();
4771
4772 // C++0x [temp.deduct.conv]p4:
4773 // [...] If A is a reference type, the type referred to by A is used
4774 // for type deduction.
4775 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4776 A = ARef->getPointeeType();
4777 // We work around a defect in the standard here: cv-qualifiers are also
4778 // removed from P and A in this case, unless P was a reference type. This
4779 // seems to mostly match what other compilers are doing.
4780 if (!FromType->getAs<ReferenceType>()) {
4781 A = A.getUnqualifiedType();
4782 P = P.getUnqualifiedType();
4783 }
4784
4785 // C++ [temp.deduct.conv]p3:
4786 //
4787 // If A is not a reference type:
4788 } else {
4789 assert(!A->isReferenceType() && "Reference types were handled above");
4790
4791 // - If P is an array type, the pointer type produced by the
4792 // array-to-pointer standard conversion (4.2) is used in place
4793 // of P for type deduction; otherwise,
4794 if (P->isArrayType())
4796 // - If P is a function type, the pointer type produced by the
4797 // function-to-pointer standard conversion (4.3) is used in
4798 // place of P for type deduction; otherwise,
4799 else if (P->isFunctionType())
4801 // - If P is a cv-qualified type, the top level cv-qualifiers of
4802 // P's type are ignored for type deduction.
4803 else
4804 P = P.getUnqualifiedType();
4805
4806 // C++0x [temp.deduct.conv]p4:
4807 // If A is a cv-qualified type, the top level cv-qualifiers of A's
4808 // type are ignored for type deduction. If A is a reference type, the type
4809 // referred to by A is used for type deduction.
4810 A = A.getUnqualifiedType();
4811 }
4812
4813 // Unevaluated SFINAE context.
4816 SFINAETrap Trap(*this);
4817
4818 // C++ [temp.deduct.conv]p1:
4819 // Template argument deduction is done by comparing the return
4820 // type of the template conversion function (call it P) with the
4821 // type that is required as the result of the conversion (call it
4822 // A) as described in 14.8.2.4.
4823 TemplateParameterList *TemplateParams
4824 = ConversionTemplate->getTemplateParameters();
4826 Deduced.resize(TemplateParams->size());
4827
4828 // C++0x [temp.deduct.conv]p4:
4829 // In general, the deduction process attempts to find template
4830 // argument values that will make the deduced A identical to
4831 // A. However, there are two cases that allow a difference:
4832 unsigned TDF = 0;
4833 // - If the original A is a reference type, A can be more
4834 // cv-qualified than the deduced A (i.e., the type referred to
4835 // by the reference)
4836 if (ToType->isReferenceType())
4838 // - The deduced A can be another pointer or pointer to member
4839 // type that can be converted to A via a qualification
4840 // conversion.
4841 //
4842 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4843 // both P and A are pointers or member pointers. In this case, we
4844 // just ignore cv-qualifiers completely).
4845 if ((P->isPointerType() && A->isPointerType()) ||
4846 (P->isMemberPointerType() && A->isMemberPointerType()))
4847 TDF |= TDF_IgnoreQualifiers;
4848
4850 if (ConversionGeneric->isExplicitObjectMemberFunction()) {
4851 QualType ParamType = ConversionGeneric->getParamDecl(0)->getType();
4854 *this, TemplateParams, getFirstInnerIndex(ConversionTemplate),
4855 ParamType, ObjectType, ObjectClassification,
4856 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4857 /*Decomposed*/ false, 0, /*TDF*/ 0);
4859 return