clang 20.0.0git
SemaTemplateDeduction.cpp
Go to the documentation of this file.
1//===- SemaTemplateDeduction.cpp - Template Argument Deduction ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TreeTransform.h"
14#include "TypeLocBuilder.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
29#include "clang/AST/Type.h"
30#include "clang/AST/TypeLoc.h"
35#include "clang/Basic/LLVM.h"
42#include "clang/Sema/Sema.h"
43#include "clang/Sema/Template.h"
45#include "llvm/ADT/APInt.h"
46#include "llvm/ADT/APSInt.h"
47#include "llvm/ADT/ArrayRef.h"
48#include "llvm/ADT/DenseMap.h"
49#include "llvm/ADT/FoldingSet.h"
50#include "llvm/ADT/SmallBitVector.h"
51#include "llvm/ADT/SmallPtrSet.h"
52#include "llvm/ADT/SmallVector.h"
53#include "llvm/Support/Casting.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/Support/ErrorHandling.h"
56#include <algorithm>
57#include <cassert>
58#include <optional>
59#include <tuple>
60#include <type_traits>
61#include <utility>
62
63namespace clang {
64
65 /// Various flags that control template argument deduction.
66 ///
67 /// These flags can be bitwise-OR'd together.
69 /// No template argument deduction flags, which indicates the
70 /// strictest results for template argument deduction (as used for, e.g.,
71 /// matching class template partial specializations).
73
74 /// Within template argument deduction from a function call, we are
75 /// matching with a parameter type for which the original parameter was
76 /// a reference.
78
79 /// Within template argument deduction from a function call, we
80 /// are matching in a case where we ignore cv-qualifiers.
82
83 /// Within template argument deduction from a function call,
84 /// we are matching in a case where we can perform template argument
85 /// deduction from a template-id of a derived class of the argument type.
87
88 /// Allow non-dependent types to differ, e.g., when performing
89 /// template argument deduction from a function call where conversions
90 /// may apply.
92
93 /// Whether we are performing template argument deduction for
94 /// parameters and arguments in a top-level template argument
96
97 /// Within template argument deduction from overload resolution per
98 /// C++ [over.over] allow matching function types that are compatible in
99 /// terms of noreturn and default calling convention adjustments, or
100 /// similarly matching a declared template specialization against a
101 /// possible template, per C++ [temp.deduct.decl]. In either case, permit
102 /// deduction where the parameter is a function type that can be converted
103 /// to the argument type.
105
106 /// Within template argument deduction for a conversion function, we are
107 /// matching with an argument type for which the original argument was
108 /// a reference.
110 };
111}
112
113using namespace clang;
114using namespace sema;
115
116/// Compare two APSInts, extending and switching the sign as
117/// necessary to compare their values regardless of underlying type.
118static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
119 if (Y.getBitWidth() > X.getBitWidth())
120 X = X.extend(Y.getBitWidth());
121 else if (Y.getBitWidth() < X.getBitWidth())
122 Y = Y.extend(X.getBitWidth());
123
124 // If there is a signedness mismatch, correct it.
125 if (X.isSigned() != Y.isSigned()) {
126 // If the signed value is negative, then the values cannot be the same.
127 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
128 return false;
129
130 Y.setIsSigned(true);
131 X.setIsSigned(true);
132 }
133
134 return X == Y;
135}
136
137/// The kind of PartialOrdering we're performing template argument deduction
138/// for (C++11 [temp.deduct.partial]).
140
142 Sema &S, TemplateParameterList *TemplateParams, QualType Param,
144 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
145 PartialOrderingKind POK, bool DeducedFromArrayBound,
146 bool *HasDeducedAnyParam);
147
155 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
156 PackFold PackFold, bool *HasDeducedAnyParam);
157
160 bool OnlyDeduced, unsigned Depth,
161 llvm::SmallBitVector &Used);
162
164 bool OnlyDeduced, unsigned Level,
165 llvm::SmallBitVector &Deduced);
166
167/// If the given expression is of a form that permits the deduction
168/// of a non-type template parameter, return the declaration of that
169/// non-type template parameter.
170static const NonTypeTemplateParmDecl *
171getDeducedParameterFromExpr(const Expr *E, unsigned Depth) {
172 // If we are within an alias template, the expression may have undergone
173 // any number of parameter substitutions already.
174 while (true) {
175 if (const auto *IC = dyn_cast<ImplicitCastExpr>(E))
176 E = IC->getSubExpr();
177 else if (const auto *CE = dyn_cast<ConstantExpr>(E))
178 E = CE->getSubExpr();
179 else if (const auto *Subst = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
180 E = Subst->getReplacement();
181 else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) {
182 // Look through implicit copy construction from an lvalue of the same type.
183 if (CCE->getParenOrBraceRange().isValid())
184 break;
185 // Note, there could be default arguments.
186 assert(CCE->getNumArgs() >= 1 && "implicit construct expr should have 1 arg");
187 E = CCE->getArg(0);
188 } else
189 break;
190 }
191
192 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
193 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
194 if (NTTP->getDepth() == Depth)
195 return NTTP;
196
197 return nullptr;
198}
199
200static const NonTypeTemplateParmDecl *
203}
204
205/// Determine whether two declaration pointers refer to the same
206/// declaration.
207static bool isSameDeclaration(Decl *X, Decl *Y) {
208 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
209 X = NX->getUnderlyingDecl();
210 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
211 Y = NY->getUnderlyingDecl();
212
213 return X->getCanonicalDecl() == Y->getCanonicalDecl();
214}
215
216/// Verify that the given, deduced template arguments are compatible.
217///
218/// \returns The deduced template argument, or a NULL template argument if
219/// the deduced template arguments were incompatible.
224 bool AggregateCandidateDeduction = false) {
225 // We have no deduction for one or both of the arguments; they're compatible.
226 if (X.isNull())
227 return Y;
228 if (Y.isNull())
229 return X;
230
231 // If we have two non-type template argument values deduced for the same
232 // parameter, they must both match the type of the parameter, and thus must
233 // match each other's type. As we're only keeping one of them, we must check
234 // for that now. The exception is that if either was deduced from an array
235 // bound, the type is permitted to differ.
236 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
237 QualType XType = X.getNonTypeTemplateArgumentType();
238 if (!XType.isNull()) {
240 if (YType.isNull() || !Context.hasSameType(XType, YType))
242 }
243 }
244
245 switch (X.getKind()) {
247 llvm_unreachable("Non-deduced template arguments handled above");
248
250 // If two template type arguments have the same type, they're compatible.
251 QualType TX = X.getAsType(), TY = Y.getAsType();
252 if (Y.getKind() == TemplateArgument::Type && Context.hasSameType(TX, TY))
253 return DeducedTemplateArgument(Context.getCommonSugaredType(TX, TY),
254 X.wasDeducedFromArrayBound() ||
256
257 // If one of the two arguments was deduced from an array bound, the other
258 // supersedes it.
259 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
260 return X.wasDeducedFromArrayBound() ? Y : X;
261
262 // The arguments are not compatible.
264 }
265
267 // If we deduced a constant in one case and either a dependent expression or
268 // declaration in another case, keep the integral constant.
269 // If both are integral constants with the same value, keep that value.
273 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
274 return X.wasDeducedFromArrayBound() ? Y : X;
275
276 // All other combinations are incompatible.
278
280 // If we deduced a value and a dependent expression, keep the value.
283 X.structurallyEquals(Y)))
284 return X;
285
286 // All other combinations are incompatible.
288
291 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
292 return X;
293
294 // All other combinations are incompatible.
296
299 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
301 return X;
302
303 // All other combinations are incompatible.
305
308 return checkDeducedTemplateArguments(Context, Y, X);
309
310 // Compare the expressions for equality
311 llvm::FoldingSetNodeID ID1, ID2;
312 X.getAsExpr()->Profile(ID1, Context, true);
313 Y.getAsExpr()->Profile(ID2, Context, true);
314 if (ID1 == ID2)
315 return X.wasDeducedFromArrayBound() ? Y : X;
316
317 // Differing dependent expressions are incompatible.
319 }
320
322 assert(!X.wasDeducedFromArrayBound());
323
324 // If we deduced a declaration and a dependent expression, keep the
325 // declaration.
327 return X;
328
329 // If we deduced a declaration and an integral constant, keep the
330 // integral constant and whichever type did not come from an array
331 // bound.
334 return TemplateArgument(Context, Y.getAsIntegral(),
335 X.getParamTypeForDecl());
336 return Y;
337 }
338
339 // If we deduced two declarations, make sure that they refer to the
340 // same declaration.
342 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
343 return X;
344
345 // All other combinations are incompatible.
347
349 // If we deduced a null pointer and a dependent expression, keep the
350 // null pointer.
353 X.getNullPtrType(), Y.getAsExpr()->getType()),
354 true);
355
356 // If we deduced a null pointer and an integral constant, keep the
357 // integral constant.
359 return Y;
360
361 // If we deduced two null pointers, they are the same.
363 return TemplateArgument(
364 Context.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
365 true);
366
367 // All other combinations are incompatible.
369
371 if (Y.getKind() != TemplateArgument::Pack ||
372 (!AggregateCandidateDeduction && X.pack_size() != Y.pack_size()))
374
377 XA = X.pack_begin(),
378 XAEnd = X.pack_end(), YA = Y.pack_begin(), YAEnd = Y.pack_end();
379 XA != XAEnd; ++XA) {
380 if (YA != YAEnd) {
382 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
384 if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
386 NewPack.push_back(Merged);
387 ++YA;
388 } else {
389 NewPack.push_back(*XA);
390 }
391 }
392
394 TemplateArgument::CreatePackCopy(Context, NewPack),
395 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
396 }
397 }
398
399 llvm_unreachable("Invalid TemplateArgument Kind!");
400}
401
402/// Deduce the value of the given non-type template parameter
403/// as the given deduced template argument. All non-type template parameter
404/// deduction is funneled through here.
407 const NonTypeTemplateParmDecl *NTTP,
408 const DeducedTemplateArgument &NewDeduced,
409 QualType ValueType, TemplateDeductionInfo &Info,
410 bool PartialOrdering,
412 bool *HasDeducedAnyParam) {
413 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
414 "deducing non-type template argument with wrong depth");
415
417 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
418 if (Result.isNull()) {
419 Info.Param = const_cast<NonTypeTemplateParmDecl*>(NTTP);
420 Info.FirstArg = Deduced[NTTP->getIndex()];
421 Info.SecondArg = NewDeduced;
422 return TemplateDeductionResult::Inconsistent;
423 }
424
425 Deduced[NTTP->getIndex()] = Result;
426 if (!S.getLangOpts().CPlusPlus17)
427 return TemplateDeductionResult::Success;
428
429 if (NTTP->isExpandedParameterPack())
430 // FIXME: We may still need to deduce parts of the type here! But we
431 // don't have any way to find which slice of the type to use, and the
432 // type stored on the NTTP itself is nonsense. Perhaps the type of an
433 // expanded NTTP should be a pack expansion type?
434 return TemplateDeductionResult::Success;
435
436 // Get the type of the parameter for deduction. If it's a (dependent) array
437 // or function type, we will not have decayed it yet, so do that now.
438 QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
439 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
440 ParamType = Expansion->getPattern();
441
442 // FIXME: It's not clear how deduction of a parameter of reference
443 // type from an argument (of non-reference type) should be performed.
444 // For now, we just make the argument have same reference type as the
445 // parameter.
446 if (ParamType->isReferenceType() && !ValueType->isReferenceType()) {
447 if (ParamType->isRValueReferenceType())
448 ValueType = S.Context.getRValueReferenceType(ValueType);
449 else
450 ValueType = S.Context.getLValueReferenceType(ValueType);
451 }
452
454 S, TemplateParams, ParamType, ValueType, Info, Deduced,
458 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound(), HasDeducedAnyParam);
459}
460
461/// Deduce the value of the given non-type template parameter
462/// from the given integral constant.
464 Sema &S, TemplateParameterList *TemplateParams,
465 const NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
466 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
468 bool *HasDeducedAnyParam) {
470 S, TemplateParams, NTTP,
472 DeducedFromArrayBound),
473 ValueType, Info, PartialOrdering, Deduced, HasDeducedAnyParam);
474}
475
476/// Deduce the value of the given non-type template parameter
477/// from the given null pointer template argument type.
480 const NonTypeTemplateParmDecl *NTTP,
481 QualType NullPtrType, TemplateDeductionInfo &Info,
482 bool PartialOrdering,
484 bool *HasDeducedAnyParam) {
487 NTTP->getLocation()),
488 NullPtrType,
489 NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer
490 : CK_NullToPointer)
491 .get();
493 S, TemplateParams, NTTP, DeducedTemplateArgument(Value), Value->getType(),
494 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
495}
496
497/// Deduce the value of the given non-type template parameter
498/// from the given type- or value-dependent expression.
499///
500/// \returns true if deduction succeeded, false otherwise.
503 const NonTypeTemplateParmDecl *NTTP, Expr *Value,
506 bool *HasDeducedAnyParam) {
508 S, TemplateParams, NTTP, DeducedTemplateArgument(Value), Value->getType(),
509 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
510}
511
512/// Deduce the value of the given non-type template parameter
513/// from the given declaration.
514///
515/// \returns true if deduction succeeded, false otherwise.
518 const NonTypeTemplateParmDecl *NTTP, ValueDecl *D,
520 bool PartialOrdering,
522 bool *HasDeducedAnyParam) {
523 TemplateArgument New(D, T);
525 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info,
526 PartialOrdering, Deduced, HasDeducedAnyParam);
527}
528
530 Sema &S, TemplateParameterList *TemplateParams, TemplateName Param,
534 bool *HasDeducedAnyParam) {
535 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
536 if (!ParamDecl) {
537 // The parameter type is dependent and is not a template template parameter,
538 // so there is nothing that we can deduce.
539 return TemplateDeductionResult::Success;
540 }
541
542 if (auto *TempParam = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
543 // If we're not deducing at this depth, there's nothing to deduce.
544 if (TempParam->getDepth() != Info.getDeducedDepth())
545 return TemplateDeductionResult::Success;
546
547 ArrayRef<NamedDecl *> Params =
548 ParamDecl->getTemplateParameters()->asArray();
549 unsigned StartPos = 0;
550 for (unsigned I = 0, E = std::min(Params.size(), DefaultArguments.size());
551 I < E; ++I) {
552 if (Params[I]->isParameterPack()) {
553 StartPos = DefaultArguments.size();
554 break;
555 }
556 StartPos = I + 1;
557 }
558
559 // Provisional resolution for CWG2398: If Arg names a template
560 // specialization, then we deduce a synthesized template name
561 // based on A, but using the TS's extra arguments, relative to P, as
562 // defaults.
563 DeducedTemplateArgument NewDeduced =
566 Arg, {StartPos, DefaultArguments.drop_front(StartPos)}))
567 : Arg;
568
570 S.Context, Deduced[TempParam->getIndex()], NewDeduced);
571 if (Result.isNull()) {
572 Info.Param = TempParam;
573 Info.FirstArg = Deduced[TempParam->getIndex()];
574 Info.SecondArg = NewDeduced;
575 return TemplateDeductionResult::Inconsistent;
576 }
577
578 Deduced[TempParam->getIndex()] = Result;
579 if (HasDeducedAnyParam)
580 *HasDeducedAnyParam = true;
581 return TemplateDeductionResult::Success;
582 }
583
584 // Verify that the two template names are equivalent.
586 Param, Arg, /*IgnoreDeduced=*/DefaultArguments.size() != 0))
587 return TemplateDeductionResult::Success;
588
589 // Mismatch of non-dependent template parameter to argument.
590 Info.FirstArg = TemplateArgument(Param);
591 Info.SecondArg = TemplateArgument(Arg);
592 return TemplateDeductionResult::NonDeducedMismatch;
593}
594
595/// Deduce the template arguments by comparing the template parameter
596/// type (which is a template-id) with the template argument type.
597///
598/// \param S the Sema
599///
600/// \param TemplateParams the template parameters that we are deducing
601///
602/// \param P the parameter type
603///
604/// \param A the argument type
605///
606/// \param Info information about the template argument deduction itself
607///
608/// \param Deduced the deduced template arguments
609///
610/// \returns the result of template argument deduction so far. Note that a
611/// "success" result means that template argument deduction has not yet failed,
612/// but it may still fail, later, for other reasons.
613
615 for (const Type *T = QT.getTypePtr(); /**/; /**/) {
616 const TemplateSpecializationType *TST =
618 assert(TST && "Expected a TemplateSpecializationType");
619 if (!TST->isSugared())
620 return TST;
621 T = TST->desugar().getTypePtr();
622 }
623}
624
627 const QualType P, QualType A,
630 bool *HasDeducedAnyParam) {
631 QualType UP = P;
632 if (const auto *IP = P->getAs<InjectedClassNameType>())
633 UP = IP->getInjectedSpecializationType();
634
635 assert(isa<TemplateSpecializationType>(UP.getCanonicalType()));
637 TemplateName TNP = TP->getTemplateName();
638
639 // If the parameter is an alias template, there is nothing to deduce.
640 if (const auto *TD = TNP.getAsTemplateDecl(); TD && TD->isTypeAlias())
641 return TemplateDeductionResult::Success;
642
643 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
644 // arguments.
648 ->template_arguments();
649
650 QualType UA = A;
651 std::optional<NestedNameSpecifier *> NNS;
652 // Treat an injected-class-name as its underlying template-id.
653 if (const auto *Elaborated = A->getAs<ElaboratedType>()) {
654 NNS = Elaborated->getQualifier();
655 } else if (const auto *Injected = A->getAs<InjectedClassNameType>()) {
656 UA = Injected->getInjectedSpecializationType();
657 NNS = nullptr;
658 }
659
660 // Check whether the template argument is a dependent template-id.
661 if (isa<TemplateSpecializationType>(UA.getCanonicalType())) {
663 TemplateName TNA = SA->getTemplateName();
664
665 // If the argument is an alias template, there is nothing to deduce.
666 if (const auto *TD = TNA.getAsTemplateDecl(); TD && TD->isTypeAlias())
667 return TemplateDeductionResult::Success;
668
669 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
670 // arguments.
674 ->template_arguments();
675
676 // Perform template argument deduction for the template name.
677 if (auto Result = DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
678 /*DefaultArguments=*/AResolved,
679 PartialOrdering, Deduced,
680 HasDeducedAnyParam);
681 Result != TemplateDeductionResult::Success)
682 return Result;
683
684 // Perform template argument deduction on each template
685 // argument. Ignore any missing/extra arguments, since they could be
686 // filled in by default arguments.
688 S, TemplateParams, PResolved, AResolved, Info, Deduced,
689 /*NumberOfArgumentsMustMatch=*/false, PartialOrdering,
690 PackFold::ParameterToArgument, HasDeducedAnyParam);
691 }
692
693 // If the argument type is a class template specialization, we
694 // perform template argument deduction using its template
695 // arguments.
696 const auto *RA = UA->getAs<RecordType>();
697 const auto *SA =
698 RA ? dyn_cast<ClassTemplateSpecializationDecl>(RA->getDecl()) : nullptr;
699 if (!SA) {
701 Info.SecondArg = TemplateArgument(A);
702 return TemplateDeductionResult::NonDeducedMismatch;
703 }
704
705 TemplateName TNA = TemplateName(SA->getSpecializedTemplate());
706 if (NNS)
708 *NNS, false, TemplateName(SA->getSpecializedTemplate()));
709
710 // Perform template argument deduction for the template name.
711 if (auto Result = DeduceTemplateArguments(
712 S, TemplateParams, TNP, TNA, Info,
713 /*DefaultArguments=*/SA->getTemplateArgs().asArray(), PartialOrdering,
714 Deduced, HasDeducedAnyParam);
715 Result != TemplateDeductionResult::Success)
716 return Result;
717
718 // Perform template argument deduction for the template arguments.
719 return DeduceTemplateArguments(S, TemplateParams, PResolved,
720 SA->getTemplateArgs().asArray(), Info, Deduced,
721 /*NumberOfArgumentsMustMatch=*/true,
723 HasDeducedAnyParam);
724}
725
727 assert(T->isCanonicalUnqualified());
728
729 switch (T->getTypeClass()) {
730 case Type::TypeOfExpr:
731 case Type::TypeOf:
732 case Type::DependentName:
733 case Type::Decltype:
734 case Type::PackIndexing:
735 case Type::UnresolvedUsing:
736 case Type::TemplateTypeParm:
737 case Type::Auto:
738 return true;
739
740 case Type::ConstantArray:
741 case Type::IncompleteArray:
742 case Type::VariableArray:
743 case Type::DependentSizedArray:
745 cast<ArrayType>(T)->getElementType().getTypePtr());
746
747 default:
748 return false;
749 }
750}
751
752/// Determines whether the given type is an opaque type that
753/// might be more qualified when instantiated.
757}
758
759/// Helper function to build a TemplateParameter when we don't
760/// know its type statically.
762 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
763 return TemplateParameter(TTP);
764 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
765 return TemplateParameter(NTTP);
766
767 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
768}
769
770/// A pack that we're currently deducing.
772 // The index of the pack.
773 unsigned Index;
774
775 // The old value of the pack before we started deducing it.
777
778 // A deferred value of this pack from an inner deduction, that couldn't be
779 // deduced because this deduction hadn't happened yet.
781
782 // The new value of the pack.
784
785 // The outer deduction for this pack, if any.
786 DeducedPack *Outer = nullptr;
787
788 DeducedPack(unsigned Index) : Index(Index) {}
789};
790
791namespace {
792
793/// A scope in which we're performing pack deduction.
794class PackDeductionScope {
795public:
796 /// Prepare to deduce the packs named within Pattern.
797 /// \param FinishingDeduction Don't attempt to deduce the pack. Useful when
798 /// just checking a previous deduction of the pack.
799 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
802 bool DeducePackIfNotAlreadyDeduced = false,
803 bool FinishingDeduction = false)
804 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info),
805 DeducePackIfNotAlreadyDeduced(DeducePackIfNotAlreadyDeduced),
806 FinishingDeduction(FinishingDeduction) {
807 unsigned NumNamedPacks = addPacks(Pattern);
808 finishConstruction(NumNamedPacks);
809 }
810
811 /// Prepare to directly deduce arguments of the parameter with index \p Index.
812 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
814 TemplateDeductionInfo &Info, unsigned Index)
815 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
816 addPack(Index);
817 finishConstruction(1);
818 }
819
820private:
821 void addPack(unsigned Index) {
822 // Save the deduced template argument for the parameter pack expanded
823 // by this pack expansion, then clear out the deduction.
824 DeducedFromEarlierParameter = !Deduced[Index].isNull();
825 DeducedPack Pack(Index);
826 if (!FinishingDeduction) {
827 Pack.Saved = Deduced[Index];
828 Deduced[Index] = TemplateArgument();
829 }
830
831 // FIXME: What if we encounter multiple packs with different numbers of
832 // pre-expanded expansions? (This should already have been diagnosed
833 // during substitution.)
834 if (std::optional<unsigned> ExpandedPackExpansions =
835 getExpandedPackSize(TemplateParams->getParam(Index)))
836 FixedNumExpansions = ExpandedPackExpansions;
837
838 Packs.push_back(Pack);
839 }
840
841 unsigned addPacks(TemplateArgument Pattern) {
842 // Compute the set of template parameter indices that correspond to
843 // parameter packs expanded by the pack expansion.
844 llvm::SmallBitVector SawIndices(TemplateParams->size());
846
847 auto AddPack = [&](unsigned Index) {
848 if (SawIndices[Index])
849 return;
850 SawIndices[Index] = true;
851 addPack(Index);
852
853 // Deducing a parameter pack that is a pack expansion also constrains the
854 // packs appearing in that parameter to have the same deduced arity. Also,
855 // in C++17 onwards, deducing a non-type template parameter deduces its
856 // type, so we need to collect the pending deduced values for those packs.
857 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
858 TemplateParams->getParam(Index))) {
859 if (!NTTP->isExpandedParameterPack())
860 // FIXME: CWG2982 suggests a type-constraint forms a non-deduced
861 // context, however it is not yet resolved.
862 if (auto *Expansion = dyn_cast<PackExpansionType>(
863 S.Context.getUnconstrainedType(NTTP->getType())))
864 ExtraDeductions.push_back(Expansion->getPattern());
865 }
866 // FIXME: Also collect the unexpanded packs in any type and template
867 // parameter packs that are pack expansions.
868 };
869
870 auto Collect = [&](TemplateArgument Pattern) {
872 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
873 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
874 unsigned Depth, Index;
875 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
876 if (Depth == Info.getDeducedDepth())
877 AddPack(Index);
878 }
879 };
880
881 // Look for unexpanded packs in the pattern.
882 Collect(Pattern);
883 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
884
885 unsigned NumNamedPacks = Packs.size();
886
887 // Also look for unexpanded packs that are indirectly deduced by deducing
888 // the sizes of the packs in this pattern.
889 while (!ExtraDeductions.empty())
890 Collect(ExtraDeductions.pop_back_val());
891
892 return NumNamedPacks;
893 }
894
895 void finishConstruction(unsigned NumNamedPacks) {
896 // Dig out the partially-substituted pack, if there is one.
897 const TemplateArgument *PartialPackArgs = nullptr;
898 unsigned NumPartialPackArgs = 0;
899 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
900 if (auto *Scope = S.CurrentInstantiationScope)
901 if (auto *Partial = Scope->getPartiallySubstitutedPack(
902 &PartialPackArgs, &NumPartialPackArgs))
903 PartialPackDepthIndex = getDepthAndIndex(Partial);
904
905 // This pack expansion will have been partially or fully expanded if
906 // it only names explicitly-specified parameter packs (including the
907 // partially-substituted one, if any).
908 bool IsExpanded = true;
909 for (unsigned I = 0; I != NumNamedPacks; ++I) {
910 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
911 IsExpanded = false;
912 IsPartiallyExpanded = false;
913 break;
914 }
915 if (PartialPackDepthIndex ==
916 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
917 IsPartiallyExpanded = true;
918 }
919 }
920
921 // Skip over the pack elements that were expanded into separate arguments.
922 // If we partially expanded, this is the number of partial arguments.
923 // FIXME: `&& FixedNumExpansions` is a workaround for UB described in
924 // https://github.com/llvm/llvm-project/issues/100095
925 if (IsPartiallyExpanded)
926 PackElements += NumPartialPackArgs;
927 else if (IsExpanded && FixedNumExpansions)
928 PackElements += *FixedNumExpansions;
929
930 for (auto &Pack : Packs) {
931 if (Info.PendingDeducedPacks.size() > Pack.Index)
932 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
933 else
934 Info.PendingDeducedPacks.resize(Pack.Index + 1);
935 Info.PendingDeducedPacks[Pack.Index] = &Pack;
936
937 if (PartialPackDepthIndex ==
938 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
939 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
940 // We pre-populate the deduced value of the partially-substituted
941 // pack with the specified value. This is not entirely correct: the
942 // value is supposed to have been substituted, not deduced, but the
943 // cases where this is observable require an exact type match anyway.
944 //
945 // FIXME: If we could represent a "depth i, index j, pack elem k"
946 // parameter, we could substitute the partially-substituted pack
947 // everywhere and avoid this.
948 if (!FinishingDeduction && !IsPartiallyExpanded)
949 Deduced[Pack.Index] = Pack.New[PackElements];
950 }
951 }
952 }
953
954public:
955 ~PackDeductionScope() {
956 for (auto &Pack : Packs)
957 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
958 }
959
960 // Return the size of the saved packs if all of them has the same size.
961 std::optional<unsigned> getSavedPackSizeIfAllEqual() const {
962 unsigned PackSize = Packs[0].Saved.pack_size();
963
964 if (std::all_of(Packs.begin() + 1, Packs.end(), [&PackSize](const auto &P) {
965 return P.Saved.pack_size() == PackSize;
966 }))
967 return PackSize;
968 return {};
969 }
970
971 /// Determine whether this pack has already been deduced from a previous
972 /// argument.
973 bool isDeducedFromEarlierParameter() const {
974 return DeducedFromEarlierParameter;
975 }
976
977 /// Determine whether this pack has already been partially expanded into a
978 /// sequence of (prior) function parameters / template arguments.
979 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
980
981 /// Determine whether this pack expansion scope has a known, fixed arity.
982 /// This happens if it involves a pack from an outer template that has
983 /// (notionally) already been expanded.
984 bool hasFixedArity() { return FixedNumExpansions.has_value(); }
985
986 /// Determine whether the next element of the argument is still part of this
987 /// pack. This is the case unless the pack is already expanded to a fixed
988 /// length.
989 bool hasNextElement() {
990 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
991 }
992
993 /// Move to deducing the next element in each pack that is being deduced.
994 void nextPackElement() {
995 // Capture the deduced template arguments for each parameter pack expanded
996 // by this pack expansion, add them to the list of arguments we've deduced
997 // for that pack, then clear out the deduced argument.
998 if (!FinishingDeduction) {
999 for (auto &Pack : Packs) {
1000 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
1001 if (!Pack.New.empty() || !DeducedArg.isNull()) {
1002 while (Pack.New.size() < PackElements)
1003 Pack.New.push_back(DeducedTemplateArgument());
1004 if (Pack.New.size() == PackElements)
1005 Pack.New.push_back(DeducedArg);
1006 else
1007 Pack.New[PackElements] = DeducedArg;
1008 DeducedArg = Pack.New.size() > PackElements + 1
1009 ? Pack.New[PackElements + 1]
1011 }
1012 }
1013 }
1014 ++PackElements;
1015 }
1016
1017 /// Finish template argument deduction for a set of argument packs,
1018 /// producing the argument packs and checking for consistency with prior
1019 /// deductions.
1020 TemplateDeductionResult finish() {
1021 if (FinishingDeduction)
1022 return TemplateDeductionResult::Success;
1023 // Build argument packs for each of the parameter packs expanded by this
1024 // pack expansion.
1025 for (auto &Pack : Packs) {
1026 // Put back the old value for this pack.
1027 if (!FinishingDeduction)
1028 Deduced[Pack.Index] = Pack.Saved;
1029
1030 // Always make sure the size of this pack is correct, even if we didn't
1031 // deduce any values for it.
1032 //
1033 // FIXME: This isn't required by the normative wording, but substitution
1034 // and post-substitution checking will always fail if the arity of any
1035 // pack is not equal to the number of elements we processed. (Either that
1036 // or something else has gone *very* wrong.) We're permitted to skip any
1037 // hard errors from those follow-on steps by the intent (but not the
1038 // wording) of C++ [temp.inst]p8:
1039 //
1040 // If the function selected by overload resolution can be determined
1041 // without instantiating a class template definition, it is unspecified
1042 // whether that instantiation actually takes place
1043 Pack.New.resize(PackElements);
1044
1045 // Build or find a new value for this pack.
1047 if (Pack.New.empty()) {
1048 // If we deduced an empty argument pack, create it now.
1050 } else {
1051 TemplateArgument *ArgumentPack =
1052 new (S.Context) TemplateArgument[Pack.New.size()];
1053 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
1054 NewPack = DeducedTemplateArgument(
1055 TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())),
1056 // FIXME: This is wrong, it's possible that some pack elements are
1057 // deduced from an array bound and others are not:
1058 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
1059 // g({1, 2, 3}, {{}, {}});
1060 // ... should deduce T = {int, size_t (from array bound)}.
1061 Pack.New[0].wasDeducedFromArrayBound());
1062 }
1063
1064 // Pick where we're going to put the merged pack.
1066 if (Pack.Outer) {
1067 if (Pack.Outer->DeferredDeduction.isNull()) {
1068 // Defer checking this pack until we have a complete pack to compare
1069 // it against.
1070 Pack.Outer->DeferredDeduction = NewPack;
1071 continue;
1072 }
1073 Loc = &Pack.Outer->DeferredDeduction;
1074 } else {
1075 Loc = &Deduced[Pack.Index];
1076 }
1077
1078 // Check the new pack matches any previous value.
1079 DeducedTemplateArgument OldPack = *Loc;
1081 S.Context, OldPack, NewPack, DeducePackIfNotAlreadyDeduced);
1082
1083 Info.AggregateDeductionCandidateHasMismatchedArity =
1084 OldPack.getKind() == TemplateArgument::Pack &&
1085 NewPack.getKind() == TemplateArgument::Pack &&
1086 OldPack.pack_size() != NewPack.pack_size() && !Result.isNull();
1087
1088 // If we deferred a deduction of this pack, check that one now too.
1089 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
1090 OldPack = Result;
1091 NewPack = Pack.DeferredDeduction;
1092 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
1093 }
1094
1095 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
1096 if (Result.isNull()) {
1097 Info.Param = makeTemplateParameter(Param);
1098 Info.FirstArg = OldPack;
1099 Info.SecondArg = NewPack;
1100 return TemplateDeductionResult::Inconsistent;
1101 }
1102
1103 // If we have a pre-expanded pack and we didn't deduce enough elements
1104 // for it, fail deduction.
1105 if (std::optional<unsigned> Expansions = getExpandedPackSize(Param)) {
1106 if (*Expansions != PackElements) {
1107 Info.Param = makeTemplateParameter(Param);
1108 Info.FirstArg = Result;
1109 return TemplateDeductionResult::IncompletePack;
1110 }
1111 }
1112
1113 *Loc = Result;
1114 }
1115
1116 return TemplateDeductionResult::Success;
1117 }
1118
1119private:
1120 Sema &S;
1121 TemplateParameterList *TemplateParams;
1124 unsigned PackElements = 0;
1125 bool IsPartiallyExpanded = false;
1126 bool DeducePackIfNotAlreadyDeduced = false;
1127 bool DeducedFromEarlierParameter = false;
1128 bool FinishingDeduction = false;
1129 /// The number of expansions, if we have a fully-expanded pack in this scope.
1130 std::optional<unsigned> FixedNumExpansions;
1131
1133};
1134
1135} // namespace
1136
1137template <class T>
1139 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1142 bool FinishingDeduction, T &&DeductFunc) {
1143 // C++0x [temp.deduct.type]p10:
1144 // Similarly, if P has a form that contains (T), then each parameter type
1145 // Pi of the respective parameter-type- list of P is compared with the
1146 // corresponding parameter type Ai of the corresponding parameter-type-list
1147 // of A. [...]
1148 unsigned ArgIdx = 0, ParamIdx = 0;
1149 for (; ParamIdx != Params.size(); ++ParamIdx) {
1150 // Check argument types.
1151 const PackExpansionType *Expansion
1152 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1153 if (!Expansion) {
1154 // Simple case: compare the parameter and argument types at this point.
1155
1156 // Make sure we have an argument.
1157 if (ArgIdx >= Args.size())
1158 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1159
1160 if (isa<PackExpansionType>(Args[ArgIdx])) {
1161 // C++0x [temp.deduct.type]p22:
1162 // If the original function parameter associated with A is a function
1163 // parameter pack and the function parameter associated with P is not
1164 // a function parameter pack, then template argument deduction fails.
1165 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1166 }
1167
1168 if (TemplateDeductionResult Result =
1169 DeductFunc(S, TemplateParams, ParamIdx, ArgIdx,
1170 Params[ParamIdx].getUnqualifiedType(),
1171 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, POK);
1172 Result != TemplateDeductionResult::Success)
1173 return Result;
1174
1175 ++ArgIdx;
1176 continue;
1177 }
1178
1179 // C++0x [temp.deduct.type]p10:
1180 // If the parameter-declaration corresponding to Pi is a function
1181 // parameter pack, then the type of its declarator- id is compared with
1182 // each remaining parameter type in the parameter-type-list of A. Each
1183 // comparison deduces template arguments for subsequent positions in the
1184 // template parameter packs expanded by the function parameter pack.
1185
1186 QualType Pattern = Expansion->getPattern();
1187 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern,
1188 /*DeducePackIfNotAlreadyDeduced=*/false,
1189 FinishingDeduction);
1190
1191 // A pack scope with fixed arity is not really a pack any more, so is not
1192 // a non-deduced context.
1193 if (ParamIdx + 1 == Params.size() || PackScope.hasFixedArity()) {
1194 for (; ArgIdx < Args.size() && PackScope.hasNextElement(); ++ArgIdx) {
1195 // Deduce template arguments from the pattern.
1196 if (TemplateDeductionResult Result = DeductFunc(
1197 S, TemplateParams, ParamIdx, ArgIdx,
1198 Pattern.getUnqualifiedType(), Args[ArgIdx].getUnqualifiedType(),
1199 Info, Deduced, POK);
1200 Result != TemplateDeductionResult::Success)
1201 return Result;
1202 PackScope.nextPackElement();
1203 }
1204 } else {
1205 // C++0x [temp.deduct.type]p5:
1206 // The non-deduced contexts are:
1207 // - A function parameter pack that does not occur at the end of the
1208 // parameter-declaration-clause.
1209 //
1210 // FIXME: There is no wording to say what we should do in this case. We
1211 // choose to resolve this by applying the same rule that is applied for a
1212 // function call: that is, deduce all contained packs to their
1213 // explicitly-specified values (or to <> if there is no such value).
1214 //
1215 // This is seemingly-arbitrarily different from the case of a template-id
1216 // with a non-trailing pack-expansion in its arguments, which renders the
1217 // entire template-argument-list a non-deduced context.
1218
1219 // If the parameter type contains an explicitly-specified pack that we
1220 // could not expand, skip the number of parameters notionally created
1221 // by the expansion.
1222 std::optional<unsigned> NumExpansions = Expansion->getNumExpansions();
1223 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1224 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
1225 ++I, ++ArgIdx)
1226 PackScope.nextPackElement();
1227 }
1228 }
1229
1230 // Build argument packs for each of the parameter packs expanded by this
1231 // pack expansion.
1232 if (auto Result = PackScope.finish();
1233 Result != TemplateDeductionResult::Success)
1234 return Result;
1235 }
1236
1237 // DR692, DR1395
1238 // C++0x [temp.deduct.type]p10:
1239 // If the parameter-declaration corresponding to P_i ...
1240 // During partial ordering, if Ai was originally a function parameter pack:
1241 // - if P does not contain a function parameter type corresponding to Ai then
1242 // Ai is ignored;
1243 if (POK == PartialOrderingKind::Call && ArgIdx + 1 == Args.size() &&
1244 isa<PackExpansionType>(Args[ArgIdx]))
1245 return TemplateDeductionResult::Success;
1246
1247 // Make sure we don't have any extra arguments.
1248 if (ArgIdx < Args.size())
1249 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1250
1251 return TemplateDeductionResult::Success;
1252}
1253
1254/// Deduce the template arguments by comparing the list of parameter
1255/// types to the list of argument types, as in the parameter-type-lists of
1256/// function types (C++ [temp.deduct.type]p10).
1257///
1258/// \param S The semantic analysis object within which we are deducing
1259///
1260/// \param TemplateParams The template parameters that we are deducing
1261///
1262/// \param Params The list of parameter types
1263///
1264/// \param Args The list of argument types
1265///
1266/// \param Info information about the template argument deduction itself
1267///
1268/// \param Deduced the deduced template arguments
1269///
1270/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1271/// how template argument deduction is performed.
1272///
1273/// \param PartialOrdering If true, we are performing template argument
1274/// deduction for during partial ordering for a call
1275/// (C++0x [temp.deduct.partial]).
1276///
1277/// \param HasDeducedAnyParam If set, the object pointed at will indicate
1278/// whether any template parameter was deduced.
1279///
1280/// \param HasDeducedParam If set, the bit vector will be used to represent
1281/// which template parameters were deduced, in order.
1282///
1283/// \returns the result of template argument deduction so far. Note that a
1284/// "success" result means that template argument deduction has not yet failed,
1285/// but it may still fail, later, for other reasons.
1287 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1289 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1290 PartialOrderingKind POK, bool *HasDeducedAnyParam,
1291 llvm::SmallBitVector *HasDeducedParam) {
1292 return ::DeduceForEachType(
1293 S, TemplateParams, Params, Args, Info, Deduced, POK,
1294 /*FinishingDeduction=*/false,
1295 [&](Sema &S, TemplateParameterList *TemplateParams, int ParamIdx,
1296 int ArgIdx, QualType P, QualType A, TemplateDeductionInfo &Info,
1298 PartialOrderingKind POK) {
1299 bool HasDeducedAnyParamCopy = false;
1301 S, TemplateParams, P, A, Info, Deduced, TDF, POK,
1302 /*DeducedFromArrayBound=*/false, &HasDeducedAnyParamCopy);
1303 if (HasDeducedAnyParam && HasDeducedAnyParamCopy)
1304 *HasDeducedAnyParam = true;
1305 if (HasDeducedParam && HasDeducedAnyParamCopy)
1306 (*HasDeducedParam)[ParamIdx] = true;
1307 return TDR;
1308 });
1309}
1310
1311/// Determine whether the parameter has qualifiers that the argument
1312/// lacks. Put another way, determine whether there is no way to add
1313/// a deduced set of qualifiers to the ParamType that would result in
1314/// its qualifiers matching those of the ArgType.
1316 QualType ArgType) {
1317 Qualifiers ParamQs = ParamType.getQualifiers();
1318 Qualifiers ArgQs = ArgType.getQualifiers();
1319
1320 if (ParamQs == ArgQs)
1321 return false;
1322
1323 // Mismatched (but not missing) Objective-C GC attributes.
1324 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1325 ParamQs.hasObjCGCAttr())
1326 return true;
1327
1328 // Mismatched (but not missing) address spaces.
1329 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1330 ParamQs.hasAddressSpace())
1331 return true;
1332
1333 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1334 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1335 ParamQs.hasObjCLifetime())
1336 return true;
1337
1338 // CVR qualifiers inconsistent or a superset.
1339 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1340}
1341
1343 const FunctionType *PF = P->getAs<FunctionType>(),
1344 *AF = A->getAs<FunctionType>();
1345
1346 // Just compare if not functions.
1347 if (!PF || !AF)
1348 return Context.hasSameType(P, A);
1349
1350 // Noreturn and noexcept adjustment.
1351 if (QualType AdjustedParam; IsFunctionConversion(P, A, AdjustedParam))
1352 P = AdjustedParam;
1353
1354 // FIXME: Compatible calling conventions.
1356}
1357
1358/// Get the index of the first template parameter that was originally from the
1359/// innermost template-parameter-list. This is 0 except when we concatenate
1360/// the template parameter lists of a class template and a constructor template
1361/// when forming an implicit deduction guide.
1363 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1364 if (!Guide || !Guide->isImplicit())
1365 return 0;
1366 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1367}
1368
1369/// Determine whether a type denotes a forwarding reference.
1370static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1371 // C++1z [temp.deduct.call]p3:
1372 // A forwarding reference is an rvalue reference to a cv-unqualified
1373 // template parameter that does not represent a template parameter of a
1374 // class template.
1375 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1376 if (ParamRef->getPointeeType().getQualifiers())
1377 return false;
1378 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1379 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1380 }
1381 return false;
1382}
1383
1384/// Attempt to deduce the template arguments by checking the base types
1385/// according to (C++20 [temp.deduct.call] p4b3.
1386///
1387/// \param S the semantic analysis object within which we are deducing.
1388///
1389/// \param RD the top level record object we are deducing against.
1390///
1391/// \param TemplateParams the template parameters that we are deducing.
1392///
1393/// \param P the template specialization parameter type.
1394///
1395/// \param Info information about the template argument deduction itself.
1396///
1397/// \param Deduced the deduced template arguments.
1398///
1399/// \returns the result of template argument deduction with the bases. "invalid"
1400/// means no matches, "success" found a single item, and the
1401/// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
1404 TemplateParameterList *TemplateParams, QualType P,
1407 bool *HasDeducedAnyParam) {
1408 // C++14 [temp.deduct.call] p4b3:
1409 // If P is a class and P has the form simple-template-id, then the
1410 // transformed A can be a derived class of the deduced A. Likewise if
1411 // P is a pointer to a class of the form simple-template-id, the
1412 // transformed A can be a pointer to a derived class pointed to by the
1413 // deduced A. However, if there is a class C that is a (direct or
1414 // indirect) base class of D and derived (directly or indirectly) from a
1415 // class B and that would be a valid deduced A, the deduced A cannot be
1416 // B or pointer to B, respectively.
1417 //
1418 // These alternatives are considered only if type deduction would
1419 // otherwise fail. If they yield more than one possible deduced A, the
1420 // type deduction fails.
1421
1422 // Use a breadth-first search through the bases to collect the set of
1423 // successful matches. Visited contains the set of nodes we have already
1424 // visited, while ToVisit is our stack of records that we still need to
1425 // visit. Matches contains a list of matches that have yet to be
1426 // disqualified.
1429 // We iterate over this later, so we have to use MapVector to ensure
1430 // determinism.
1431 struct MatchValue {
1433 bool HasDeducedAnyParam;
1434 };
1435 llvm::MapVector<const CXXRecordDecl *, MatchValue> Matches;
1436
1437 auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
1438 for (const auto &Base : RD->bases()) {
1439 QualType T = Base.getType();
1440 assert(T->isRecordType() && "Base class that isn't a record?");
1441 if (Visited.insert(T->getAsCXXRecordDecl()).second)
1442 ToVisit.push_back(T);
1443 }
1444 };
1445
1446 // Set up the loop by adding all the bases.
1447 AddBases(RD);
1448
1449 // Search each path of bases until we either run into a successful match
1450 // (where all bases of it are invalid), or we run out of bases.
1451 while (!ToVisit.empty()) {
1452 QualType NextT = ToVisit.pop_back_val();
1453
1454 SmallVector<DeducedTemplateArgument, 8> DeducedCopy(Deduced.begin(),
1455 Deduced.end());
1457 bool HasDeducedAnyParamCopy = false;
1459 S, TemplateParams, P, NextT, BaseInfo, PartialOrdering, DeducedCopy,
1460 &HasDeducedAnyParamCopy);
1461
1462 // If this was a successful deduction, add it to the list of matches,
1463 // otherwise we need to continue searching its bases.
1464 const CXXRecordDecl *RD = NextT->getAsCXXRecordDecl();
1466 Matches.insert({RD, {DeducedCopy, HasDeducedAnyParamCopy}});
1467 else
1468 AddBases(RD);
1469 }
1470
1471 // At this point, 'Matches' contains a list of seemingly valid bases, however
1472 // in the event that we have more than 1 match, it is possible that the base
1473 // of one of the matches might be disqualified for being a base of another
1474 // valid match. We can count on cyclical instantiations being invalid to
1475 // simplify the disqualifications. That is, if A & B are both matches, and B
1476 // inherits from A (disqualifying A), we know that A cannot inherit from B.
1477 if (Matches.size() > 1) {
1478 Visited.clear();
1479 for (const auto &Match : Matches)
1480 AddBases(Match.first);
1481
1482 // We can give up once we have a single item (or have run out of things to
1483 // search) since cyclical inheritance isn't valid.
1484 while (Matches.size() > 1 && !ToVisit.empty()) {
1485 const CXXRecordDecl *RD = ToVisit.pop_back_val()->getAsCXXRecordDecl();
1486 Matches.erase(RD);
1487
1488 // Always add all bases, since the inheritance tree can contain
1489 // disqualifications for multiple matches.
1490 AddBases(RD);
1491 }
1492 }
1493
1494 if (Matches.empty())
1496 if (Matches.size() > 1)
1498
1499 std::swap(Matches.front().second.Deduced, Deduced);
1500 if (bool HasDeducedAnyParamCopy = Matches.front().second.HasDeducedAnyParam;
1501 HasDeducedAnyParamCopy && HasDeducedAnyParam)
1502 *HasDeducedAnyParam = HasDeducedAnyParamCopy;
1504}
1505
1506/// When propagating a partial ordering kind into a NonCall context,
1507/// this is used to downgrade a 'Call' into a 'NonCall', so that
1508/// the kind still reflects whether we are in a partial ordering context.
1511 return std::min(POK, PartialOrderingKind::NonCall);
1512}
1513
1514/// Deduce the template arguments by comparing the parameter type and
1515/// the argument type (C++ [temp.deduct.type]).
1516///
1517/// \param S the semantic analysis object within which we are deducing
1518///
1519/// \param TemplateParams the template parameters that we are deducing
1520///
1521/// \param P the parameter type
1522///
1523/// \param A the argument type
1524///
1525/// \param Info information about the template argument deduction itself
1526///
1527/// \param Deduced the deduced template arguments
1528///
1529/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1530/// how template argument deduction is performed.
1531///
1532/// \param PartialOrdering Whether we're performing template argument deduction
1533/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1534///
1535/// \returns the result of template argument deduction so far. Note that a
1536/// "success" result means that template argument deduction has not yet failed,
1537/// but it may still fail, later, for other reasons.
1539 Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
1541 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1542 PartialOrderingKind POK, bool DeducedFromArrayBound,
1543 bool *HasDeducedAnyParam) {
1544
1545 // If the argument type is a pack expansion, look at its pattern.
1546 // This isn't explicitly called out
1547 if (const auto *AExp = dyn_cast<PackExpansionType>(A))
1548 A = AExp->getPattern();
1549 assert(!isa<PackExpansionType>(A.getCanonicalType()));
1550
1551 if (POK == PartialOrderingKind::Call) {
1552 // C++11 [temp.deduct.partial]p5:
1553 // Before the partial ordering is done, certain transformations are
1554 // performed on the types used for partial ordering:
1555 // - If P is a reference type, P is replaced by the type referred to.
1556 const ReferenceType *PRef = P->getAs<ReferenceType>();
1557 if (PRef)
1558 P = PRef->getPointeeType();
1559
1560 // - If A is a reference type, A is replaced by the type referred to.
1561 const ReferenceType *ARef = A->getAs<ReferenceType>();
1562 if (ARef)
1563 A = A->getPointeeType();
1564
1565 if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
1566 // C++11 [temp.deduct.partial]p9:
1567 // If, for a given type, deduction succeeds in both directions (i.e.,
1568 // the types are identical after the transformations above) and both
1569 // P and A were reference types [...]:
1570 // - if [one type] was an lvalue reference and [the other type] was
1571 // not, [the other type] is not considered to be at least as
1572 // specialized as [the first type]
1573 // - if [one type] is more cv-qualified than [the other type],
1574 // [the other type] is not considered to be at least as specialized
1575 // as [the first type]
1576 // Objective-C ARC adds:
1577 // - [one type] has non-trivial lifetime, [the other type] has
1578 // __unsafe_unretained lifetime, and the types are otherwise
1579 // identical
1580 //
1581 // A is "considered to be at least as specialized" as P iff deduction
1582 // succeeds, so we model this as a deduction failure. Note that
1583 // [the first type] is P and [the other type] is A here; the standard
1584 // gets this backwards.
1585 Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
1586 if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
1587 PQuals.isStrictSupersetOf(AQuals) ||
1588 (PQuals.hasNonTrivialObjCLifetime() &&
1589 AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1590 PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
1591 Info.FirstArg = TemplateArgument(P);
1592 Info.SecondArg = TemplateArgument(A);
1594 }
1595 }
1596 Qualifiers DiscardedQuals;
1597 // C++11 [temp.deduct.partial]p7:
1598 // Remove any top-level cv-qualifiers:
1599 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1600 // version of P.
1601 P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
1602 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1603 // version of A.
1604 A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
1605 } else {
1606 // C++0x [temp.deduct.call]p4 bullet 1:
1607 // - If the original P is a reference type, the deduced A (i.e., the type
1608 // referred to by the reference) can be more cv-qualified than the
1609 // transformed A.
1610 if (TDF & TDF_ParamWithReferenceType) {
1611 Qualifiers Quals;
1612 QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
1614 P = S.Context.getQualifiedType(UnqualP, Quals);
1615 }
1616
1617 if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
1618 // C++0x [temp.deduct.type]p10:
1619 // If P and A are function types that originated from deduction when
1620 // taking the address of a function template (14.8.2.2) or when deducing
1621 // template arguments from a function declaration (14.8.2.6) and Pi and
1622 // Ai are parameters of the top-level parameter-type-list of P and A,
1623 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1624 // is an lvalue reference, in
1625 // which case the type of Pi is changed to be the template parameter
1626 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1627 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1628 // deduced as X&. - end note ]
1629 TDF &= ~TDF_TopLevelParameterTypeList;
1630 if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
1632 P = P->getPointeeType();
1633 }
1634 }
1635
1636 // C++ [temp.deduct.type]p9:
1637 // A template type argument T, a template template argument TT or a
1638 // template non-type argument i can be deduced if P and A have one of
1639 // the following forms:
1640 //
1641 // T
1642 // cv-list T
1643 if (const auto *TTP = P->getAs<TemplateTypeParmType>()) {
1644 // Just skip any attempts to deduce from a placeholder type or a parameter
1645 // at a different depth.
1646 if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
1648
1649 unsigned Index = TTP->getIndex();
1650
1651 // If the argument type is an array type, move the qualifiers up to the
1652 // top level, so they can be matched with the qualifiers on the parameter.
1653 if (A->isArrayType()) {
1654 Qualifiers Quals;
1655 A = S.Context.getUnqualifiedArrayType(A, Quals);
1656 if (Quals)
1657 A = S.Context.getQualifiedType(A, Quals);
1658 }
1659
1660 // The argument type can not be less qualified than the parameter
1661 // type.
1662 if (!(TDF & TDF_IgnoreQualifiers) &&
1664 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1665 Info.FirstArg = TemplateArgument(P);
1666 Info.SecondArg = TemplateArgument(A);
1668 }
1669
1670 // Do not match a function type with a cv-qualified type.
1671 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1672 if (A->isFunctionType() && P.hasQualifiers())
1674
1675 assert(TTP->getDepth() == Info.getDeducedDepth() &&
1676 "saw template type parameter with wrong depth");
1677 assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&
1678 "Unresolved overloaded function");
1680
1681 // Remove any qualifiers on the parameter from the deduced type.
1682 // We checked the qualifiers for consistency above.
1683 Qualifiers DeducedQs = DeducedType.getQualifiers();
1684 Qualifiers ParamQs = P.getQualifiers();
1685 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1686 if (ParamQs.hasObjCGCAttr())
1687 DeducedQs.removeObjCGCAttr();
1688 if (ParamQs.hasAddressSpace())
1689 DeducedQs.removeAddressSpace();
1690 if (ParamQs.hasObjCLifetime())
1691 DeducedQs.removeObjCLifetime();
1692
1693 // Objective-C ARC:
1694 // If template deduction would produce a lifetime qualifier on a type
1695 // that is not a lifetime type, template argument deduction fails.
1696 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1698 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1699 Info.FirstArg = TemplateArgument(P);
1700 Info.SecondArg = TemplateArgument(A);
1702 }
1703
1704 // Objective-C ARC:
1705 // If template deduction would produce an argument type with lifetime type
1706 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1707 if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
1708 !DeducedQs.hasObjCLifetime())
1710
1711 DeducedType =
1712 S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
1713
1714 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1716 checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
1717 if (Result.isNull()) {
1718 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1719 Info.FirstArg = Deduced[Index];
1720 Info.SecondArg = NewDeduced;
1722 }
1723
1724 Deduced[Index] = Result;
1725 if (HasDeducedAnyParam)
1726 *HasDeducedAnyParam = true;
1728 }
1729
1730 // Set up the template argument deduction information for a failure.
1731 Info.FirstArg = TemplateArgument(P);
1732 Info.SecondArg = TemplateArgument(A);
1733
1734 // If the parameter is an already-substituted template parameter
1735 // pack, do nothing: we don't know which of its arguments to look
1736 // at, so we have to wait until all of the parameter packs in this
1737 // expansion have arguments.
1738 if (P->getAs<SubstTemplateTypeParmPackType>())
1740
1741 // Check the cv-qualifiers on the parameter and argument types.
1742 if (!(TDF & TDF_IgnoreQualifiers)) {
1743 if (TDF & TDF_ParamWithReferenceType) {
1746 } else if (TDF & TDF_ArgWithReferenceType) {
1747 // C++ [temp.deduct.conv]p4:
1748 // If the original A is a reference type, A can be more cv-qualified
1749 // than the deduced A
1750 if (!A.getQualifiers().compatiblyIncludes(P.getQualifiers(),
1751 S.getASTContext()))
1753
1754 // Strip out all extra qualifiers from the argument to figure out the
1755 // type we're converting to, prior to the qualification conversion.
1756 Qualifiers Quals;
1757 A = S.Context.getUnqualifiedArrayType(A, Quals);
1758 A = S.Context.getQualifiedType(A, P.getQualifiers());
1759 } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
1760 if (P.getCVRQualifiers() != A.getCVRQualifiers())
1762 }
1763 }
1764
1765 // If the parameter type is not dependent, there is nothing to deduce.
1766 if (!P->isDependentType()) {
1767 if (TDF & TDF_SkipNonDependent)
1770 : S.Context.hasSameType(P, A))
1775 if (!(TDF & TDF_IgnoreQualifiers))
1777 // Otherwise, when ignoring qualifiers, the types not having the same
1778 // unqualified type does not mean they do not match, so in this case we
1779 // must keep going and analyze with a non-dependent parameter type.
1780 }
1781
1782 switch (P.getCanonicalType()->getTypeClass()) {
1783 // Non-canonical types cannot appear here.
1784#define NON_CANONICAL_TYPE(Class, Base) \
1785 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1786#define TYPE(Class, Base)
1787#include "clang/AST/TypeNodes.inc"
1788
1789 case Type::TemplateTypeParm:
1790 case Type::SubstTemplateTypeParmPack:
1791 llvm_unreachable("Type nodes handled above");
1792
1793 case Type::Auto:
1794 // C++23 [temp.deduct.funcaddr]/3:
1795 // A placeholder type in the return type of a function template is a
1796 // non-deduced context.
1797 // There's no corresponding wording for [temp.deduct.decl], but we treat
1798 // it the same to match other compilers.
1799 if (P->isDependentType())
1801 [[fallthrough]];
1802 case Type::Builtin:
1803 case Type::VariableArray:
1804 case Type::Vector:
1805 case Type::FunctionNoProto:
1806 case Type::Record:
1807 case Type::Enum:
1808 case Type::ObjCObject:
1809 case Type::ObjCInterface:
1810 case Type::ObjCObjectPointer:
1811 case Type::BitInt:
1812 return (TDF & TDF_SkipNonDependent) ||
1813 ((TDF & TDF_IgnoreQualifiers)
1815 : S.Context.hasSameType(P, A))
1818
1819 // _Complex T [placeholder extension]
1820 case Type::Complex: {
1821 const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
1822 if (!CA)
1825 S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
1826 Deduced, TDF, degradeCallPartialOrderingKind(POK),
1827 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1828 }
1829
1830 // _Atomic T [extension]
1831 case Type::Atomic: {
1832 const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
1833 if (!AA)
1836 S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
1837 Deduced, TDF, degradeCallPartialOrderingKind(POK),
1838 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1839 }
1840
1841 // T *
1842 case Type::Pointer: {
1843 QualType PointeeType;
1844 if (const auto *PA = A->getAs<PointerType>()) {
1845 PointeeType = PA->getPointeeType();
1846 } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
1847 PointeeType = PA->getPointeeType();
1848 } else {
1850 }
1852 S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
1853 PointeeType, Info, Deduced,
1856 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1857 }
1858
1859 // T &
1860 case Type::LValueReference: {
1861 const auto *RP = P->castAs<LValueReferenceType>(),
1862 *RA = A->getAs<LValueReferenceType>();
1863 if (!RA)
1865
1867 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1868 Deduced, 0, degradeCallPartialOrderingKind(POK),
1869 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1870 }
1871
1872 // T && [C++0x]
1873 case Type::RValueReference: {
1874 const auto *RP = P->castAs<RValueReferenceType>(),
1875 *RA = A->getAs<RValueReferenceType>();
1876 if (!RA)
1878
1880 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1881 Deduced, 0, degradeCallPartialOrderingKind(POK),
1882 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1883 }
1884
1885 // T [] (implied, but not stated explicitly)
1886 case Type::IncompleteArray: {
1887 const auto *IAA = S.Context.getAsIncompleteArrayType(A);
1888 if (!IAA)
1890
1891 const auto *IAP = S.Context.getAsIncompleteArrayType(P);
1892 assert(IAP && "Template parameter not of incomplete array type");
1893
1895 S, TemplateParams, IAP->getElementType(), IAA->getElementType(), Info,
1896 Deduced, TDF & TDF_IgnoreQualifiers,
1898 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1899 }
1900
1901 // T [integer-constant]
1902 case Type::ConstantArray: {
1903 const auto *CAA = S.Context.getAsConstantArrayType(A),
1905 assert(CAP);
1906 if (!CAA || CAA->getSize() != CAP->getSize())
1908
1910 S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
1911 Deduced, TDF & TDF_IgnoreQualifiers,
1913 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1914 }
1915
1916 // type [i]
1917 case Type::DependentSizedArray: {
1918 const auto *AA = S.Context.getAsArrayType(A);
1919 if (!AA)
1921
1922 // Check the element type of the arrays
1923 const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
1924 assert(DAP);
1926 S, TemplateParams, DAP->getElementType(), AA->getElementType(),
1927 Info, Deduced, TDF & TDF_IgnoreQualifiers,
1929 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1931 return Result;
1932
1933 // Determine the array bound is something we can deduce.
1934 const NonTypeTemplateParmDecl *NTTP =
1935 getDeducedParameterFromExpr(Info, DAP->getSizeExpr());
1936 if (!NTTP)
1938
1939 // We can perform template argument deduction for the given non-type
1940 // template parameter.
1941 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1942 "saw non-type template parameter with wrong depth");
1943 if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
1944 llvm::APSInt Size(CAA->getSize());
1946 S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
1947 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
1948 Deduced, HasDeducedAnyParam);
1949 }
1950 if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
1951 if (DAA->getSizeExpr())
1953 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info,
1954 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
1955
1956 // Incomplete type does not match a dependently-sized array type
1958 }
1959
1960 // type(*)(T)
1961 // T(*)()
1962 // T(*)(T)
1963 case Type::FunctionProto: {
1964 const auto *FPP = P->castAs<FunctionProtoType>(),
1965 *FPA = A->getAs<FunctionProtoType>();
1966 if (!FPA)
1968
1969 if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
1970 FPP->getRefQualifier() != FPA->getRefQualifier() ||
1971 FPP->isVariadic() != FPA->isVariadic())
1973
1974 // Check return types.
1976 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
1977 Info, Deduced, 0, degradeCallPartialOrderingKind(POK),
1978 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1980 return Result;
1981
1982 // Check parameter types.
1984 S, TemplateParams, FPP->param_types(), FPA->param_types(), Info,
1985 Deduced, TDF & TDF_TopLevelParameterTypeList, POK,
1986 HasDeducedAnyParam,
1987 /*HasDeducedParam=*/nullptr);
1989 return Result;
1990
1993
1994 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1995 // deducing through the noexcept-specifier if it's part of the canonical
1996 // type. libstdc++ relies on this.
1997 Expr *NoexceptExpr = FPP->getNoexceptExpr();
1998 if (const NonTypeTemplateParmDecl *NTTP =
1999 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
2000 : nullptr) {
2001 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
2002 "saw non-type template parameter with wrong depth");
2003
2004 llvm::APSInt Noexcept(1);
2005 switch (FPA->canThrow()) {
2006 case CT_Cannot:
2007 Noexcept = 1;
2008 [[fallthrough]];
2009
2010 case CT_Can:
2011 // We give E in noexcept(E) the "deduced from array bound" treatment.
2012 // FIXME: Should we?
2014 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
2015 /*DeducedFromArrayBound=*/true, Info,
2016 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2017
2018 case CT_Dependent:
2019 if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
2021 S, TemplateParams, NTTP, ArgNoexceptExpr, Info,
2022 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2023 // Can't deduce anything from throw(T...).
2024 break;
2025 }
2026 }
2027 // FIXME: Detect non-deduced exception specification mismatches?
2028 //
2029 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
2030 // top-level differences in noexcept-specifications.
2031
2033 }
2034
2035 case Type::InjectedClassName:
2036 // Treat a template's injected-class-name as if the template
2037 // specialization type had been used.
2038
2039 // template-name<T> (where template-name refers to a class template)
2040 // template-name<i>
2041 // TT<T>
2042 // TT<i>
2043 // TT<>
2044 case Type::TemplateSpecialization: {
2045 // When Arg cannot be a derived class, we can just try to deduce template
2046 // arguments from the template-id.
2047 if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
2048 return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
2049 POK != PartialOrderingKind::None,
2050 Deduced, HasDeducedAnyParam);
2051
2052 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
2053 Deduced.end());
2054
2056 S, TemplateParams, P, A, Info, POK != PartialOrderingKind::None,
2057 Deduced, HasDeducedAnyParam);
2059 return Result;
2060
2061 // We cannot inspect base classes as part of deduction when the type
2062 // is incomplete, so either instantiate any templates necessary to
2063 // complete the type, or skip over it if it cannot be completed.
2064 if (!S.isCompleteType(Info.getLocation(), A))
2065 return Result;
2066
2067 const CXXRecordDecl *RD = A->getAsCXXRecordDecl();
2068 if (RD->isInvalidDecl())
2069 return Result;
2070
2071 // Reset the incorrectly deduced argument from above.
2072 Deduced = DeducedOrig;
2073
2074 // Check bases according to C++14 [temp.deduct.call] p4b3:
2075 auto BaseResult = DeduceTemplateBases(S, RD, TemplateParams, P, Info,
2076 POK != PartialOrderingKind::None,
2077 Deduced, HasDeducedAnyParam);
2079 : Result;
2080 }
2081
2082 // T type::*
2083 // T T::*
2084 // T (type::*)()
2085 // type (T::*)()
2086 // type (type::*)(T)
2087 // type (T::*)(T)
2088 // T (type::*)(T)
2089 // T (T::*)()
2090 // T (T::*)(T)
2091 case Type::MemberPointer: {
2092 const auto *MPP = P->castAs<MemberPointerType>(),
2093 *MPA = A->getAs<MemberPointerType>();
2094 if (!MPA)
2096
2097 QualType PPT = MPP->getPointeeType();
2098 if (PPT->isFunctionType())
2099 S.adjustMemberFunctionCC(PPT, /*HasThisPointer=*/false,
2100 /*IsCtorOrDtor=*/false, Info.getLocation());
2101 QualType APT = MPA->getPointeeType();
2102 if (APT->isFunctionType())
2103 S.adjustMemberFunctionCC(APT, /*HasThisPointer=*/false,
2104 /*IsCtorOrDtor=*/false, Info.getLocation());
2105
2106 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
2108 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF,
2110 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2112 return Result;
2114 S, TemplateParams, QualType(MPP->getClass(), 0),
2115 QualType(MPA->getClass(), 0), Info, Deduced, SubTDF,
2117 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2118 }
2119
2120 // (clang extension)
2121 //
2122 // type(^)(T)
2123 // T(^)()
2124 // T(^)(T)
2125 case Type::BlockPointer: {
2126 const auto *BPP = P->castAs<BlockPointerType>(),
2127 *BPA = A->getAs<BlockPointerType>();
2128 if (!BPA)
2131 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
2132 Deduced, 0, degradeCallPartialOrderingKind(POK),
2133 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2134 }
2135
2136 // (clang extension)
2137 //
2138 // T __attribute__(((ext_vector_type(<integral constant>))))
2139 case Type::ExtVector: {
2140 const auto *VP = P->castAs<ExtVectorType>();
2141 QualType ElementType;
2142 if (const auto *VA = A->getAs<ExtVectorType>()) {
2143 // Make sure that the vectors have the same number of elements.
2144 if (VP->getNumElements() != VA->getNumElements())
2146 ElementType = VA->getElementType();
2147 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2148 // We can't check the number of elements, since the argument has a
2149 // dependent number of elements. This can only occur during partial
2150 // ordering.
2151 ElementType = VA->getElementType();
2152 } else {
2154 }
2155 // Perform deduction on the element types.
2157 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
2159 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2160 }
2161
2162 case Type::DependentVector: {
2163 const auto *VP = P->castAs<DependentVectorType>();
2164
2165 if (const auto *VA = A->getAs<VectorType>()) {
2166 // Perform deduction on the element types.
2168 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2169 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2170 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2172 return Result;
2173
2174 // Perform deduction on the vector size, if we can.
2175 const NonTypeTemplateParmDecl *NTTP =
2176 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2177 if (!NTTP)
2179
2180 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2181 ArgSize = VA->getNumElements();
2182 // Note that we use the "array bound" rules here; just like in that
2183 // case, we don't have any particular type for the vector size, but
2184 // we can provide one if necessary.
2186 S, TemplateParams, NTTP, ArgSize, S.Context.UnsignedIntTy, true,
2187 Info, POK != PartialOrderingKind::None, Deduced,
2188 HasDeducedAnyParam);
2189 }
2190
2191 if (const auto *VA = A->getAs<DependentVectorType>()) {
2192 // Perform deduction on the element types.
2194 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2195 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2196 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2198 return Result;
2199
2200 // Perform deduction on the vector size, if we can.
2201 const NonTypeTemplateParmDecl *NTTP =
2202 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2203 if (!NTTP)
2205
2207 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2208 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2209 }
2210
2212 }
2213
2214 // (clang extension)
2215 //
2216 // T __attribute__(((ext_vector_type(N))))
2217 case Type::DependentSizedExtVector: {
2218 const auto *VP = P->castAs<DependentSizedExtVectorType>();
2219
2220 if (const auto *VA = A->getAs<ExtVectorType>()) {
2221 // Perform deduction on the element types.
2223 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2224 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2225 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2227 return Result;
2228
2229 // Perform deduction on the vector size, if we can.
2230 const NonTypeTemplateParmDecl *NTTP =
2231 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2232 if (!NTTP)
2234
2235 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2236 ArgSize = VA->getNumElements();
2237 // Note that we use the "array bound" rules here; just like in that
2238 // case, we don't have any particular type for the vector size, but
2239 // we can provide one if necessary.
2241 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2242 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2243 }
2244
2245 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2246 // Perform deduction on the element types.
2248 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2249 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2250 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2252 return Result;
2253
2254 // Perform deduction on the vector size, if we can.
2255 const NonTypeTemplateParmDecl *NTTP =
2256 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2257 if (!NTTP)
2259
2261 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2262 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2263 }
2264
2266 }
2267
2268 // (clang extension)
2269 //
2270 // T __attribute__((matrix_type(<integral constant>,
2271 // <integral constant>)))
2272 case Type::ConstantMatrix: {
2273 const auto *MP = P->castAs<ConstantMatrixType>(),
2274 *MA = A->getAs<ConstantMatrixType>();
2275 if (!MA)
2277
2278 // Check that the dimensions are the same
2279 if (MP->getNumRows() != MA->getNumRows() ||
2280 MP->getNumColumns() != MA->getNumColumns()) {
2282 }
2283 // Perform deduction on element types.
2285 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2286 Deduced, TDF, degradeCallPartialOrderingKind(POK),
2287 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2288 }
2289
2290 case Type::DependentSizedMatrix: {
2291 const auto *MP = P->castAs<DependentSizedMatrixType>();
2292 const auto *MA = A->getAs<MatrixType>();
2293 if (!MA)
2295
2296 // Check the element type of the matrixes.
2298 S, TemplateParams, MP->getElementType(), MA->getElementType(),
2299 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2300 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2302 return Result;
2303
2304 // Try to deduce a matrix dimension.
2305 auto DeduceMatrixArg =
2306 [&S, &Info, &Deduced, &TemplateParams, &HasDeducedAnyParam, POK](
2307 Expr *ParamExpr, const MatrixType *A,
2308 unsigned (ConstantMatrixType::*GetArgDimension)() const,
2309 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2310 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2311 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
2312 if (!ParamExpr->isValueDependent()) {
2313 std::optional<llvm::APSInt> ParamConst =
2314 ParamExpr->getIntegerConstantExpr(S.Context);
2315 if (!ParamConst)
2317
2318 if (ACM) {
2319 if ((ACM->*GetArgDimension)() == *ParamConst)
2322 }
2323
2324 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2325 if (std::optional<llvm::APSInt> ArgConst =
2326 ArgExpr->getIntegerConstantExpr(S.Context))
2327 if (*ArgConst == *ParamConst)
2330 }
2331
2332 const NonTypeTemplateParmDecl *NTTP =
2333 getDeducedParameterFromExpr(Info, ParamExpr);
2334 if (!NTTP)
2336
2337 if (ACM) {
2338 llvm::APSInt ArgConst(
2340 ArgConst = (ACM->*GetArgDimension)();
2342 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
2343 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
2344 Deduced, HasDeducedAnyParam);
2345 }
2346
2348 S, TemplateParams, NTTP, (ADM->*GetArgDimensionExpr)(), Info,
2349 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2350 };
2351
2352 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
2356 return Result;
2357
2358 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2361 }
2362
2363 // (clang extension)
2364 //
2365 // T __attribute__(((address_space(N))))
2366 case Type::DependentAddressSpace: {
2367 const auto *ASP = P->castAs<DependentAddressSpaceType>();
2368
2369 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
2370 // Perform deduction on the pointer type.
2372 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2373 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2374 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2376 return Result;
2377
2378 // Perform deduction on the address space, if we can.
2379 const NonTypeTemplateParmDecl *NTTP =
2380 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2381 if (!NTTP)
2383
2385 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info,
2386 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2387 }
2388
2390 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2391 false);
2392 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
2393
2394 // Perform deduction on the pointer types.
2396 S, TemplateParams, ASP->getPointeeType(),
2397 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF,
2399 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2401 return Result;
2402
2403 // Perform deduction on the address space, if we can.
2404 const NonTypeTemplateParmDecl *NTTP =
2405 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2406 if (!NTTP)
2408
2410 S, TemplateParams, NTTP, ArgAddressSpace, S.Context.IntTy, true,
2411 Info, POK != PartialOrderingKind::None, Deduced,
2412 HasDeducedAnyParam);
2413 }
2414
2416 }
2417 case Type::DependentBitInt: {
2418 const auto *IP = P->castAs<DependentBitIntType>();
2419
2420 if (const auto *IA = A->getAs<BitIntType>()) {
2421 if (IP->isUnsigned() != IA->isUnsigned())
2423
2424 const NonTypeTemplateParmDecl *NTTP =
2425 getDeducedParameterFromExpr(Info, IP->getNumBitsExpr());
2426 if (!NTTP)
2428
2429 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2430 ArgSize = IA->getNumBits();
2431
2433 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2434 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2435 }
2436
2437 if (const auto *IA = A->getAs<DependentBitIntType>()) {
2438 if (IP->isUnsigned() != IA->isUnsigned())
2441 }
2442
2444 }
2445
2446 case Type::TypeOfExpr:
2447 case Type::TypeOf:
2448 case Type::DependentName:
2449 case Type::UnresolvedUsing:
2450 case Type::Decltype:
2451 case Type::UnaryTransform:
2452 case Type::DeducedTemplateSpecialization:
2453 case Type::DependentTemplateSpecialization:
2454 case Type::PackExpansion:
2455 case Type::Pipe:
2456 case Type::ArrayParameter:
2457 case Type::HLSLAttributedResource:
2458 // No template argument deduction for these types
2460
2461 case Type::PackIndexing: {
2462 const PackIndexingType *PIT = P->getAs<PackIndexingType>();
2463 if (PIT->hasSelectedType()) {
2465 S, TemplateParams, PIT->getSelectedType(), A, Info, Deduced, TDF,
2467 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2468 }
2470 }
2471 }
2472
2473 llvm_unreachable("Invalid Type Class!");
2474}
2475
2481 bool *HasDeducedAnyParam) {
2482 // If the template argument is a pack expansion, perform template argument
2483 // deduction against the pattern of that expansion. This only occurs during
2484 // partial ordering.
2485 if (A.isPackExpansion())
2487
2488 switch (P.getKind()) {
2490 llvm_unreachable("Null template argument in parameter list");
2491
2495 S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0,
2496 PartialOrdering ? PartialOrderingKind::NonCall
2497 : PartialOrderingKind::None,
2498 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2499 Info.FirstArg = P;
2500 Info.SecondArg = A;
2502
2504 // PartialOrdering does not matter here, since template specializations are
2505 // not being deduced.
2508 S, TemplateParams, P.getAsTemplate(), A.getAsTemplate(), Info,
2509 /*DefaultArguments=*/{}, /*PartialOrdering=*/false, Deduced,
2510 HasDeducedAnyParam);
2511 Info.FirstArg = P;
2512 Info.SecondArg = A;
2514
2516 llvm_unreachable("caller should handle pack expansions");
2517
2520 isSameDeclaration(P.getAsDecl(), A.getAsDecl()))
2522
2523 Info.FirstArg = P;
2524 Info.SecondArg = A;
2526
2529 S.Context.hasSameType(P.getNullPtrType(), A.getNullPtrType()))
2531
2532 Info.FirstArg = P;
2533 Info.SecondArg = A;
2535
2538 if (hasSameExtendedValue(P.getAsIntegral(), A.getAsIntegral()))
2540 }
2541 Info.FirstArg = P;
2542 Info.SecondArg = A;
2544
2549
2550 Info.FirstArg = P;
2551 Info.SecondArg = A;
2553
2555 if (const NonTypeTemplateParmDecl *NTTP =
2556 getDeducedParameterFromExpr(Info, P.getAsExpr())) {
2557 switch (A.getKind()) {
2562 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2564 HasDeducedAnyParam);
2565
2568 S, TemplateParams, NTTP, A.getNullPtrType(), Info, PartialOrdering,
2569 Deduced, HasDeducedAnyParam);
2570
2573 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
2574 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
2575
2581 Info.FirstArg = P;
2582 Info.SecondArg = A;
2584 }
2585 llvm_unreachable("Unknown template argument kind");
2586 }
2587
2588 // Can't deduce anything, but that's okay.
2591 llvm_unreachable("Argument packs should be expanded by the caller!");
2592 }
2593
2594 llvm_unreachable("Invalid TemplateArgument Kind!");
2595}
2596
2597/// Determine whether there is a template argument to be used for
2598/// deduction.
2599///
2600/// This routine "expands" argument packs in-place, overriding its input
2601/// parameters so that \c Args[ArgIdx] will be the available template argument.
2602///
2603/// \returns true if there is another template argument (which will be at
2604/// \c Args[ArgIdx]), false otherwise.
2606 unsigned &ArgIdx) {
2607 if (ArgIdx == Args.size())
2608 return false;
2609
2610 const TemplateArgument &Arg = Args[ArgIdx];
2611 if (Arg.getKind() != TemplateArgument::Pack)
2612 return true;
2613
2614 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2615 Args = Arg.pack_elements();
2616 ArgIdx = 0;
2617 return ArgIdx < Args.size();
2618}
2619
2620/// Determine whether the given set of template arguments has a pack
2621/// expansion that is not the last template argument.
2623 bool FoundPackExpansion = false;
2624 for (const auto &A : Args) {
2625 if (FoundPackExpansion)
2626 return true;
2627
2628 if (A.getKind() == TemplateArgument::Pack)
2629 return hasPackExpansionBeforeEnd(A.pack_elements());
2630
2631 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2632 // templates, it should not be treated as a pack expansion.
2633 if (A.isPackExpansion())
2634 FoundPackExpansion = true;
2635 }
2636
2637 return false;
2638}
2639
2646 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
2647 PackFold PackFold, bool *HasDeducedAnyParam) {
2648 if (PackFold == PackFold::ArgumentToParameter)
2649 std::swap(Ps, As);
2650 // C++0x [temp.deduct.type]p9:
2651 // If the template argument list of P contains a pack expansion that is not
2652 // the last template argument, the entire template argument list is a
2653 // non-deduced context.
2656
2657 // C++0x [temp.deduct.type]p9:
2658 // If P has a form that contains <T> or <i>, then each argument Pi of the
2659 // respective template argument list P is compared with the corresponding
2660 // argument Ai of the corresponding template argument list of A.
2661 unsigned ArgIdx = 0, ParamIdx = 0;
2663 const TemplateArgument &P = Ps[ParamIdx];
2664 if (!P.isPackExpansion()) {
2665 // The simple case: deduce template arguments by matching Pi and Ai.
2666
2667 // Check whether we have enough arguments.
2668 if (!hasTemplateArgumentForDeduction(As, ArgIdx))
2669 return NumberOfArgumentsMustMatch
2672
2673 // C++1z [temp.deduct.type]p9:
2674 // During partial ordering, if Ai was originally a pack expansion [and]
2675 // Pi is not a pack expansion, template argument deduction fails.
2676 if (As[ArgIdx].isPackExpansion())
2678
2679 // Perform deduction for this Pi/Ai pair.
2680 TemplateArgument Pi = P, Ai = As[ArgIdx];
2681 if (PackFold == PackFold::ArgumentToParameter)
2682 std::swap(Pi, Ai);
2683 if (auto Result = DeduceTemplateArguments(S, TemplateParams, Pi, Ai, Info,
2684 PartialOrdering, Deduced,
2685 HasDeducedAnyParam);
2687 return Result;
2688
2689 // Move to the next argument.
2690 ++ArgIdx;
2691 continue;
2692 }
2693
2694 // The parameter is a pack expansion.
2695
2696 // C++0x [temp.deduct.type]p9:
2697 // If Pi is a pack expansion, then the pattern of Pi is compared with
2698 // each remaining argument in the template argument list of A. Each
2699 // comparison deduces template arguments for subsequent positions in the
2700 // template parameter packs expanded by Pi.
2701 TemplateArgument Pattern = P.getPackExpansionPattern();
2702
2703 // Prepare to deduce the packs within the pattern.
2704 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2705
2706 // Keep track of the deduced template arguments for each parameter pack
2707 // expanded by this pack expansion (the outer index) and for each
2708 // template argument (the inner SmallVectors).
2709 for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
2710 PackScope.hasNextElement();
2711 ++ArgIdx) {
2712 TemplateArgument Pi = Pattern, Ai = As[ArgIdx];
2713 if (PackFold == PackFold::ArgumentToParameter)
2714 std::swap(Pi, Ai);
2715 // Deduce template arguments from the pattern.
2716 if (auto Result = DeduceTemplateArguments(S, TemplateParams, Pi, Ai, Info,
2717 PartialOrdering, Deduced,
2718 HasDeducedAnyParam);
2720 return Result;
2721
2722 PackScope.nextPackElement();
2723 }
2724
2725 // Build argument packs for each of the parameter packs expanded by this
2726 // pack expansion.
2727 if (auto Result = PackScope.finish();
2729 return Result;
2730 }
2731
2733}
2734
2739 bool NumberOfArgumentsMustMatch) {
2740 return ::DeduceTemplateArguments(
2741 *this, TemplateParams, Ps, As, Info, Deduced, NumberOfArgumentsMustMatch,
2742 /*PartialOrdering=*/false, PackFold::ParameterToArgument,
2743 /*HasDeducedAnyParam=*/nullptr);
2744}
2745
2746/// Determine whether two template arguments are the same.
2747static bool isSameTemplateArg(ASTContext &Context,
2749 const TemplateArgument &Y,
2750 bool PartialOrdering,
2751 bool PackExpansionMatchesPack = false) {
2752 // If we're checking deduced arguments (X) against original arguments (Y),
2753 // we will have flattened packs to non-expansions in X.
2754 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2755 X = X.getPackExpansionPattern();
2756
2757 if (X.getKind() != Y.getKind())
2758 return false;
2759
2760 switch (X.getKind()) {
2762 llvm_unreachable("Comparing NULL template argument");
2763
2765 return Context.getCanonicalType(X.getAsType()) ==
2766 Context.getCanonicalType(Y.getAsType());
2767
2769 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
2770
2772 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2773
2776 return Context.getCanonicalTemplateName(
2777 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2780
2782 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2783
2785 return X.structurallyEquals(Y);
2786
2788 llvm::FoldingSetNodeID XID, YID;
2789 X.getAsExpr()->Profile(XID, Context, true);
2790 Y.getAsExpr()->Profile(YID, Context, true);
2791 return XID == YID;
2792 }
2793
2795 unsigned PackIterationSize = X.pack_size();
2796 if (X.pack_size() != Y.pack_size()) {
2797 if (!PartialOrdering)
2798 return false;
2799
2800 // C++0x [temp.deduct.type]p9:
2801 // During partial ordering, if Ai was originally a pack expansion:
2802 // - if P does not contain a template argument corresponding to Ai
2803 // then Ai is ignored;
2804 bool XHasMoreArg = X.pack_size() > Y.pack_size();
2805 if (!(XHasMoreArg && X.pack_elements().back().isPackExpansion()) &&
2806 !(!XHasMoreArg && Y.pack_elements().back().isPackExpansion()))
2807 return false;
2808
2809 if (XHasMoreArg)
2810 PackIterationSize = Y.pack_size();
2811 }
2812
2813 ArrayRef<TemplateArgument> XP = X.pack_elements();
2815 for (unsigned i = 0; i < PackIterationSize; ++i)
2816 if (!isSameTemplateArg(Context, XP[i], YP[i], PartialOrdering,
2817 PackExpansionMatchesPack))
2818 return false;
2819 return true;
2820 }
2821 }
2822
2823 llvm_unreachable("Invalid TemplateArgument Kind!");
2824}
2825
2828 QualType NTTPType, SourceLocation Loc,
2830 switch (Arg.getKind()) {
2832 llvm_unreachable("Can't get a NULL template argument here");
2833
2835 return TemplateArgumentLoc(
2837
2839 if (NTTPType.isNull())
2840 NTTPType = Arg.getParamTypeForDecl();
2843 .getAs<Expr>();
2845 }
2846
2848 if (NTTPType.isNull())
2849 NTTPType = Arg.getNullPtrType();
2851 .getAs<Expr>();
2852 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2853 E);
2854 }
2855
2860 }
2861
2867 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2868 else if (QualifiedTemplateName *QTN =
2869 Template.getAsQualifiedTemplateName())
2870 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2871
2873 return TemplateArgumentLoc(Context, Arg,
2874 Builder.getWithLocInContext(Context), Loc);
2875
2876 return TemplateArgumentLoc(
2877 Context, Arg, Builder.getWithLocInContext(Context), Loc, Loc);
2878 }
2879
2881 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2882
2885 }
2886
2887 llvm_unreachable("Invalid TemplateArgument Kind!");
2888}
2889
2892 SourceLocation Location) {
2894 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2895}
2896
2897/// Convert the given deduced template argument and add it to the set of
2898/// fully-converted template arguments.
2900 Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template,
2901 TemplateDeductionInfo &Info, bool IsDeduced,
2902 SmallVectorImpl<TemplateArgument> &SugaredOutput,
2903 SmallVectorImpl<TemplateArgument> &CanonicalOutput) {
2904 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2905 unsigned ArgumentPackIndex) {
2906 // Convert the deduced template argument into a template
2907 // argument that we can check, almost as if the user had written
2908 // the template argument explicitly.
2910 Arg, QualType(), Info.getLocation(), Param);
2911
2912 // Check the template argument, converting it as necessary.
2913 return S.CheckTemplateArgument(
2914 Param, ArgLoc, Template, Template->getLocation(),
2915 Template->getSourceRange().getEnd(), ArgumentPackIndex, SugaredOutput,
2916 CanonicalOutput,
2917 IsDeduced
2921 };
2922
2923 if (Arg.getKind() == TemplateArgument::Pack) {
2924 // This is a template argument pack, so check each of its arguments against
2925 // the template parameter.
2926 SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
2927 CanonicalPackedArgsBuilder;
2928 for (const auto &P : Arg.pack_elements()) {
2929 // When converting the deduced template argument, append it to the
2930 // general output list. We need to do this so that the template argument
2931 // checking logic has all of the prior template arguments available.
2932 DeducedTemplateArgument InnerArg(P);
2934 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2935 "deduced nested pack");
2936 if (P.isNull()) {
2937 // We deduced arguments for some elements of this pack, but not for
2938 // all of them. This happens if we get a conditionally-non-deduced
2939 // context in a pack expansion (such as an overload set in one of the
2940 // arguments).
2941 S.Diag(Param->getLocation(),
2942 diag::err_template_arg_deduced_incomplete_pack)
2943 << Arg << Param;
2944 return true;
2945 }
2946 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
2947 return true;
2948
2949 // Move the converted template argument into our argument pack.
2950 SugaredPackedArgsBuilder.push_back(SugaredOutput.pop_back_val());
2951 CanonicalPackedArgsBuilder.push_back(CanonicalOutput.pop_back_val());
2952 }
2953
2954 // If the pack is empty, we still need to substitute into the parameter
2955 // itself, in case that substitution fails.
2956 if (SugaredPackedArgsBuilder.empty()) {
2958 MultiLevelTemplateArgumentList Args(Template, SugaredOutput,
2959 /*Final=*/true);
2960
2961 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2962 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2963 NTTP, SugaredOutput,
2964 Template->getSourceRange());
2965 if (Inst.isInvalid() ||
2966 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2967 NTTP->getDeclName()).isNull())
2968 return true;
2969 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2970 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2971 TTP, SugaredOutput,
2972 Template->getSourceRange());
2973 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2974 return true;
2975 }
2976 // For type parameters, no substitution is ever required.
2977 }
2978
2979 // Create the resulting argument pack.
2980 SugaredOutput.push_back(
2981 TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
2982 CanonicalOutput.push_back(TemplateArgument::CreatePackCopy(
2983 S.Context, CanonicalPackedArgsBuilder));
2984 return false;
2985 }
2986
2987 return ConvertArg(Arg, 0);
2988}
2989
2990// FIXME: This should not be a template, but
2991// ClassTemplatePartialSpecializationDecl sadly does not derive from
2992// TemplateDecl.
2993/// \param IsIncomplete When used, we only consider template parameters that
2994/// were deduced, disregarding any default arguments. After the function
2995/// finishes, the object pointed at will contain a value indicating if the
2996/// conversion was actually incomplete.
2997template <typename TemplateDeclT>
2999 Sema &S, TemplateDeclT *Template, bool IsDeduced,
3002 SmallVectorImpl<TemplateArgument> &SugaredBuilder,
3003 SmallVectorImpl<TemplateArgument> &CanonicalBuilder,
3004 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
3005 unsigned NumAlreadyConverted = 0, bool *IsIncomplete = nullptr) {
3006 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3007
3008 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3009 NamedDecl *Param = TemplateParams->getParam(I);
3010
3011 // C++0x [temp.arg.explicit]p3:
3012 // A trailing template parameter pack (14.5.3) not otherwise deduced will
3013 // be deduced to an empty sequence of template arguments.
3014 // FIXME: Where did the word "trailing" come from?
3015 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
3016 if (auto Result =
3017 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish();
3019 return Result;
3020 }
3021
3022 if (!Deduced[I].isNull()) {
3023 if (I < NumAlreadyConverted) {
3024 // We may have had explicitly-specified template arguments for a
3025 // template parameter pack (that may or may not have been extended
3026 // via additional deduced arguments).
3027 if (Param->isParameterPack() && CurrentInstantiationScope &&
3028 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
3029 // Forget the partially-substituted pack; its substitution is now
3030 // complete.
3031 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
3032 // We still need to check the argument in case it was extended by
3033 // deduction.
3034 } else {
3035 // We have already fully type-checked and converted this
3036 // argument, because it was explicitly-specified. Just record the
3037 // presence of this argument.
3038 SugaredBuilder.push_back(Deduced[I]);
3039 CanonicalBuilder.push_back(
3041 continue;
3042 }
3043 }
3044
3045 // We may have deduced this argument, so it still needs to be
3046 // checked and converted.
3047 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
3048 IsDeduced, SugaredBuilder,
3049 CanonicalBuilder)) {
3050 Info.Param = makeTemplateParameter(Param);
3051 // FIXME: These template arguments are temporary. Free them!
3052 Info.reset(
3053 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3054 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3056 }
3057
3058 continue;
3059 }
3060
3061 // [C++26][temp.deduct.partial]p12 - When partial ordering, it's ok for
3062 // template parameters to remain not deduced. As a provisional fix for a
3063 // core issue that does not exist yet, which may be related to CWG2160, only
3064 // consider template parameters that were deduced, disregarding any default
3065 // arguments.
3066 if (IsIncomplete) {
3067 *IsIncomplete = true;
3068 SugaredBuilder.push_back({});
3069 CanonicalBuilder.push_back({});
3070 continue;
3071 }
3072
3073 // Substitute into the default template argument, if available.
3074 bool HasDefaultArg = false;
3075 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
3076 if (!TD) {
3077 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
3078 isa<VarTemplatePartialSpecializationDecl>(Template));
3080 }
3081
3082 TemplateArgumentLoc DefArg;
3083 {
3084 Qualifiers ThisTypeQuals;
3085 CXXRecordDecl *ThisContext = nullptr;
3086 if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
3087 if (Rec->isLambda())
3088 if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
3089 ThisContext = Method->getParent();
3090 ThisTypeQuals = Method->getMethodQualifiers();
3091 }
3092
3093 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
3094 S.getLangOpts().CPlusPlus17);
3095
3097 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param,
3098 SugaredBuilder, CanonicalBuilder, HasDefaultArg);
3099 }
3100
3101 // If there was no default argument, deduction is incomplete.
3102 if (DefArg.getArgument().isNull()) {
3104 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
3105 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3106 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3107
3110 }
3111
3112 // Check whether we can actually use the default argument.
3114 Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
3115 0, SugaredBuilder, CanonicalBuilder, Sema::CTAK_Specified)) {
3117 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
3118 // FIXME: These template arguments are temporary. Free them!
3119 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3120 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3122 }
3123
3124 // If we get here, we successfully used the default template argument.
3125 }
3126
3128}
3129
3131 if (auto *DC = dyn_cast<DeclContext>(D))
3132 return DC;
3133 return D->getDeclContext();
3134}
3135
3136template<typename T> struct IsPartialSpecialization {
3137 static constexpr bool value = false;
3138};
3139template<>
3141 static constexpr bool value = true;
3142};
3143template<>
3145 static constexpr bool value = true;
3146};
3147template <typename TemplateDeclT>
3148static bool DeducedArgsNeedReplacement(TemplateDeclT *Template) {
3149 return false;
3150}
3151template <>
3154 return !Spec->isClassScopeExplicitSpecialization();
3155}
3156template <>
3159 return !Spec->isClassScopeExplicitSpecialization();
3160}
3161
3162template <typename TemplateDeclT>
3164CheckDeducedArgumentConstraints(Sema &S, TemplateDeclT *Template,
3165 ArrayRef<TemplateArgument> SugaredDeducedArgs,
3166 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
3167 TemplateDeductionInfo &Info) {
3168 llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
3169 Template->getAssociatedConstraints(AssociatedConstraints);
3170
3171 std::optional<ArrayRef<TemplateArgument>> Innermost;
3172 // If we don't need to replace the deduced template arguments,
3173 // we can add them immediately as the inner-most argument list.
3174 if (!DeducedArgsNeedReplacement(Template))
3175 Innermost = CanonicalDeducedArgs;
3176
3178 Template, Template->getDeclContext(), /*Final=*/false, Innermost,
3179 /*RelativeToPrimary=*/true, /*Pattern=*/
3180 nullptr, /*ForConstraintInstantiation=*/true);
3181
3182 // getTemplateInstantiationArgs picks up the non-deduced version of the
3183 // template args when this is a variable template partial specialization and
3184 // not class-scope explicit specialization, so replace with Deduced Args
3185 // instead of adding to inner-most.
3186 if (!Innermost)
3187 MLTAL.replaceInnermostTemplateArguments(Template, CanonicalDeducedArgs);
3188
3189 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
3190 Info.getLocation(),
3193 Info.reset(
3194 TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
3195 TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
3197 }
3199}
3200
3201/// Complete template argument deduction for a partial specialization.
3202template <typename T>
3203static std::enable_if_t<IsPartialSpecialization<T>::value,
3206 Sema &S, T *Partial, bool IsPartialOrdering,
3207 ArrayRef<TemplateArgument> TemplateArgs,
3209 TemplateDeductionInfo &Info) {
3210 // Unevaluated SFINAE context.
3213 Sema::SFINAETrap Trap(S);
3214
3215 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
3216
3217 // C++ [temp.deduct.type]p2:
3218 // [...] or if any template argument remains neither deduced nor
3219 // explicitly specified, template argument deduction fails.
3220 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3222 S, Partial, IsPartialOrdering, Deduced, Info, SugaredBuilder,
3223 CanonicalBuilder);
3225 return Result;
3226
3227 // Form the template argument list from the deduced template arguments.
3228 TemplateArgumentList *SugaredDeducedArgumentList =
3229 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
3230 TemplateArgumentList *CanonicalDeducedArgumentList =
3231 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
3232
3233 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3234
3235 // Substitute the deduced template arguments into the template
3236 // arguments of the class template partial specialization, and
3237 // verify that the instantiated template arguments are both valid
3238 // and are equivalent to the template arguments originally provided
3239 // to the class template.
3240 LocalInstantiationScope InstScope(S);
3241 auto *Template = Partial->getSpecializedTemplate();
3242 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
3243 Partial->getTemplateArgsAsWritten();
3244
3245 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
3246 PartialTemplArgInfo->RAngleLoc);
3247
3248 if (S.SubstTemplateArguments(PartialTemplArgInfo->arguments(),
3250 SugaredBuilder,
3251 /*Final=*/true),
3252 InstArgs)) {
3253 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
3254 if (ParamIdx >= Partial->getTemplateParameters()->size())
3255 ParamIdx = Partial->getTemplateParameters()->size() - 1;
3256
3257 Decl *Param = const_cast<NamedDecl *>(
3258 Partial->getTemplateParameters()->getParam(ParamIdx));
3259 Info.Param = makeTemplateParameter(Param);
3260 Info.FirstArg = (*PartialTemplArgInfo)[ArgIdx].getArgument();
3262 }
3263
3265 SmallVector<TemplateArgument, 4> SugaredConvertedInstArgs,
3266 CanonicalConvertedInstArgs;
3268 Template, Partial->getLocation(), InstArgs, /*DefaultArgs=*/{}, false,
3269 SugaredConvertedInstArgs, CanonicalConvertedInstArgs,
3270 /*UpdateArgsWithConversions=*/true, &ConstraintsNotSatisfied))
3274
3275 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3276 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3277 TemplateArgument InstArg = SugaredConvertedInstArgs.data()[I];
3278 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
3279 IsPartialOrdering)) {
3280 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3281 Info.FirstArg = TemplateArgs[I];
3282 Info.SecondArg = InstArg;
3284 }
3285 }
3286
3287 if (Trap.hasErrorOccurred())
3289
3290 if (!IsPartialOrdering) {
3292 S, Partial, SugaredBuilder, CanonicalBuilder, Info);
3294 return Result;
3295 }
3296
3298}
3299
3300/// Complete template argument deduction for a class or variable template,
3301/// when partial ordering against a partial specialization.
3302// FIXME: Factor out duplication with partial specialization version above.
3304 Sema &S, TemplateDecl *Template, bool PartialOrdering,
3305 ArrayRef<TemplateArgument> TemplateArgs,
3307 TemplateDeductionInfo &Info) {
3308 // Unevaluated SFINAE context.
3311 Sema::SFINAETrap Trap(S);
3312
3313 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
3314
3315 // C++ [temp.deduct.type]p2:
3316 // [...] or if any template argument remains neither deduced nor
3317 // explicitly specified, template argument deduction fails.
3318 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3320 S, Template, /*IsDeduced*/ PartialOrdering, Deduced, Info,
3321 SugaredBuilder, CanonicalBuilder,
3322 /*CurrentInstantiationScope=*/nullptr,
3323 /*NumAlreadyConverted=*/0U);
3325 return Result;
3326
3327 // Check that we produced the correct argument list.
3328 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3329 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3330 TemplateArgument InstArg = CanonicalBuilder[I];
3331 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg, PartialOrdering,
3332 /*PackExpansionMatchesPack=*/true)) {
3333 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3334 Info.FirstArg = TemplateArgs[I];
3335 Info.SecondArg = InstArg;
3337 }
3338 }
3339
3340 if (Trap.hasErrorOccurred())
3342
3343 if (!PartialOrdering) {
3345 S, Template, SugaredBuilder, CanonicalBuilder, Info);
3347 return Result;
3348 }
3349
3351}
3352
3353/// Complete template argument deduction for DeduceTemplateArgumentsFromType.
3354/// FIXME: this is mostly duplicated with the above two versions. Deduplicate
3355/// the three implementations.
3357 Sema &S, TemplateDecl *TD,
3359 TemplateDeductionInfo &Info) {
3360 // Unevaluated SFINAE context.
3363 Sema::SFINAETrap Trap(S);
3364
3366
3367 // C++ [temp.deduct.type]p2:
3368 // [...] or if any template argument remains neither deduced nor
3369 // explicitly specified, template argument deduction fails.
3370 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3372 S, TD, /*IsPartialOrdering=*/false, Deduced, Info, SugaredBuilder,
3373 CanonicalBuilder);
3375 return Result;
3376
3377 if (Trap.hasErrorOccurred())
3379
3380 if (auto Result = CheckDeducedArgumentConstraints(S, TD, SugaredBuilder,
3381 CanonicalBuilder, Info);
3383 return Result;
3384
3386}
3387
3388/// Perform template argument deduction to determine whether the given template
3389/// arguments match the given class or variable template partial specialization
3390/// per C++ [temp.class.spec.match].
3391template <typename T>
3392static std::enable_if_t<IsPartialSpecialization<T>::value,
3395 ArrayRef<TemplateArgument> TemplateArgs,
3396 TemplateDeductionInfo &Info) {
3397 if (Partial->isInvalidDecl())
3399
3400 // C++ [temp.class.spec.match]p2:
3401 // A partial specialization matches a given actual template
3402 // argument list if the template arguments of the partial
3403 // specialization can be deduced from the actual template argument
3404 // list (14.8.2).
3405
3406 // Unevaluated SFINAE context.
3409 Sema::SFINAETrap Trap(S);
3410
3411 // This deduction has no relation to any outer instantiation we might be
3412 // performing.
3413 LocalInstantiationScope InstantiationScope(S);
3414
3416 Deduced.resize(Partial->getTemplateParameters()->size());
3418 S, Partial->getTemplateParameters(),
3419 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3420 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/false,
3421 PackFold::ParameterToArgument,
3422 /*HasDeducedAnyParam=*/nullptr);
3424 return Result;
3425
3426 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3427 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs,
3428 Info);
3429 if (Inst.isInvalid())
3431
3432 if (Trap.hasErrorOccurred())
3434
3437 Result = ::FinishTemplateArgumentDeduction(S, Partial,
3438 /*IsPartialOrdering=*/false,
3439 TemplateArgs, Deduced, Info);
3440 });
3441 return Result;
3442}
3443
3446 ArrayRef<TemplateArgument> TemplateArgs,
3447 TemplateDeductionInfo &Info) {
3448 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3449}
3452 ArrayRef<TemplateArgument> TemplateArgs,
3453 TemplateDeductionInfo &Info) {
3454 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3455}
3456
3460 if (TD->isInvalidDecl())
3462
3463 QualType PType;
3464 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
3465 // Use the InjectedClassNameType.
3466 PType = Context.getTypeDeclType(CTD->getTemplatedDecl());
3467 } else if (const auto *AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(TD)) {
3468 PType = AliasTemplate->getTemplatedDecl()->getUnderlyingType();
3469 } else {
3470 assert(false && "Expected a class or alias template");
3471 }
3472
3473 // Unevaluated SFINAE context.
3476 SFINAETrap Trap(*this);
3477
3478 // This deduction has no relation to any outer instantiation we might be
3479 // performing.
3480 LocalInstantiationScope InstantiationScope(*this);
3481
3483 TD->getTemplateParameters()->size());
3486 if (auto DeducedResult = DeduceTemplateArguments(
3487 TD->getTemplateParameters(), PArgs, AArgs, Info, Deduced, false);
3488 DeducedResult != TemplateDeductionResult::Success) {
3489 return DeducedResult;
3490 }
3491
3492 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3493 InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs, Info);
3494 if (Inst.isInvalid())
3496
3497 if (Trap.hasErrorOccurred())
3499
3502 Result = ::FinishTemplateArgumentDeduction(*this, TD, Deduced, Info);
3503 });
3504 return Result;
3505}
3506
3507/// Determine whether the given type T is a simple-template-id type.
3509 if (const TemplateSpecializationType *Spec
3511 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
3512
3513 // C++17 [temp.local]p2:
3514 // the injected-class-name [...] is equivalent to the template-name followed
3515 // by the template-arguments of the class template specialization or partial
3516 // specialization enclosed in <>
3517 // ... which means it's equivalent to a simple-template-id.
3518 //
3519 // This only arises during class template argument deduction for a copy
3520 // deduction candidate, where it permits slicing.
3522 return true;
3523
3524 return false;
3525}
3526
3528 FunctionTemplateDecl *FunctionTemplate,
3529 TemplateArgumentListInfo &ExplicitTemplateArgs,
3532 TemplateDeductionInfo &Info) {
3533 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3534 TemplateParameterList *TemplateParams
3535 = FunctionTemplate->getTemplateParameters();
3536
3537 if (ExplicitTemplateArgs.size() == 0) {
3538 // No arguments to substitute; just copy over the parameter types and
3539 // fill in the function type.
3540 for (auto *P : Function->parameters())
3541 ParamTypes.push_back(P->getType());
3542
3543 if (FunctionType)
3544 *FunctionType = Function->getType();
3546 }
3547
3548 // Unevaluated SFINAE context.
3551 SFINAETrap Trap(*this);
3552
3553 // C++ [temp.arg.explicit]p3:
3554 // Template arguments that are present shall be specified in the
3555 // declaration order of their corresponding template-parameters. The
3556 // template argument list shall not specify more template-arguments than
3557 // there are corresponding template-parameters.
3558 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3559
3560 // Enter a new template instantiation context where we check the
3561 // explicitly-specified template arguments against this function template,
3562 // and then substitute them into the function parameter types.
3565 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3567 if (Inst.isInvalid())
3569
3571 ExplicitTemplateArgs, /*DefaultArgs=*/{}, true,
3572 SugaredBuilder, CanonicalBuilder,
3573 /*UpdateArgsWithConversions=*/false) ||
3574 Trap.hasErrorOccurred()) {
3575 unsigned Index = SugaredBuilder.size();
3576 if (Index >= TemplateParams->size())
3578 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3580 }
3581
3582 // Form the template argument list from the explicitly-specified
3583 // template arguments.
3584 TemplateArgumentList *SugaredExplicitArgumentList =
3586 TemplateArgumentList *CanonicalExplicitArgumentList =
3587 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3588 Info.setExplicitArgs(SugaredExplicitArgumentList,
3589 CanonicalExplicitArgumentList);
3590
3591 // Template argument deduction and the final substitution should be
3592 // done in the context of the templated declaration. Explicit
3593 // argument substitution, on the other hand, needs to happen in the
3594 // calling context.
3595 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3596
3597 // If we deduced template arguments for a template parameter pack,
3598 // note that the template argument pack is partially substituted and record
3599 // the explicit template arguments. They'll be used as part of deduction
3600 // for this template parameter pack.
3601 unsigned PartiallySubstitutedPackIndex = -1u;
3602 if (!SugaredBuilder.empty()) {
3603 const TemplateArgument &Arg = SugaredBuilder.back();
3604 if (Arg.getKind() == TemplateArgument::Pack) {
3605 auto *Param = TemplateParams->getParam(SugaredBuilder.size() - 1);
3606 // If this is a fully-saturated fixed-size pack, it should be
3607 // fully-substituted, not partially-substituted.
3608 std::optional<unsigned> Expansions = getExpandedPackSize(Param);
3609 if (!Expansions || Arg.pack_size() < *Expansions) {
3610 PartiallySubstitutedPackIndex = SugaredBuilder.size() - 1;
3612 Param, Arg.pack_begin(), Arg.pack_size());
3613 }
3614 }
3615 }
3616
3617 const FunctionProtoType *Proto
3618 = Function->getType()->getAs<FunctionProtoType>();
3619 assert(Proto && "Function template does not have a prototype?");
3620
3621 // Isolate our substituted parameters from our caller.
3622 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3623
3624 ExtParameterInfoBuilder ExtParamInfos;
3625
3627 SugaredExplicitArgumentList->asArray(),
3628 /*Final=*/true);
3629
3630 // Instantiate the types of each of the function parameters given the
3631 // explicitly-specified template arguments. If the function has a trailing
3632 // return type, substitute it after the arguments to ensure we substitute
3633 // in lexical order.
3634 if (Proto->hasTrailingReturn()) {
3635 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3636 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3637 /*params=*/nullptr, ExtParamInfos))
3639 }
3640
3641 // Instantiate the return type.
3642 QualType ResultType;
3643 {
3644 // C++11 [expr.prim.general]p3:
3645 // If a declaration declares a member function or member function
3646 // template of a class X, the expression this is a prvalue of type
3647 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3648 // and the end of the function-definition, member-declarator, or
3649 // declarator.
3650 Qualifiers ThisTypeQuals;
3651 CXXRecordDecl *ThisContext = nullptr;
3652 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3653 ThisContext = Method->getParent();
3654 ThisTypeQuals = Method->getMethodQualifiers();
3655 }
3656
3657 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3659
3660 ResultType =
3661 SubstType(Proto->getReturnType(), MLTAL,
3662 Function->getTypeSpecStartLoc(), Function->getDeclName());
3663 if (ResultType.isNull() || Trap.hasErrorOccurred())
3665 // CUDA: Kernel function must have 'void' return type.
3666 if (getLangOpts().CUDA)
3667 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3668 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3669 << Function->getType() << Function->getSourceRange();
3671 }
3672 }
3673
3674 // Instantiate the types of each of the function parameters given the
3675 // explicitly-specified template arguments if we didn't do so earlier.
3676 if (!Proto->hasTrailingReturn() &&
3677 SubstParmTypes(Function->getLocation(), Function->parameters(),
3678 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3679 /*params*/ nullptr, ExtParamInfos))
3681
3682 if (FunctionType) {
3683 auto EPI = Proto->getExtProtoInfo();
3684 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3685 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3686 Function->getLocation(),
3687 Function->getDeclName(),
3688 EPI);
3689 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3691 }
3692
3693 // C++ [temp.arg.explicit]p2:
3694 // Trailing template arguments that can be deduced (14.8.2) may be
3695 // omitted from the list of explicit template-arguments. If all of the
3696 // template arguments can be deduced, they may all be omitted; in this
3697 // case, the empty template argument list <> itself may also be omitted.
3698 //
3699 // Take all of the explicitly-specified arguments and put them into
3700 // the set of deduced template arguments. The partially-substituted
3701 // parameter pack, however, will be set to NULL since the deduction
3702 // mechanism handles the partially-substituted argument pack directly.
3703 Deduced.reserve(TemplateParams->size());
3704 for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3705 const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
3706 if (I == PartiallySubstitutedPackIndex)
3707 Deduced.push_back(DeducedTemplateArgument());
3708 else
3709 Deduced.push_back(Arg);
3710 }
3711
3713}
3714
3715/// Check whether the deduced argument type for a call to a function
3716/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3719 Sema::OriginalCallArg OriginalArg,
3720 QualType DeducedA) {
3721 ASTContext &Context = S.Context;
3722
3723 auto Failed = [&]() -> TemplateDeductionResult {
3724 Info.FirstArg = TemplateArgument(DeducedA);
3725 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3726 Info.CallArgIndex = OriginalArg.ArgIdx;
3727 return OriginalArg.DecomposedParam
3730 };
3731
3732 QualType A = OriginalArg.OriginalArgType;
3733 QualType OriginalParamType = OriginalArg.OriginalParamType;
3734
3735 // Check for type equality (top-level cv-qualifiers are ignored).
3736 if (Context.hasSameUnqualifiedType(A, DeducedA))
3738
3739 // Strip off references on the argument types; they aren't needed for
3740 // the following checks.
3741 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3742 DeducedA = DeducedARef->getPointeeType();
3743 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3744 A = ARef->getPointeeType();
3745
3746 // C++ [temp.deduct.call]p4:
3747 // [...] However, there are three cases that allow a difference:
3748 // - If the original P is a reference type, the deduced A (i.e., the
3749 // type referred to by the reference) can be more cv-qualified than
3750 // the transformed A.
3751 if (const ReferenceType *OriginalParamRef
3752 = OriginalParamType->getAs<ReferenceType>()) {
3753 // We don't want to keep the reference around any more.
3754 OriginalParamType = OriginalParamRef->getPointeeType();
3755
3756 // FIXME: Resolve core issue (no number yet): if the original P is a
3757 // reference type and the transformed A is function type "noexcept F",
3758 // the deduced A can be F.
3759 QualType Tmp;
3760 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
3762
3763 Qualifiers AQuals = A.getQualifiers();
3764 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3765
3766 // Under Objective-C++ ARC, the deduced type may have implicitly
3767 // been given strong or (when dealing with a const reference)
3768 // unsafe_unretained lifetime. If so, update the original
3769 // qualifiers to include this lifetime.
3770 if (S.getLangOpts().ObjCAutoRefCount &&
3771 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3773 (DeducedAQuals.hasConst() &&
3774 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3775 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3776 }
3777
3778 if (AQuals == DeducedAQuals) {
3779 // Qualifiers match; there's nothing to do.
3780 } else if (!DeducedAQuals.compatiblyIncludes(AQuals, S.getASTContext())) {
3781 return Failed();
3782 } else {
3783 // Qualifiers are compatible, so have the argument type adopt the
3784 // deduced argument type's qualifiers as if we had performed the
3785 // qualification conversion.
3786 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3787 }
3788 }
3789
3790 // - The transformed A can be another pointer or pointer to member
3791 // type that can be converted to the deduced A via a function pointer
3792 // conversion and/or a qualification conversion.
3793 //
3794 // Also allow conversions which merely strip __attribute__((noreturn)) from
3795 // function types (recursively).
3796 bool ObjCLifetimeConversion = false;
3797 QualType ResultTy;
3798 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3799 (S.IsQualificationConversion(A, DeducedA, false,
3800 ObjCLifetimeConversion) ||
3801 S.IsFunctionConversion(A, DeducedA, ResultTy)))
3803
3804 // - If P is a class and P has the form simple-template-id, then the
3805 // transformed A can be a derived class of the deduced A. [...]
3806 // [...] Likewise, if P is a pointer to a class of the form
3807 // simple-template-id, the transformed A can be a pointer to a
3808 // derived class pointed to by the deduced A.
3809 if (const PointerType *OriginalParamPtr
3810 = OriginalParamType->getAs<PointerType>()) {
3811 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3812 if (const PointerType *APtr = A->getAs<PointerType>()) {
3813 if (A->getPointeeType()->isRecordType()) {
3814 OriginalParamType = OriginalParamPtr->getPointeeType();
3815 DeducedA = DeducedAPtr->getPointeeType();
3816 A = APtr->getPointeeType();
3817 }
3818 }
3819 }
3820 }
3821
3822 if (Context.hasSameUnqualifiedType(A, DeducedA))
3824
3825 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3826 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3828
3829 return Failed();
3830}
3831
3832/// Find the pack index for a particular parameter index in an instantiation of
3833/// a function template with specific arguments.
3834///
3835/// \return The pack index for whichever pack produced this parameter, or -1
3836/// if this was not produced by a parameter. Intended to be used as the
3837/// ArgumentPackSubstitutionIndex for further substitutions.
3838// FIXME: We should track this in OriginalCallArgs so we don't need to
3839// reconstruct it here.
3840static unsigned getPackIndexForParam(Sema &S,
3841 FunctionTemplateDecl *FunctionTemplate,
3843 unsigned ParamIdx) {
3844 unsigned Idx = 0;
3845 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3846 if (PD->isParameterPack()) {
3847 unsigned NumExpansions =
3848 S.getNumArgumentsInExpansion(PD->getType(), Args).value_or(1);
3849 if (Idx + NumExpansions > ParamIdx)
3850 return ParamIdx - Idx;
3851 Idx += NumExpansions;
3852 } else {
3853 if (Idx == ParamIdx)
3854 return -1; // Not a pack expansion
3855 ++Idx;
3856 }
3857 }
3858
3859 llvm_unreachable("parameter index would not be produced from template");
3860}
3861
3862// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`,
3863// we'll try to instantiate and update its explicit specifier after constraint
3864// checking.
3867 const MultiLevelTemplateArgumentList &SubstArgs,
3868 TemplateDeductionInfo &Info, FunctionTemplateDecl *FunctionTemplate,
3869 ArrayRef<TemplateArgument> DeducedArgs) {
3870 auto GetExplicitSpecifier = [](FunctionDecl *D) {
3871 return isa<CXXConstructorDecl>(D)
3872 ? cast<CXXConstructorDecl>(D)->getExplicitSpecifier()
3873 : cast<CXXConversionDecl>(D)->getExplicitSpecifier();
3874 };
3875 auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) {
3876 isa<CXXConstructorDecl>(D)
3877 ? cast<CXXConstructorDecl>(D)->setExplicitSpecifier(ES)
3878 : cast<CXXConversionDecl>(D)->setExplicitSpecifier(ES);
3879 };
3880
3881 ExplicitSpecifier ES = GetExplicitSpecifier(Specialization);
3882 Expr *ExplicitExpr = ES.getExpr();
3883 if (!ExplicitExpr)
3885 if (!ExplicitExpr->isValueDependent())
3887
3889 S, Info.getLocation(), FunctionTemplate, DeducedArgs,
3891 if (Inst.isInvalid())
3893 Sema::SFINAETrap Trap(S);
3894 const ExplicitSpecifier InstantiatedES =
3895 S.instantiateExplicitSpecifier(SubstArgs, ES);
3896 if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) {
3897 Specialization->setInvalidDecl(true);
3899 }
3900 SetExplicitSpecifier(Specialization, InstantiatedES);
3902}
3903
3905 FunctionTemplateDecl *FunctionTemplate,
3907 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3909 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3910 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
3911 // Unevaluated SFINAE context.
3914 SFINAETrap Trap(*this);
3915
3916 // Enter a new template instantiation context while we instantiate the
3917 // actual function declaration.
3918 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3920 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3922 if (Inst.isInvalid())
3924
3925 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3926
3927 // C++ [temp.deduct.type]p2:
3928 // [...] or if any template argument remains neither deduced nor
3929 // explicitly specified, template argument deduction fails.
3930 bool IsIncomplete = false;
3931 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3933 *this, FunctionTemplate, /*IsDeduced*/ true, Deduced, Info,
3934 SugaredBuilder, CanonicalBuilder, CurrentInstantiationScope,
3935 NumExplicitlySpecified, PartialOverloading ? &IsIncomplete : nullptr);
3937 return Result;
3938
3939 // C++ [temp.deduct.call]p10: [DR1391]
3940 // If deduction succeeds for all parameters that contain
3941 // template-parameters that participate in template argument deduction,
3942 // and all template arguments are explicitly specified, deduced, or
3943 // obtained from default template arguments, remaining parameters are then
3944 // compared with the corresponding arguments. For each remaining parameter
3945 // P with a type that was non-dependent before substitution of any
3946 // explicitly-specified template arguments, if the corresponding argument
3947 // A cannot be implicitly converted to P, deduction fails.
3948 if (CheckNonDependent())
3950
3951 // Form the template argument list from the deduced template arguments.
3952 TemplateArgumentList *SugaredDeducedArgumentList =
3954 TemplateArgumentList *CanonicalDeducedArgumentList =
3955 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3956 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3957
3958 // Substitute the deduced template arguments into the function template
3959 // declaration to produce the function template specialization.
3960 DeclContext *Owner = FunctionTemplate->getDeclContext();
3961 if (FunctionTemplate->getFriendObjectKind())
3962 Owner = FunctionTemplate->getLexicalDeclContext();
3963 FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
3964 // additional check for inline friend,
3965 // ```
3966 // template <class F1> int foo(F1 X);
3967 // template <int A1> struct A {
3968 // template <class F1> friend int foo(F1 X) { return A1; }
3969 // };
3970 // template struct A<1>;
3971 // int a = foo(1.0);
3972 // ```
3973 const FunctionDecl *FDFriend;
3975 FD->isDefined(FDFriend, /*CheckForPendingFriendDefinition*/ true) &&
3977 FD = const_cast<FunctionDecl *>(FDFriend);
3978 Owner = FD->getLexicalDeclContext();
3979 }
3981 FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
3982 /*Final=*/false);
3983 Specialization = cast_or_null<FunctionDecl>(
3984 SubstDecl(FD, Owner, SubstArgs));
3985 if (!Specialization || Specialization->isInvalidDecl())
3987
3988 assert(isSameDeclaration(Specialization->getPrimaryTemplate(),
3990
3991 // If the template argument list is owned by the function template
3992 // specialization, release it.
3993 if (Specialization->getTemplateSpecializationArgs() ==
3994 CanonicalDeducedArgumentList &&
3995 !Trap.hasErrorOccurred())
3996 Info.takeCanonical();
3997
3998 // There may have been an error that did not prevent us from constructing a
3999 // declaration. Mark the declaration invalid and return with a substitution
4000 // failure.
4001 if (Trap.hasErrorOccurred()) {
4002 Specialization->setInvalidDecl(true);
4004 }
4005
4006 // C++2a [temp.deduct]p5
4007 // [...] When all template arguments have been deduced [...] all uses of
4008 // template parameters [...] are replaced with the corresponding deduced
4009 // or default argument values.
4010 // [...] If the function template has associated constraints
4011 // ([temp.constr.decl]), those constraints are checked for satisfaction
4012 // ([temp.constr.constr]). If the constraints are not satisfied, type
4013 // deduction fails.
4014 if (!IsIncomplete) {
4016 Info.getLocation(), Specialization, CanonicalBuilder,
4019
4021 Info.reset(Info.takeSugared(),
4022 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder));
4024 }
4025 }
4026
4027 // We skipped the instantiation of the explicit-specifier during the
4028 // substitution of `FD` before. So, we try to instantiate it back if
4029 // `Specialization` is either a constructor or a conversion function.
4030 if (isa<CXXConstructorDecl, CXXConversionDecl>(Specialization)) {
4033 Info, FunctionTemplate,
4034 DeducedArgs)) {
4036 }
4037 }
4038
4039 if (OriginalCallArgs) {
4040 // C++ [temp.deduct.call]p4:
4041 // In general, the deduction process attempts to find template argument
4042 // values that will make the deduced A identical to A (after the type A
4043 // is transformed as described above). [...]
4044 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
4045 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
4046 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
4047
4048 auto ParamIdx = OriginalArg.ArgIdx;
4049 unsigned ExplicitOffset =
4050 Specialization->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
4051 if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset)
4052 // FIXME: This presumably means a pack ended up smaller than we
4053 // expected while deducing. Should this not result in deduction
4054 // failure? Can it even happen?
4055 continue;
4056
4057 QualType DeducedA;
4058 if (!OriginalArg.DecomposedParam) {
4059 // P is one of the function parameters, just look up its substituted
4060 // type.
4061 DeducedA =
4062 Specialization->getParamDecl(ParamIdx + ExplicitOffset)->getType();
4063 } else {
4064 // P is a decomposed element of a parameter corresponding to a
4065 // braced-init-list argument. Substitute back into P to find the
4066 // deduced A.
4067 QualType &CacheEntry =
4068 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
4069 if (CacheEntry.isNull()) {
4071 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
4072 ParamIdx));
4073 CacheEntry =
4074 SubstType(OriginalArg.OriginalParamType, SubstArgs,
4075 Specialization->getTypeSpecStartLoc(),
4076 Specialization->getDeclName());
4077 }
4078 DeducedA = CacheEntry;
4079 }
4080
4081 if (auto TDK =
4082 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
4084 return TDK;
4085 }
4086 }
4087
4088 // If we suppressed any diagnostics while performing template argument
4089 // deduction, and if we haven't already instantiated this declaration,
4090 // keep track of these diagnostics. They'll be emitted if this specialization
4091 // is actually used.
4092 if (Info.diag_begin() != Info.diag_end()) {
4093 auto [Pos, Inserted] =
4094 SuppressedDiagnostics.try_emplace(Specialization->getCanonicalDecl());
4095 if (Inserted)
4096 Pos->second.append(Info.diag_begin(), Info.diag_end());
4097 }
4098
4100}
4101
4102/// Gets the type of a function for template-argument-deducton
4103/// purposes when it's considered as part of an overload set.
4105 FunctionDecl *Fn) {
4106 // We may need to deduce the return type of the function now.
4107 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
4108 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
4109 return {};
4110
4111 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
4112 if (Method->isImplicitObjectMemberFunction()) {
4113 // An instance method that's referenced in a form that doesn't
4114 // look like a member pointer is just invalid.
4116 return {};
4117
4118 return S.Context.getMemberPointerType(Fn->getType(),
4119 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
4120 }
4121
4122 if (!R.IsAddressOfOperand) return Fn->getType();
4123 return S.Context.getPointerType(Fn->getType());
4124}
4125
4126/// Apply the deduction rules for overload sets.
4127///
4128/// \return the null type if this argument should be treated as an
4129/// undeduced context
4130static QualType
4132 Expr *Arg, QualType ParamType,
4133 bool ParamWasReference,
4134 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4135
4137
4138 OverloadExpr *Ovl = R.Expression;
4139
4140 // C++0x [temp.deduct.call]p4
4141 unsigned TDF = 0;
4142 if (ParamWasReference)
4144 if (R.IsAddressOfOperand)
4145 TDF |= TDF_IgnoreQualifiers;
4146
4147 // C++0x [temp.deduct.call]p6:
4148 // When P is a function type, pointer to function type, or pointer
4149 // to member function type:
4150
4151 if (!ParamType->isFunctionType() &&
4152 !ParamType->isFunctionPointerType() &&
4153 !ParamType->isMemberFunctionPointerType()) {
4154 if (Ovl->hasExplicitTemplateArgs()) {
4155 // But we can still look for an explicit specialization.
4156 if (FunctionDecl *ExplicitSpec =
4158 Ovl, /*Complain=*/false,
4159 /*FoundDeclAccessPair=*/nullptr, FailedTSC))
4160 return GetTypeOfFunction(S, R, ExplicitSpec);
4161 }
4162
4163 DeclAccessPair DAP;
4164 if (FunctionDecl *Viable =
4166 return GetTypeOfFunction(S, R, Viable);
4167
4168 return {};
4169 }
4170
4171 // Gather the explicit template arguments, if any.
4172 TemplateArgumentListInfo ExplicitTemplateArgs;
4173 if (Ovl->hasExplicitTemplateArgs())
4174 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4175 QualType Match;
4176 for (UnresolvedSetIterator I = Ovl->decls_begin(),
4177 E = Ovl->decls_end(); I != E; ++I) {
4178 NamedDecl *D = (*I)->getUnderlyingDecl();
4179
4180 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
4181 // - If the argument is an overload set containing one or more
4182 // function templates, the parameter is treated as a
4183 // non-deduced context.
4184 if (!Ovl->hasExplicitTemplateArgs())
4185 return {};
4186
4187 // Otherwise, see if we can resolve a function type
4188 FunctionDecl *Specialization = nullptr;
4189 TemplateDeductionInfo Info(Ovl->getNameLoc());
4190 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
4193 continue;
4194
4195 D = Specialization;
4196 }
4197
4198 FunctionDecl *Fn = cast<FunctionDecl>(D);
4199 QualType ArgType = GetTypeOfFunction(S, R, Fn);
4200 if (ArgType.isNull()) continue;
4201
4202 // Function-to-pointer conversion.
4203 if (!ParamWasReference && ParamType->isPointerType() &&
4204 ArgType->isFunctionType())
4205 ArgType = S.Context.getPointerType(ArgType);
4206
4207 // - If the argument is an overload set (not containing function
4208 // templates), trial argument deduction is attempted using each
4209 // of the members of the set. If deduction succeeds for only one
4210 // of the overload set members, that member is used as the
4211 // argument value for the deduction. If deduction succeeds for
4212 // more than one member of the overload set the parameter is
4213 // treated as a non-deduced context.
4214
4215 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
4216 // Type deduction is done independently for each P/A pair, and
4217 // the deduced template argument values are then combined.
4218 // So we do not reject deductions which were made elsewhere.
4220 Deduced(TemplateParams->size());
4221 TemplateDeductionInfo Info(Ovl->getNameLoc());
4223 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4224 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4225 /*HasDeducedAnyParam=*/nullptr);
4227 continue;
4228 if (!Match.isNull())
4229 return {};
4230 Match = ArgType;
4231 }
4232
4233 return Match;
4234}
4235
4236/// Perform the adjustments to the parameter and argument types
4237/// described in C++ [temp.deduct.call].
4238///
4239/// \returns true if the caller should not attempt to perform any template
4240/// argument deduction based on this P/A pair because the argument is an
4241/// overloaded function set that could not be resolved.
4243 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4244 QualType &ParamType, QualType &ArgType,
4245 Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
4246 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4247 // C++0x [temp.deduct.call]p3:
4248 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
4249 // are ignored for type deduction.
4250 if (ParamType.hasQualifiers())
4251 ParamType = ParamType.getUnqualifiedType();
4252
4253 // [...] If P is a reference type, the type referred to by P is
4254 // used for type deduction.
4255 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
4256 if (ParamRefType)
4257 ParamType = ParamRefType->getPointeeType();
4258
4259 // Overload sets usually make this parameter an undeduced context,
4260 // but there are sometimes special circumstances. Typically
4261 // involving a template-id-expr.
4262 if (ArgType == S.Context.OverloadTy) {
4263 assert(Arg && "expected a non-null arg expression");
4264 ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType,
4265 ParamRefType != nullptr, FailedTSC);
4266 if (ArgType.isNull())
4267 return true;
4268 }
4269
4270 if (ParamRefType) {
4271 // If the argument has incomplete array type, try to complete its type.
4272 if (ArgType->isIncompleteArrayType()) {
4273 assert(Arg && "expected a non-null arg expression");
4274 ArgType = S.getCompletedType(Arg);
4275 }
4276
4277 // C++1z [temp.deduct.call]p3:
4278 // If P is a forwarding reference and the argument is an lvalue, the type
4279 // "lvalue reference to A" is used in place of A for type deduction.
4280 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
4281 ArgClassification.isLValue()) {
4282 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
4283 ArgType = S.Context.getAddrSpaceQualType(
4285 ArgType = S.Context.getLValueReferenceType(ArgType);
4286 }
4287 } else {
4288 // C++ [temp.deduct.call]p2:
4289 // If P is not a reference type:
4290 // - If A is an array type, the pointer type produced by the
4291 // array-to-pointer standard conversion (4.2) is used in place of
4292 // A for type deduction; otherwise,
4293 // - If A is a function type, the pointer type produced by the
4294 // function-to-pointer standard conversion (4.3) is used in place
4295 // of A for type deduction; otherwise,
4296 if (ArgType->canDecayToPointerType())
4297 ArgType = S.Context.getDecayedType(ArgType);
4298 else {
4299 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
4300 // type are ignored for type deduction.
4301 ArgType = ArgType.getUnqualifiedType();
4302 }
4303 }
4304
4305 // C++0x [temp.deduct.call]p4:
4306 // In general, the deduction process attempts to find template argument
4307 // values that will make the deduced A identical to A (after the type A
4308 // is transformed as described above). [...]
4310
4311 // - If the original P is a reference type, the deduced A (i.e., the
4312 // type referred to by the reference) can be more cv-qualified than
4313 // the transformed A.
4314 if (ParamRefType)
4316 // - The transformed A can be another pointer or pointer to member
4317 // type that can be converted to the deduced A via a qualification
4318 // conversion (4.4).
4319 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
4320 ArgType->isObjCObjectPointerType())
4321 TDF |= TDF_IgnoreQualifiers;
4322 // - If P is a class and P has the form simple-template-id, then the
4323 // transformed A can be a derived class of the deduced A. Likewise,
4324 // if P is a pointer to a class of the form simple-template-id, the
4325 // transformed A can be a pointer to a derived class pointed to by
4326 // the deduced A.
4327 if (isSimpleTemplateIdType(ParamType) ||
4328 (isa<PointerType>(ParamType) &&
4330 ParamType->castAs<PointerType>()->getPointeeType())))
4331 TDF |= TDF_DerivedClass;
4332
4333 return false;
4334}
4335
4336static bool
4338 QualType T);
4339
4341 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4342 QualType ParamType, QualType ArgType,
4343 Expr::Classification ArgClassification, Expr *Arg,
4347 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4348 TemplateSpecCandidateSet *FailedTSC = nullptr);
4349
4350/// Attempt template argument deduction from an initializer list
4351/// deemed to be an argument in a function call.
4353 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
4356 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
4357 unsigned TDF) {
4358 // C++ [temp.deduct.call]p1: (CWG 1591)
4359 // If removing references and cv-qualifiers from P gives
4360 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
4361 // a non-empty initializer list, then deduction is performed instead for
4362 // each element of the initializer list, taking P0 as a function template
4363 // parameter type and the initializer element as its argument
4364 //
4365 // We've already removed references and cv-qualifiers here.
4366 if (!ILE->getNumInits())
4368
4369 QualType ElTy;
4370 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
4371 if (ArrTy)
4372 ElTy = ArrTy->getElementType();
4373 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
4374 // Otherwise, an initializer list argument causes the parameter to be
4375 // considered a non-deduced context
4377 }
4378
4379 // Resolving a core issue: a braced-init-list containing any designators is
4380 // a non-deduced context.
4381 for (Expr *E : ILE->inits())
4382 if (isa<DesignatedInitExpr>(E))
4384
4385 // Deduction only needs to be done for dependent types.
4386 if (ElTy->isDependentType()) {
4387 for (Expr *E : ILE->inits()) {
4389 S, TemplateParams, 0, ElTy, E->getType(),
4390 E->Classify(S.getASTContext()), E, Info, Deduced,
4391 OriginalCallArgs, true, ArgIdx, TDF);
4393 return Result;
4394 }
4395 }
4396
4397 // in the P0[N] case, if N is a non-type template parameter, N is deduced
4398 // from the length of the initializer list.
4399 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
4400 // Determine the array bound is something we can deduce.
4401 if (const NonTypeTemplateParmDecl *NTTP =
4402 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
4403 // We can perform template argument deduction for the given non-type
4404 // template parameter.
4405 // C++ [temp.deduct.type]p13:
4406 // The type of N in the type T[N] is std::size_t.
4408 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
4410 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
4411 /*ArrayBound=*/true, Info, /*PartialOrdering=*/false, Deduced,
4412 /*HasDeducedAnyParam=*/nullptr);
4414 return Result;
4415 }
4416 }
4417
4419}
4420
4421/// Perform template argument deduction per [temp.deduct.call] for a
4422/// single parameter / argument pair.
4424 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4425 QualType ParamType, QualType ArgType,
4426 Expr::Classification ArgClassification, Expr *Arg,
4430 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4431 TemplateSpecCandidateSet *FailedTSC) {
4432
4433 QualType OrigParamType = ParamType;
4434
4435 // If P is a reference type [...]
4436 // If P is a cv-qualified type [...]
4438 S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
4439 ArgClassification, Arg, TDF, FailedTSC))
4441
4442 // If [...] the argument is a non-empty initializer list [...]
4443 if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
4444 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
4445 Deduced, OriginalCallArgs, ArgIdx, TDF);
4446
4447 // [...] the deduction process attempts to find template argument values
4448 // that will make the deduced A identical to A
4449 //
4450 // Keep track of the argument type and corresponding parameter index,
4451 // so we can check for compatibility between the deduced A and A.
4452 if (Arg)
4453 OriginalCallArgs.push_back(
4454 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
4456 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4457 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4458 /*HasDeducedAnyParam=*/nullptr);
4459}
4460
4462 FunctionTemplateDecl *FunctionTemplate,
4463 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4465 bool PartialOverloading, bool AggregateDeductionCandidate,
4466 QualType ObjectType, Expr::Classification ObjectClassification,
4467 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
4468 if (FunctionTemplate->isInvalidDecl())
4470
4471 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4472 unsigned NumParams = Function->getNumParams();
4473 bool HasExplicitObject = false;
4474 int ExplicitObjectOffset = 0;
4475 if (Function->hasCXXExplicitFunctionObjectParameter()) {
4476 HasExplicitObject = true;
4477 ExplicitObjectOffset = 1;
4478 }
4479
4480 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
4481
4482 // C++ [temp.deduct.call]p1:
4483 // Template argument deduction is done by comparing each function template
4484 // parameter type (call it P) with the type of the corresponding argument
4485 // of the call (call it A) as described below.
4486 if (Args.size() < Function->getMinRequiredExplicitArguments() &&
4487 !PartialOverloading)
4489 else if (TooManyArguments(NumParams, Args.size() + ExplicitObjectOffset,
4490 PartialOverloading)) {
4491 const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
4492 if (Proto->isTemplateVariadic())
4493 /* Do nothing */;
4494 else if (!Proto->isVariadic())
4496 }
4497
4498 // The types of the parameters from which we will perform template argument
4499 // deduction.
4500 LocalInstantiationScope InstScope(*this);
4501 TemplateParameterList *TemplateParams
4502 = FunctionTemplate->getTemplateParameters();
4504 SmallVector<QualType, 8> ParamTypes;
4505 unsigned NumExplicitlySpecified = 0;
4506 if (ExplicitTemplateArgs) {
4509 Result = SubstituteExplicitTemplateArguments(
4510 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4511 Info);
4512 });
4514 return Result;
4515
4516 NumExplicitlySpecified = Deduced.size();
4517 } else {
4518 // Just fill in the parameter types from the function declaration.
4519 for (unsigned I = 0; I != NumParams; ++I)
4520 ParamTypes.push_back(Function->getParamDecl(I)->getType());
4521 }
4522
4523 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
4524
4525 // Deduce an argument of type ParamType from an expression with index ArgIdx.
4526 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx,
4527 bool ExplicitObjectArgument) {
4528 // C++ [demp.deduct.call]p1: (DR1391)
4529 // Template argument deduction is done by comparing each function template
4530 // parameter that contains template-parameters that participate in
4531 // template argument deduction ...
4532 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4534
4535 if (ExplicitObjectArgument) {
4536 // ... with the type of the corresponding argument
4538 *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
4539 ObjectClassification,
4540 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4541 /*Decomposed*/ false, ArgIdx, /*TDF*/ 0);
4542 }
4543
4544 // ... with the type of the corresponding argument
4546 *this, TemplateParams, FirstInnerIndex, ParamType,
4547 Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()),
4548 Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false,
4549 ArgIdx, /*TDF*/ 0);
4550 };
4551
4552 // Deduce template arguments from the function parameters.
4553 Deduced.resize(TemplateParams->size());
4554 SmallVector<QualType, 8> ParamTypesForArgChecking;
4555 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4556 ParamIdx != NumParamTypes; ++ParamIdx) {
4557 QualType ParamType = ParamTypes[ParamIdx];
4558
4559 const PackExpansionType *ParamExpansion =
4560 dyn_cast<PackExpansionType>(ParamType);
4561 if (!ParamExpansion) {
4562 // Simple case: matching a function parameter to a function argument.
4563 if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0))
4564 break;
4565
4566 ParamTypesForArgChecking.push_back(ParamType);
4567
4568 if (ParamIdx == 0 && HasExplicitObject) {
4569 if (ObjectType.isNull())
4571
4572 if (auto Result = DeduceCallArgument(ParamType, 0,
4573 /*ExplicitObjectArgument=*/true);
4575 return Result;
4576 continue;
4577 }
4578
4579 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4580 /*ExplicitObjectArgument=*/false);
4582 return Result;
4583
4584 continue;
4585 }
4586
4587 bool IsTrailingPack = ParamIdx + 1 == NumParamTypes;
4588
4589 QualType ParamPattern = ParamExpansion->getPattern();
4590 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
4591 ParamPattern,
4592 AggregateDeductionCandidate && IsTrailingPack);
4593
4594 // C++0x [temp.deduct.call]p1:
4595 // For a function parameter pack that occurs at the end of the
4596 // parameter-declaration-list, the type A of each remaining argument of
4597 // the call is compared with the type P of the declarator-id of the
4598 // function parameter pack. Each comparison deduces template arguments
4599 // for subsequent positions in the template parameter packs expanded by
4600 // the function parameter pack. When a function parameter pack appears
4601 // in a non-deduced context [not at the end of the list], the type of
4602 // that parameter pack is never deduced.
4603 //
4604 // FIXME: The above rule allows the size of the parameter pack to change
4605 // after we skip it (in the non-deduced case). That makes no sense, so
4606 // we instead notionally deduce the pack against N arguments, where N is
4607 // the length of the explicitly-specified pack if it's expanded by the
4608 // parameter pack and 0 otherwise, and we treat each deduction as a
4609 // non-deduced context.
4610 if (IsTrailingPack || PackScope.hasFixedArity()) {
4611 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4612 PackScope.nextPackElement(), ++ArgIdx) {
4613 ParamTypesForArgChecking.push_back(ParamPattern);
4614 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4615 /*ExplicitObjectArgument=*/false);
4617 return Result;
4618 }
4619 } else {
4620 // If the parameter type contains an explicitly-specified pack that we
4621 // could not expand, skip the number of parameters notionally created
4622 // by the expansion.
4623 std::optional<unsigned> NumExpansions =
4624 ParamExpansion->getNumExpansions();
4625 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4626 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4627 ++I, ++ArgIdx) {
4628 ParamTypesForArgChecking.push_back(ParamPattern);
4629 // FIXME: Should we add OriginalCallArgs for these? What if the
4630 // corresponding argument is a list?
4631 PackScope.nextPackElement();
4632 }
4633 } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4634 PackScope.isDeducedFromEarlierParameter()) {
4635 // [temp.deduct.general#3]
4636 // When all template arguments have been deduced
4637 // or obtained from default template arguments, all uses of template
4638 // parameters in the template parameter list of the template are
4639 // replaced with the corresponding deduced or default argument values
4640 //
4641 // If we have a trailing parameter pack, that has been deduced
4642 // previously we substitute the pack here in a similar fashion as
4643 // above with the trailing parameter packs. The main difference here is
4644 // that, in this case we are not processing all of the remaining
4645 // arguments. We are only process as many arguments as we have in
4646 // the already deduced parameter.
4647 std::optional<unsigned> ArgPosAfterSubstitution =
4648 PackScope.getSavedPackSizeIfAllEqual();
4649 if (!ArgPosAfterSubstitution)
4650 continue;
4651
4652 unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4653 for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4654 ParamTypesForArgChecking.push_back(ParamPattern);
4655 if (auto Result =
4656 DeduceCallArgument(ParamPattern, ArgIdx,
4657 /*ExplicitObjectArgument=*/false);
4659 return Result;
4660
4661 PackScope.nextPackElement();
4662 }
4663 }
4664 }
4665
4666 // Build argument packs for each of the parameter packs expanded by this
4667 // pack expansion.
4668 if (auto Result = PackScope.finish();
4670 return Result;
4671 }
4672
4673 // Capture the context in which the function call is made. This is the context
4674 // that is needed when the accessibility of template arguments is checked.
4675 DeclContext *CallingCtx = CurContext;
4676
4679 Result = FinishTemplateArgumentDeduction(
4680 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4681 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
4682 ContextRAII SavedContext(*this, CallingCtx);
4683 return CheckNonDependent(ParamTypesForArgChecking);
4684 });
4685 });
4686 return Result;
4687}
4688
4691 bool AdjustExceptionSpec) {
4692 if (ArgFunctionType.isNull())
4693 return ArgFunctionType;
4694
4695 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4696 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4697 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4698 bool Rebuild = false;
4699
4700 CallingConv CC = FunctionTypeP->getCallConv();
4701 if (EPI.ExtInfo.getCC() != CC) {
4702 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4703 Rebuild = true;
4704 }
4705
4706 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4707 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4708 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4709 Rebuild = true;
4710 }
4711
4712 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4713 ArgFunctionTypeP->hasExceptionSpec())) {
4714 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4715 Rebuild = true;
4716 }
4717
4718 if (!Rebuild)
4719 return ArgFunctionType;
4720
4721 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4722 ArgFunctionTypeP->getParamTypes(), EPI);
4723}
4724
4726 FunctionTemplateDecl *FunctionTemplate,
4727 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4729 bool IsAddressOfFunction) {
4730 if (FunctionTemplate->isInvalidDecl())
4732
4733 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4734 TemplateParameterList *TemplateParams
4735 = FunctionTemplate->getTemplateParameters();
4736 QualType FunctionType = Function->getType();
4737
4738 // Substitute any explicit template arguments.
4739 LocalInstantiationScope InstScope(*this);
4741 unsigned NumExplicitlySpecified = 0;
4742 SmallVector<QualType, 4> ParamTypes;
4743 if (ExplicitTemplateArgs) {
4746 Result = SubstituteExplicitTemplateArguments(
4747 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4748 &FunctionType, Info);
4749 });
4751 return Result;
4752
4753 NumExplicitlySpecified = Deduced.size();
4754 }
4755
4756 // When taking the address of a function, we require convertibility of
4757 // the resulting function type. Otherwise, we allow arbitrary mismatches
4758 // of calling convention and noreturn.
4759 if (!IsAddressOfFunction)
4760 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4761 /*AdjustExceptionSpec*/false);
4762
4763 // Unevaluated SFINAE context.
4766 SFINAETrap Trap(*this);
4767
4768 Deduced.resize(TemplateParams->size());
4769
4770 // If the function has a deduced return type, substitute it for a dependent
4771 // type so that we treat it as a non-deduced context in what follows.
4772 bool HasDeducedReturnType = false;
4773 if (getLangOpts().CPlusPlus14 &&
4774 Function->getReturnType()->getContainedAutoType()) {
4776 HasDeducedReturnType = true;
4777 }
4778
4779 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
4780 unsigned TDF =
4782 // Deduce template arguments from the function type.
4784 *this, TemplateParams, FunctionType, ArgFunctionType, Info, Deduced,
4785 TDF, PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4786 /*HasDeducedAnyParam=*/nullptr);
4788 return Result;
4789 }
4790
4793 Result = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
4794 NumExplicitlySpecified,
4795 Specialization, Info);
4796 });
4798 return Result;
4799
4800 // If the function has a deduced return type, deduce it now, so we can check
4801 // that the deduced function type matches the requested type.
4802 if (HasDeducedReturnType && IsAddressOfFunction &&
4803 Specialization->getReturnType()->isUndeducedType() &&
4806
4807 // [C++26][expr.const]/p17
4808 // An expression or conversion is immediate-escalating if it is not initially
4809 // in an immediate function context and it is [...]
4810 // a potentially-evaluated id-expression that denotes an immediate function.
4811 if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
4812 Specialization->isImmediateEscalating() &&
4813 parentEvaluationContext().isPotentiallyEvaluated() &&
4815 Info.getLocation()))
4817
4818 // Adjust the exception specification of the argument to match the
4819 // substituted and resolved type we just formed. (Calling convention and
4820 // noreturn can't be dependent, so we don't actually need this for them
4821 // right now.)
4822 QualType SpecializationType = Specialization->getType();
4823 if (!IsAddressOfFunction) {
4824 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4825 /*AdjustExceptionSpec*/true);
4826
4827 // Revert placeholder types in the return type back to undeduced types so
4828 // that the comparison below compares the declared return types.
4829 if (HasDeducedReturnType) {
4830 SpecializationType = SubstAutoType(SpecializationType, QualType());
4831 ArgFunctionType = SubstAutoType(ArgFunctionType, QualType());
4832 }
4833 }
4834
4835 // If the requested function type does not match the actual type of the
4836 // specialization with respect to arguments of compatible pointer to function
4837 // types, template argument deduction fails.
4838 if (!ArgFunctionType.isNull()) {
4839 if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
4840 SpecializationType, ArgFunctionType)
4842 SpecializationType, ArgFunctionType)) {
4843 Info.FirstArg = TemplateArgument(SpecializationType);
4844 Info.SecondArg = TemplateArgument(ArgFunctionType);
4846 }
4847 }
4848
4850}
4851
4853 FunctionTemplateDecl *ConversionTemplate, QualType ObjectType,
4854 Expr::Classification ObjectClassification, QualType A,
4856 if (ConversionTemplate->isInvalidDecl())
4858
4859 CXXConversionDecl *ConversionGeneric
4860 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4861
4862 QualType P = ConversionGeneric->getConversionType();
4863 bool IsReferenceP = P->isReferenceType();
4864 bool IsReferenceA = A->isReferenceType();
4865
4866 // C++0x [temp.deduct.conv]p2:
4867 // If P is a reference type, the type referred to by P is used for
4868 // type deduction.
4869 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4870 P = PRef->getPointeeType();
4871
4872 // C++0x [temp.deduct.conv]p4:
4873 // [...] If A is a reference type, the type referred to by A is used
4874 // for type deduction.
4875 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4876 A = ARef->getPointeeType();
4877 // We work around a defect in the standard here: cv-qualifiers are also
4878 // removed from P and A in this case, unless P was a reference type. This
4879 // seems to mostly match what other compilers are doing.
4880 if (!IsReferenceP) {
4881 A = A.getUnqualifiedType();
4882 P = P.getUnqualifiedType();
4883 }
4884
4885 // C++ [temp.deduct.conv]p3:
4886 //
4887 // If A is not a reference type:
4888 } else {
4889 assert(!A->isReferenceType() && "Reference types were handled above");
4890
4891 // - If P is an array type, the pointer type produced by the
4892 // array-to-pointer standard conversion (4.2) is used in place
4893 // of P for type deduction; otherwise,
4894 if (P->isArrayType())
4896 // - If P is a function type, the pointer type produced by the
4897 // function-to-pointer standard conversion (4.3) is used in
4898 // place of P for type deduction; otherwise,
4899 else if (P->isFunctionType())
4901 // - If P is a cv-qualified type, the top level cv-qualifiers of
4902 // P's type are ignored for type deduction.
4903 else
4904 P = P.getUnqualifiedType();
4905
4906 // C++0x [temp.deduct.conv]p4:
4907 // If A is a cv-qualified type, the top level cv-qualifiers of A's
4908 // type are ignored for type deduction. If A is a reference type, the type
4909 // referred to by A is used for type deduction.
4910 A = A.getUnqualifiedType();
4911 }
4912
4913 // Unevaluated SFINAE context.
4916 SFINAETrap Trap(*this);
4917
4918 // C++ [temp.deduct.conv]p1:
4919 // Template argument deduction is done by comparing the return
4920 // type of the template conversion function (call it P) with the
4921 // type that is required as the result of the conversion (call it
4922 // A) as described in 14.8.2.4.
4923 TemplateParameterList *TemplateParams
4924 = ConversionTemplate->getTemplateParameters();
4926 Deduced.resize(TemplateParams->size());
4927
4928 // C++0x [temp.deduct.conv]p4:
4929 // In general, the deduction process attempts to find template
4930 // argument values that will make the deduced A identical to
4931 // A. However, there are two cases that allow a difference:
4932 unsigned TDF = 0;
4933 // - If the original A is a reference type, A can be more
4934 // cv-qualified than the deduced A (i.e., the type referred to
4935 // by the reference)
4936 if (IsReferenceA)
4938 // - The deduced A can be another pointer or pointer to member
4939 // type that can be converted to A via a qualification
4940 // conversion.
4941 //
4942 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4943 // both P and A are pointers or member pointers. In this case, we
4944 // just ignore cv-qualifiers completely).
4945 if ((P->isPointerType() && A->isPointerType()) ||
4946 (P->isMemberPointerType() && A->isMemberPointerType()))
4947 TDF |= TDF_IgnoreQualifiers;
4948
4950 if (ConversionGeneric->isExplicitObjectMemberFunction()) {
4951 QualType ParamType = ConversionGeneric->getParamDecl(0)->getType();
4954 *this, TemplateParams, getFirstInnerIndex(ConversionTemplate),
4955 ParamType, ObjectType, ObjectClassification,
4956 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4957 /*Decomposed*/ false, 0, /*TDF*/ 0);
4959 return Result;
4960 }
4961
4963 *this, TemplateParams, P, A, Info, Deduced, TDF,
4964 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4965 /*HasDeducedAnyParam=*/nullptr);
4967 return Result;
4968
4969 // Create an Instantiation Scope for finalizing the operator.
4970 LocalInstantiationScope InstScope(*this);
4971 // Finish template argument deduction.
4972 FunctionDecl *ConversionSpecialized = nullptr;
4975 Result = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
4976 ConversionSpecialized, Info,
4977 &OriginalCallArgs);
4978 });
4979 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
4980 return Result;
4981}
4982
4985 TemplateArgumentListInfo *ExplicitTemplateArgs,
4988 bool IsAddressOfFunction) {
4989 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
4990 QualType(), Specialization, Info,
4991 IsAddressOfFunction);
4992}
4993
4994namespace {
4995 struct DependentAuto { bool IsPack; };
4996
4997 /// Substitute the 'auto' specifier or deduced template specialization type
4998 /// specifier within a type for a given replacement type.
4999 class SubstituteDeducedTypeTransform :
5000 public TreeTransform<SubstituteDeducedTypeTransform> {
5001 QualType Replacement;
5002 bool ReplacementIsPack;
5003 bool UseTypeSugar;
5005
5006 public:
5007 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
5008 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5009 ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
5010
5011 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
5012 bool UseTypeSugar = true)
5013 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5014 Replacement(Replacement), ReplacementIsPack(false),
5015 UseTypeSugar(UseTypeSugar) {}
5016
5017 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
5018 assert(isa<TemplateTypeParmType>(Replacement) &&
5019 "unexpected unsugared replacement kind");
5020 QualType Result = Replacement;
5022 NewTL.setNameLoc(TL.getNameLoc());
5023 return Result;
5024 }
5025
5026 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
5027 // If we're building the type pattern to deduce against, don't wrap the
5028 // substituted type in an AutoType. Certain template deduction rules
5029 // apply only when a template type parameter appears directly (and not if
5030 // the parameter is found through desugaring). For instance:
5031 // auto &&lref = lvalue;
5032 // must transform into "rvalue reference to T" not "rvalue reference to
5033 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
5034 //
5035 // FIXME: Is this still necessary?
5036 if (!UseTypeSugar)
5037 return TransformDesugared(TLB, TL);
5038
5039 QualType Result = SemaRef.Context.getAutoType(
5040 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
5041 ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(),
5043 auto NewTL = TLB.push<AutoTypeLoc>(Result);
5044 NewTL.copy(TL);
5045 return Result;
5046 }
5047
5048 QualType TransformDeducedTemplateSpecializationType(
5050 if (!UseTypeSugar)
5051 return TransformDesugared(TLB, TL);
5052
5053 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
5055 Replacement, Replacement.isNull());
5056 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5057 NewTL.setNameLoc(TL.getNameLoc());
5058 return Result;
5059 }
5060
5061 ExprResult TransformLambdaExpr(LambdaExpr *E) {
5062 // Lambdas never need to be transformed.
5063 return E;
5064 }
5065 bool TransformExceptionSpec(SourceLocation Loc,
5067 SmallVectorImpl<QualType> &Exceptions,
5068 bool &Changed) {
5069 if (ESI.Type == EST_Uninstantiated) {
5070 ESI.instantiate();
5071 Changed = true;
5072 }
5073 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
5074 }
5075
5076 QualType Apply(TypeLoc TL) {
5077 // Create some scratch storage for the transformed type locations.
5078 // FIXME: We're just going to throw this information away. Don't build it.
5079 TypeLocBuilder TLB;
5080 TLB.reserve(TL.getFullDataSize());
5081 return TransformType(TLB, TL);
5082 }
5083 };
5084
5085} // namespace
5086
5089 QualType Deduced) {
5090 ConstraintSatisfaction Satisfaction;
5091 ConceptDecl *Concept = Type.getTypeConstraintConcept();
5092 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
5093 TypeLoc.getRAngleLoc());
5094 TemplateArgs.addArgument(
5097 Deduced, TypeLoc.getNameLoc())));
5098 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
5099 TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
5100
5101 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
5103 Concept, SourceLocation(), TemplateArgs, /*DefaultArgs=*/{},
5104 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
5105 return true;
5106 MultiLevelTemplateArgumentList MLTAL(Concept, CanonicalConverted,
5107 /*Final=*/false);
5108 // Build up an EvaluationContext with an ImplicitConceptSpecializationDecl so
5109 // that the template arguments of the constraint can be preserved. For
5110 // example:
5111 //
5112 // template <class T>
5113 // concept C = []<D U = void>() { return true; }();
5114 //
5115 // We need the argument for T while evaluating type constraint D in
5116 // building the CallExpr to the lambda.
5120 S.getASTContext(), Concept->getDeclContext(), Concept->getLocation(),
5121 CanonicalConverted));
5122 if (S.CheckConstraintSatisfaction(Concept, {Concept->getConstraintExpr()},
5124 Satisfaction))
5125 return true;
5126 if (!Satisfaction.IsSatisfied) {
5127 std::string Buf;
5128 llvm::raw_string_ostream OS(Buf);
5129 OS << "'" << Concept->getName();
5130 if (TypeLoc.hasExplicitTemplateArgs()) {
5132 OS, Type.getTypeConstraintArguments(), S.getPrintingPolicy(),
5133 Type.getTypeConstraintConcept()->getTemplateParameters());
5134 }
5135 OS << "'";
5136 S.Diag(TypeLoc.getConceptNameLoc(),
5137 diag::err_placeholder_constraints_not_satisfied)
5138 << Deduced << Buf << TypeLoc.getLocalSourceRange();
5139 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
5140 return true;
5141 }
5142 return false;
5143}
5144
5147 TemplateDeductionInfo &Info, bool DependentDeduction,
5148 bool IgnoreConstraints,
5149 TemplateSpecCandidateSet *FailedTSC) {
5150 assert(DependentDeduction || Info.getDeducedDepth() == 0);
5151 if (Init->containsErrors())
5153
5154 const AutoType *AT = Type.getType()->getContainedAutoType();
5155 assert(AT);
5156
5157 if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
5158 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
5159 if (NonPlaceholder.isInvalid())
5161 Init = NonPlaceholder.get();
5162 }
5163
5164 DependentAuto DependentResult = {
5165 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
5166
5167 if (!DependentDeduction &&
5168 (Type.getType()->isDependentType() || Init->isTypeDependent() ||
5169 Init->containsUnexpandedParameterPack())) {
5170 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5171 assert(!Result.isNull() && "substituting DependentTy can't fail");
5173 }
5174
5175 // Make sure that we treat 'char[]' equaly as 'char*' in C23 mode.
5176 auto *String = dyn_cast<StringLiteral>(Init);
5177 if (getLangOpts().C23 && String && Type.getType()->isArrayType()) {
5178 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5179 TypeLoc TL = TypeLoc(Init->getType(), Type.getOpaqueData());
5180 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(TL);
5181 assert(!Result.isNull() && "substituting DependentTy can't fail");
5183 }
5184
5185 // Emit a warning if 'auto*' is used in pedantic and in C23 mode.
5186 if (getLangOpts().C23 && Type.getType()->isPointerType()) {
5187 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5188 }
5189
5190 auto *InitList = dyn_cast<InitListExpr>(Init);
5191 if (!getLangOpts().CPlusPlus && InitList) {
5192 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c)
5193 << (int)AT->getKeyword() << getLangOpts().C23;
5195 }
5196
5197 // Deduce type of TemplParam in Func(Init)
5199 Deduced.resize(1);
5200
5201 // If deduction failed, don't diagnose if the initializer is dependent; it
5202 // might acquire a matching type in the instantiation.
5203 auto DeductionFailed = [&](TemplateDeductionResult TDK) {
5204 if (Init->isTypeDependent()) {
5205 Result =
5206 SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5207 assert(!Result.isNull() && "substituting DependentTy can't fail");
5209 }
5210 return TDK;
5211 };
5212
5213 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
5214
5216 // If this is a 'decltype(auto)' specifier, do the decltype dance.
5217 if (AT->isDecltypeAuto()) {
5218 if (InitList) {
5219 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
5221 }
5222
5224 assert(!DeducedType.isNull());
5225 } else {
5226 LocalInstantiationScope InstScope(*this);
5227
5228 // Build template<class TemplParam> void Func(FuncParam);
5229 SourceLocation Loc = Init->getExprLoc();
5231 Context, nullptr, SourceLocation(), Loc, Info.getDeducedDepth(), 0,
5232 nullptr, false, false, false);
5233 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
5234 NamedDecl *TemplParamPtr = TemplParam;
5236 Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
5237
5238 if (InitList) {
5239 // Notionally, we substitute std::initializer_list<T> for 'auto' and
5240 // deduce against that. Such deduction only succeeds if removing
5241 // cv-qualifiers and references results in std::initializer_list<T>.
5242 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
5244
5245 SourceRange DeducedFromInitRange;
5246 for (Expr *Init : InitList->inits()) {
5247 // Resolving a core issue: a braced-init-list containing any designators
5248 // is a non-deduced context.
5249 if (isa<DesignatedInitExpr>(Init))
5252 *this, TemplateParamsSt.get(), 0, TemplArg, Init->getType(),
5253 Init->Classify(getASTContext()), Init, Info, Deduced,
5254 OriginalCallArgs,
5255 /*Decomposed=*/true,
5256 /*ArgIdx=*/0, /*TDF=*/0);
5259 Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction)
5260 << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
5261 << Init->getSourceRange();
5262 return DeductionFailed(TemplateDeductionResult::AlreadyDiagnosed);
5263 }
5264 return DeductionFailed(TDK);
5265 }
5266
5267 if (DeducedFromInitRange.isInvalid() &&
5268 Deduced[0].getKind() != TemplateArgument::Null)
5269 DeducedFromInitRange = Init->getSourceRange();
5270 }
5271 } else {
5272 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
5273 Diag(Loc, diag::err_auto_bitfield);
5275 }
5276 QualType FuncParam =
5277 SubstituteDeducedTypeTransform(*this, TemplArg).Apply(Type);
5278 assert(!FuncParam.isNull() &&
5279 "substituting template parameter for 'auto' failed");
5281 *this, TemplateParamsSt.get(), 0, FuncParam, Init->getType(),
5282 Init->Classify(getASTContext()), Init, Info, Deduced,
5283 OriginalCallArgs,
5284 /*Decomposed=*/false, /*ArgIdx=*/0, /*TDF=*/0, FailedTSC);
5286 return DeductionFailed(TDK);
5287 }
5288
5289 // Could be null if somehow 'auto' appears in a non-deduced context.
5290 if (Deduced[0].getKind() != TemplateArgument::Type)
5291 return DeductionFailed(TemplateDeductionResult::Incomplete);
5292 DeducedType = Deduced[0].getAsType();
5293
5294 if (InitList) {
5296 if (DeducedType.isNull())
5298 }
5299 }
5300
5301 if (!Result.isNull()) {
5303 Info.FirstArg = Result;
5304 Info.SecondArg = DeducedType;
5305 return DeductionFailed(TemplateDeductionResult::Inconsistent);
5306 }
5308 }
5309
5310 if (AT->isConstrained() && !IgnoreConstraints &&
5312 *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType))
5314
5315 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
5316 if (Result.isNull())
5318
5319 // Check that the deduced argument type is compatible with the original
5320 // argument type per C++ [temp.deduct.call]p4.
5321 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
5322 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
5323 assert((bool)InitList == OriginalArg.DecomposedParam &&
5324 "decomposed non-init-list in auto deduction?");
5325 if (auto TDK =
5326 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
5328 Result = QualType();
5329 return DeductionFailed(TDK);
5330 }
5331 }
5332
5334}
5335
5337 QualType TypeToReplaceAuto) {
5338 assert(TypeToReplaceAuto != Context.DependentTy);
5339 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5340 .TransformType(TypeWithAuto);
5341}
5342
5344 QualType TypeToReplaceAuto) {
5345 assert(TypeToReplaceAuto != Context.DependentTy);
5346 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5347 .TransformType(TypeWithAuto);
5348}
5349
5351 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5352 .TransformType(TypeWithAuto);
5353}
5354
5357 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5358 .TransformType(TypeWithAuto);
5359}
5360
5362 QualType TypeToReplaceAuto) {
5363 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5364 /*UseTypeSugar*/ false)
5365 .TransformType(TypeWithAuto);
5366}
5367
5369 QualType TypeToReplaceAuto) {
5370 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5371 /*UseTypeSugar*/ false)
5372 .TransformType(TypeWithAuto);
5373}
5374
5376 const Expr *Init) {
5377 if (isa<InitListExpr>(Init))
5378 Diag(VDecl->getLocation(),
5379 VDecl->isInitCapture()
5380 ? diag::err_init_capture_deduction_failure_from_init_list
5381 : diag::err_auto_var_deduction_failure_from_init_list)
5382 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
5383 else
5384 Diag(VDecl->getLocation(),
5385 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
5386 : diag::err_auto_var_deduction_failure)
5387 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5388 << Init->getSourceRange();
5389}
5390
5392 bool Diagnose) {
5393 assert(FD->getReturnType()->isUndeducedType());
5394
5395 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
5396 // within the return type from the call operator's type.
5398 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5399 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5400
5401 // For a generic lambda, instantiate the call operator if needed.
5402 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5404 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5405 if (!CallOp || CallOp->isInvalidDecl())
5406 return true;
5407
5408 // We might need to deduce the return type by instantiating the definition
5409 // of the operator() function.
5410 if (CallOp->getReturnType()->isUndeducedType()) {
5413 });
5414 }
5415 }
5416
5417 if (CallOp->isInvalidDecl())
5418 return true;
5419 assert(!CallOp->getReturnType()->isUndeducedType() &&
5420 "failed to deduce lambda return type");
5421
5422 // Build the new return type from scratch.
5423 CallingConv RetTyCC = FD->getReturnType()
5424 ->getPointeeType()
5425 ->castAs<FunctionType>()
5426 ->getCallConv();
5428 CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
5429 if (FD->getReturnType()->getAs<PointerType>())
5430 RetType = Context.getPointerType(RetType);
5431 else {
5432 assert(FD->getReturnType()->getAs<BlockPointerType>());
5433 RetType = Context.getBlockPointerType(RetType);
5434 }
5436 return false;
5437 }
5438
5442 });
5443 }
5444
5445 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
5446 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
5447 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
5448 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
5449 }
5450
5451 return StillUndeduced;
5452}
5453
5456 assert(FD->isImmediateEscalating());
5457
5459 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5460 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5461
5462 // For a generic lambda, instantiate the call operator if needed.
5463 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5465 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5466 if (!CallOp || CallOp->isInvalidDecl())
5467 return true;
5469 Loc, [&] { InstantiateFunctionDefinition(Loc, CallOp); });
5470 }
5471 return CallOp->isInvalidDecl();
5472 }
5473
5476 Loc, [&] { InstantiateFunctionDefinition(Loc, FD); });
5477 }
5478 return false;
5479}
5480
5482 const CXXMethodDecl *Method,
5483 QualType RawType,
5484 bool IsOtherRvr) {
5485 // C++20 [temp.func.order]p3.1, p3.2:
5486 // - The type X(M) is "rvalue reference to cv A" if the optional
5487 // ref-qualifier of M is && or if M has no ref-qualifier and the
5488 // positionally-corresponding parameter of the other transformed template
5489 // has rvalue reference type; if this determination depends recursively
5490 // upon whether X(M) is an rvalue reference type, it is not considered to
5491 // have rvalue reference type.
5492 //
5493 // - Otherwise, X(M) is "lvalue reference to cv A".
5494 assert(Method && !Method->isExplicitObjectMemberFunction() &&
5495 "expected a member function with no explicit object parameter");
5496
5497 RawType = Context.getQualifiedType(RawType, Method->getMethodQualifiers());
5498 if (Method->getRefQualifier() == RQ_RValue ||
5499 (IsOtherRvr && Method->getRefQualifier() == RQ_None))
5500 return Context.getRValueReferenceType(RawType);
5501 return Context.getLValueReferenceType(RawType);
5502}
5503
5505 Sema &S, FunctionTemplateDecl *FTD, int ArgIdx, QualType P, QualType A,
5506 ArrayRef<TemplateArgument> DeducedArgs, bool CheckConsistency) {
5507 MultiLevelTemplateArgumentList MLTAL(FTD, DeducedArgs,
5508 /*Final=*/true);
5510 S, ArgIdx != -1 ? ::getPackIndexForParam(S, FTD, MLTAL, ArgIdx) : -1);
5511 bool IsIncompleteSubstitution = false;
5512 // FIXME: A substitution can be incomplete on a non-structural part of the
5513 // type. Use the canonical type for now, until the TemplateInstantiator can
5514 // deal with that.
5515 QualType InstP = S.SubstType(P.getCanonicalType(), MLTAL, FTD->getLocation(),
5516 FTD->getDeclName(), &IsIncompleteSubstitution);
5517 if (InstP.isNull() && !IsIncompleteSubstitution)
5519 if (!CheckConsistency)
5521 if (IsIncompleteSubstitution)
5523
5524 // [temp.deduct.call]/4 - Check we produced a consistent deduction.
5525 // This handles just the cases that can appear when partial ordering.
5526 if (auto *PA = dyn_cast<PackExpansionType>(A);
5527 PA && !isa<PackExpansionType>(InstP))
5528 A = PA->getPattern();
5529 if (!S.Context.hasSameType(
5534}
5535
5536template <class T>
5538 Sema &S, FunctionTemplateDecl *FTD,
5543 Sema::SFINAETrap Trap(S);
5544
5545 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(FTD));
5546
5547 // C++26 [temp.deduct.type]p2:
5548 // [...] or if any template argument remains neither deduced nor
5549 // explicitly specified, template argument deduction fails.
5550 bool IsIncomplete = false;
5551 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
5553 S, FTD, /*IsDeduced=*/true, Deduced, Info, SugaredBuilder,
5554 CanonicalBuilder, /*CurrentInstantiationScope=*/nullptr,
5555 /*NumAlreadyConverted=*/0, &IsIncomplete);
5557 return Result;
5558
5559 // Form the template argument list from the deduced template arguments.
5560 TemplateArgumentList *SugaredDeducedArgumentList =
5561 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
5562 TemplateArgumentList *CanonicalDeducedArgumentList =
5563 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
5564
5565 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
5566
5567 // Substitute the deduced template arguments into the argument
5568 // and verify that the instantiated argument is both valid
5569 // and equivalent to the parameter.
5570 LocalInstantiationScope InstScope(S);
5571
5572 if (auto TDR = CheckDeductionConsistency(S, FTD, SugaredBuilder);
5574 return TDR;
5575
5578}
5579
5580/// Determine whether the function template \p FT1 is at least as
5581/// specialized as \p FT2.
5585 ArrayRef<QualType> Args1, ArrayRef<QualType> Args2, bool Args1Offset) {
5586 FunctionDecl *FD1 = FT1->getTemplatedDecl();
5587 FunctionDecl *FD2 = FT2->getTemplatedDecl();
5588 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
5589 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
5590 assert(Proto1 && Proto2 && "Function templates must have prototypes");
5591
5592 // C++26 [temp.deduct.partial]p3:
5593 // The types used to determine the ordering depend on the context in which
5594 // the partial ordering is done:
5595 // - In the context of a function call, the types used are those function
5596 // parameter types for which the function call has arguments.
5597 // - In the context of a call to a conversion operator, the return types
5598 // of the conversion function templates are used.
5599 // - In other contexts (14.6.6.2) the function template's function type
5600 // is used.
5601
5602 if (TPOC == TPOC_Other) {
5603 // We wouldn't be partial ordering these candidates if these didn't match.
5604 assert(Proto1->getMethodQuals() == Proto2->getMethodQuals() &&
5605 Proto1->getRefQualifier() == Proto2->getRefQualifier() &&
5606 Proto1->isVariadic() == Proto2->isVariadic() &&
5607 "shouldn't partial order functions with different qualifiers in a "
5608 "context where the function type is used");
5609
5610 assert(Args1.empty() && Args2.empty() &&
5611 "Only call context should have arguments");
5612 Args1 = Proto1->getParamTypes();
5613 Args2 = Proto2->getParamTypes();
5614 }
5615
5616 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
5617 SmallVector<DeducedTemplateArgument, 4> Deduced(TemplateParams->size());
5619
5620 bool HasDeducedAnyParamFromReturnType = false;
5621 if (TPOC != TPOC_Call) {
5623 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
5624 Info, Deduced, TDF_None, PartialOrderingKind::Call,
5625 /*DeducedFromArrayBound=*/false,
5626 &HasDeducedAnyParamFromReturnType) !=
5628 return false;
5629 }
5630
5631 llvm::SmallBitVector HasDeducedParam;
5632 if (TPOC != TPOC_Conversion) {
5633 HasDeducedParam.resize(Args2.size());
5634 if (DeduceTemplateArguments(S, TemplateParams, Args2, Args1, Info, Deduced,
5635 TDF_None, PartialOrderingKind::Call,
5636 /*HasDeducedAnyParam=*/nullptr,
5637 &HasDeducedParam) !=
5639 return false;
5640 }
5641
5642 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
5644 S, Info.getLocation(), FT2, DeducedArgs,
5646 if (Inst.isInvalid())
5647 return false;
5648
5649 bool AtLeastAsSpecialized;
5651 AtLeastAsSpecialized =
5652 ::FinishTemplateArgumentDeduction(
5653 S, FT2, Deduced, Info,
5654 [&](Sema &S, FunctionTemplateDecl *FTD,
5655 ArrayRef<TemplateArgument> DeducedArgs) {
5656 // As a provisional fix for a core issue that does not
5657 // exist yet, which may be related to CWG2160, only check the
5658 // consistency of parameters and return types which participated
5659 // in deduction. We will still try to substitute them though.
5660 if (TPOC != TPOC_Call) {
5661 if (auto TDR = ::CheckDeductionConsistency(
5662 S, FTD, /*ArgIdx=*/-1, Proto2->getReturnType(),
5663 Proto1->getReturnType(), DeducedArgs,
5664 /*CheckConsistency=*/HasDeducedAnyParamFromReturnType);
5665 TDR != TemplateDeductionResult::Success)
5666 return TDR;
5667 }
5668
5669 if (TPOC == TPOC_Conversion)
5670 return TemplateDeductionResult::Success;
5671
5672 return ::DeduceForEachType(
5673 S, TemplateParams, Args2, Args1, Info, Deduced,
5674 PartialOrderingKind::Call, /*FinishingDeduction=*/true,
5675 [&](Sema &S, TemplateParameterList *, int ParamIdx,
5676 int ArgIdx, QualType P, QualType A,
5677 TemplateDeductionInfo &Info,
5678 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5679 PartialOrderingKind) {
5680 if (ArgIdx != -1)
5681 ArgIdx -= Args1Offset;
5682 return ::CheckDeductionConsistency(
5683 S, FTD, ArgIdx, P, A, DeducedArgs,
5684 /*CheckConsistency=*/HasDeducedParam[ParamIdx]);
5685 });
5687 });
5688 if (!AtLeastAsSpecialized)
5689 return false;
5690
5691 // C++0x [temp.deduct.partial]p11:
5692 // In most cases, all template parameters must have values in order for
5693 // deduction to succeed, but for partial ordering purposes a template
5694 // parameter may remain without a value provided it is not used in the
5695 // types being used for partial ordering. [ Note: a template parameter used
5696 // in a non-deduced context is considered used. -end note]
5697 unsigned ArgIdx = 0, NumArgs = Deduced.size();
5698 for (; ArgIdx != NumArgs; ++ArgIdx)
5699 if (Deduced[ArgIdx].isNull())
5700 break;
5701
5702 if (ArgIdx == NumArgs) {
5703 // All template arguments were deduced. FT1 is at least as specialized
5704 // as FT2.
5705 return true;
5706 }
5707
5708 // Figure out which template parameters were used.
5709 llvm::SmallBitVector UsedParameters(TemplateParams->size());
5710 switch (TPOC) {
5711 case TPOC_Call:
5712 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
5713 ::MarkUsedTemplateParameters(S.Context, Args2[I], /*OnlyDeduced=*/false,
5714 TemplateParams->getDepth(), UsedParameters);
5715 break;
5716
5717 case TPOC_Conversion:
5718 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(),
5719 /*OnlyDeduced=*/false,
5720 TemplateParams->getDepth(), UsedParameters);
5721 break;
5722
5723 case TPOC_Other:
5724 // We do not deduce template arguments from the exception specification
5725 // when determining the primary template of a function template
5726 // specialization or when taking the address of a function template.
5727 // Therefore, we do not mark template parameters in the exception
5728 // specification as used during partial ordering to prevent the following
5729 // from being ambiguous:
5730 //
5731 // template<typename T, typename U>
5732 // void f(U) noexcept(noexcept(T())); // #1
5733 //
5734 // template<typename T>
5735 // void f(T*) noexcept; // #2
5736 //
5737 // template<>
5738 // void f<int>(int*) noexcept; // explicit specialization of #2
5739 //
5740 // Although there is no corresponding wording in the standard, this seems
5741 // to be the intended behavior given the definition of
5742 // 'deduction substitution loci' in [temp.deduct].
5744 S.Context,
5746 /*OnlyDeduced=*/false, TemplateParams->getDepth(), UsedParameters);
5747 break;
5748 }
5749
5750 for (; ArgIdx != NumArgs; ++ArgIdx)
5751 // If this argument had no value deduced but was used in one of the types
5752 // used for partial ordering, then deduction fails.
5753 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
5754 return false;
5755
5756 return true;
5757}
5758
5761 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
5762 QualType RawObj1Ty, QualType RawObj2Ty, bool Reversed) {
5765 const FunctionDecl *FD1 = FT1->getTemplatedDecl();
5766 const FunctionDecl *FD2 = FT2->getTemplatedDecl();
5767 bool ShouldConvert1 = false;
5768 bool ShouldConvert2 = false;
5769 bool Args1Offset = false;
5770 bool Args2Offset = false;
5771 QualType Obj1Ty;
5772 QualType Obj2Ty;
5773 if (TPOC == TPOC_Call) {
5774 const FunctionProtoType *Proto1 =
5775 FD1->getType()->castAs<FunctionProtoType>();
5776 const FunctionProtoType *Proto2 =
5777 FD2->getType()->castAs<FunctionProtoType>();
5778
5779 // - In the context of a function call, the function parameter types are
5780 // used.
5781 const CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
5782 const CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
5783 // C++20 [temp.func.order]p3
5784 // [...] Each function template M that is a member function is
5785 // considered to have a new first parameter of type
5786 // X(M), described below, inserted in its function parameter list.
5787 //
5788 // Note that we interpret "that is a member function" as
5789 // "that is a member function with no expicit object argument".
5790 // Otherwise the ordering rules for methods with expicit objet arguments
5791 // against anything else make no sense.
5792
5793 bool NonStaticMethod1 = Method1 && !Method1->isStatic(),
5794 NonStaticMethod2 = Method2 && !Method2->isStatic();
5795
5796 auto Params1Begin = Proto1->param_type_begin(),
5797 Params2Begin = Proto2->param_type_begin();
5798
5799 size_t NumComparedArguments = NumCallArguments1;
5800
5801 if (auto OO = FD1->getOverloadedOperator();
5802 (NonStaticMethod1 && NonStaticMethod2) ||
5803 (OO != OO_None && OO != OO_Call && OO != OO_Subscript)) {
5804 ShouldConvert1 =
5805 NonStaticMethod1 && !Method1->hasCXXExplicitFunctionObjectParameter();
5806 ShouldConvert2 =
5807 NonStaticMethod2 && !Method2->hasCXXExplicitFunctionObjectParameter();
5808 NumComparedArguments += 1;
5809
5810 if (ShouldConvert1) {
5811 bool IsRValRef2 =
5812 ShouldConvert2
5813 ? Method2->getRefQualifier() == RQ_RValue
5814 : Proto2->param_type_begin()[0]->isRValueReferenceType();
5815 // Compare 'this' from Method1 against first parameter from Method2.
5816 Obj1Ty = GetImplicitObjectParameterType(this->Context, Method1,
5817 RawObj1Ty, IsRValRef2);
5818 Args1.push_back(Obj1Ty);
5819 Args1Offset = true;
5820 }
5821 if (ShouldConvert2) {
5822 bool IsRValRef1 =
5823 ShouldConvert1
5824 ? Method1->getRefQualifier() == RQ_RValue
5825 : Proto1->param_type_begin()[0]->isRValueReferenceType();
5826 // Compare 'this' from Method2 against first parameter from Method1.
5827 Obj2Ty = GetImplicitObjectParameterType(this->Context, Method2,
5828 RawObj2Ty, IsRValRef1);
5829 Args2.push_back(Obj2Ty);
5830 Args2Offset = true;
5831 }
5832 } else {
5833 if (NonStaticMethod1 && Method1->hasCXXExplicitFunctionObjectParameter())
5834 Params1Begin += 1;
5835 if (NonStaticMethod2 && Method2->hasCXXExplicitFunctionObjectParameter())
5836 Params2Begin += 1;
5837 }
5838 Args1.insert(Args1.end(), Params1Begin, Proto1->param_type_end());
5839 Args2.insert(Args2.end(), Params2Begin, Proto2->param_type_end());
5840
5841 // C++ [temp.func.order]p5:
5842 // The presence of unused ellipsis and default arguments has no effect on
5843 // the partial ordering of function templates.
5844 Args1.resize(std::min(Args1.size(), NumComparedArguments));
5845 Args2.resize(std::min(Args2.size(), NumComparedArguments));
5846
5847 if (Reversed)
5848 std::reverse(Args2.begin(), Args2.end());
5849 } else {
5850 assert(!Reversed && "Only call context could have reversed arguments");
5851 }
5852 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, Args1,
5853 Args2, Args2Offset);
5854 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, Args2,
5855 Args1, Args1Offset);
5856 // C++ [temp.deduct.partial]p10:
5857 // F is more specialized than G if F is at least as specialized as G and G
5858 // is not at least as specialized as F.
5859 if (Better1 != Better2) // We have a clear winner
5860 return Better1 ? FT1 : FT2;
5861
5862 if (!Better1 && !Better2) // Neither is better than the other
5863 return nullptr;
5864
5865 // C++ [temp.deduct.partial]p11:
5866 // ... and if G has a trailing function parameter pack for which F does not
5867 // have a corresponding parameter, and if F does not have a trailing
5868 // function parameter pack, then F is more specialized than G.
5869
5870 SmallVector<QualType> Param1;
5871 Param1.reserve(FD1->param_size() + ShouldConvert1);
5872 if (ShouldConvert1)
5873 Param1.push_back(Obj1Ty);
5874 for (const auto &P : FD1->parameters())
5875 Param1.push_back(P->getType());
5876
5877 SmallVector<QualType> Param2;
5878 Param2.reserve(FD2->param_size() + ShouldConvert2);
5879 if (ShouldConvert2)
5880 Param2.push_back(Obj2Ty);
5881 for (const auto &P : FD2->parameters())
5882 Param2.push_back(P->getType());
5883
5884 unsigned NumParams1 = Param1.size();
5885 unsigned NumParams2 = Param2.size();
5886
5887 bool Variadic1 =
5888 FD1->param_size() && FD1->parameters().back()->isParameterPack();
5889 bool Variadic2 =
5890 FD2->param_size() && FD2->parameters().back()->isParameterPack();
5891 if (Variadic1 != Variadic2) {
5892 if (Variadic1 && NumParams1 > NumParams2)
5893 return FT2;
5894 if (Variadic2 && NumParams2 > NumParams1)
5895 return FT1;
5896 }
5897
5898 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
5899 // there is no wording or even resolution for this issue.
5900 for (int i = 0, e = std::min(NumParams1, NumParams2); i < e; ++i) {
5901 QualType T1 = Param1[i].getCanonicalType();
5902 QualType T2 = Param2[i].getCanonicalType();
5903 auto *TST1 = dyn_cast<TemplateSpecializationType>(T1);
5904 auto *TST2 = dyn_cast<TemplateSpecializationType>(T2);
5905 if (!TST1 || !TST2)
5906 continue;
5907 const TemplateArgument &TA1 = TST1->template_arguments().back();
5908 if (TA1.getKind() == TemplateArgument::Pack) {
5909 assert(TST1->template_arguments().size() ==
5910 TST2->template_arguments().size());
5911 const TemplateArgument &TA2 = TST2->template_arguments().back();
5912 assert(TA2.getKind() == TemplateArgument::Pack);
5913 unsigned PackSize1 = TA1.pack_size();
5914 unsigned PackSize2 = TA2.pack_size();
5915 bool IsPackExpansion1 =
5916 PackSize1 && TA1.pack_elements().back().isPackExpansion();
5917 bool IsPackExpansion2 =
5918 PackSize2 && TA2.pack_elements().back().isPackExpansion();
5919 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
5920 if (PackSize1 > PackSize2 && IsPackExpansion1)
5921 return FT2;
5922 if (PackSize1 < PackSize2 && IsPackExpansion2)
5923 return FT1;
5924 }
5925 }
5926 }
5927
5928 if (!Context.getLangOpts().CPlusPlus20)
5929 return nullptr;
5930
5931 // Match GCC on not implementing [temp.func.order]p6.2.1.
5932
5933 // C++20 [temp.func.order]p6:
5934 // If deduction against the other template succeeds for both transformed
5935 // templates, constraints can be considered as follows:
5936
5937 // C++20 [temp.func.order]p6.1:
5938 // If their template-parameter-lists (possibly including template-parameters
5939 // invented for an abbreviated function template ([dcl.fct])) or function
5940 // parameter lists differ in length, neither template is more specialized
5941 // than the other.
5944 if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
5945 return nullptr;
5946
5947 // C++20 [temp.func.order]p6.2.2:
5948 // Otherwise, if the corresponding template-parameters of the
5949 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
5950 // function parameters that positionally correspond between the two
5951 // templates are not of the same type, neither template is more specialized
5952 // than the other.
5953 if (!TemplateParameterListsAreEqual(TPL1, TPL2, false,
5955 return nullptr;
5956
5957 // [dcl.fct]p5:
5958 // Any top-level cv-qualifiers modifying a parameter type are deleted when
5959 // forming the function type.
5960 for (unsigned i = 0; i < NumParams1; ++i)
5961 if (!Context.hasSameUnqualifiedType(Param1[i], Param2[i]))
5962 return nullptr;
5963
5964 // C++20 [temp.func.order]p6.3:
5965 // Otherwise, if the context in which the partial ordering is done is
5966 // that of a call to a conversion function and the return types of the
5967 // templates are not the same, then neither template is more specialized
5968 // than the other.
5969 if (TPOC == TPOC_Conversion &&
5971 return nullptr;
5972
5974 FT1->getAssociatedConstraints(AC1);
5975 FT2->getAssociatedConstraints(AC2);
5976 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
5977 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
5978 return nullptr;
5979 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
5980 return nullptr;
5981 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
5982 return nullptr;
5983 return AtLeastAsConstrained1 ? FT1 : FT2;
5984}
5985
5988 TemplateSpecCandidateSet &FailedCandidates,
5989 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
5990 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
5991 bool Complain, QualType TargetType) {
5992 if (SpecBegin == SpecEnd) {
5993 if (Complain) {
5994 Diag(Loc, NoneDiag);
5995 FailedCandidates.NoteCandidates(*this, Loc);
5996 }
5997 return SpecEnd;
5998 }
5999
6000 if (SpecBegin + 1 == SpecEnd)
6001 return SpecBegin;
6002
6003 // Find the function template that is better than all of the templates it
6004 // has been compared to.
6005 UnresolvedSetIterator Best = SpecBegin;
6006 FunctionTemplateDecl *BestTemplate
6007 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
6008 assert(BestTemplate && "Not a function template specialization?");
6009 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
6010 FunctionTemplateDecl *Challenger
6011 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6012 assert(Challenger && "Not a function template specialization?");
6013 if (declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6014 Loc, TPOC_Other, 0),
6015 Challenger)) {
6016 Best = I;
6017 BestTemplate = Challenger;
6018 }
6019 }
6020
6021 // Make sure that the "best" function template is more specialized than all
6022 // of the others.
6023 bool Ambiguous = false;
6024 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6025 FunctionTemplateDecl *Challenger
6026 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6027 if (I != Best &&
6028 !declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6029 Loc, TPOC_Other, 0),
6030 BestTemplate)) {
6031 Ambiguous = true;
6032 break;
6033 }
6034 }
6035
6036 if (!Ambiguous) {
6037 // We found an answer. Return it.
6038 return Best;
6039 }
6040
6041 // Diagnose the ambiguity.
6042 if (Complain) {
6043 Diag(Loc, AmbigDiag);
6044
6045 // FIXME: Can we order the candidates in some sane way?
6046 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6047 PartialDiagnostic PD = CandidateDiag;
6048 const auto *FD = cast<FunctionDecl>(*I);
6050 FD->getPrimaryTemplate()->getTemplateParameters(),
6051 *FD->getTemplateSpecializationArgs());
6052 if (!TargetType.isNull())
6053 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
6054 Diag((*I)->getLocation(), PD);
6055 }
6056 }
6057
6058 return SpecEnd;
6059}
6060
6062 FunctionDecl *FD2) {
6063 assert(!FD1->getDescribedTemplate() && !FD2->getDescribedTemplate() &&
6064 "not for function templates");
6065 assert(!FD1->isFunctionTemplateSpecialization() ||
6066 isa<CXXConversionDecl>(FD1));
6067 assert(!FD2->isFunctionTemplateSpecialization() ||
6068 isa<CXXConversionDecl>(FD2));
6069
6070 FunctionDecl *F1 = FD1;
6072 F1 = P;
6073
6074 FunctionDecl *F2 = FD2;
6076 F2 = P;
6077
6079 F1->getAssociatedConstraints(AC1);
6080 F2->getAssociatedConstraints(AC2);
6081 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6082 if (IsAtLeastAsConstrained(F1, AC1, F2, AC2, AtLeastAsConstrained1))
6083 return nullptr;
6084 if (IsAtLeastAsConstrained(F2, AC2, F1, AC1, AtLeastAsConstrained2))
6085 return nullptr;
6086 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6087 return nullptr;
6088 return AtLeastAsConstrained1 ? FD1 : FD2;
6089}
6090
6091/// Determine whether one partial specialization, P1, is at least as
6092/// specialized than another, P2.
6093///
6094/// \tparam TemplateLikeDecl The kind of P2, which must be a
6095/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
6096/// \param T1 The injected-class-name of P1 (faked for a variable template).
6097/// \param T2 The injected-class-name of P2 (faked for a variable template).
6098template<typename TemplateLikeDecl>
6100 TemplateLikeDecl *P2,
6101 TemplateDeductionInfo &Info) {
6102 // C++ [temp.class.order]p1:
6103 // For two class template partial specializations, the first is at least as
6104 // specialized as the second if, given the following rewrite to two
6105 // function templates, the first function template is at least as
6106 // specialized as the second according to the ordering rules for function
6107 // templates (14.6.6.2):
6108 // - the first function template has the same template parameters as the
6109 // first partial specialization and has a single function parameter
6110 // whose type is a class template specialization with the template
6111 // arguments of the first partial specialization, and
6112 // - the second function template has the same template parameters as the
6113 // second partial specialization and has a single function parameter
6114 // whose type is a class template specialization with the template
6115 // arguments of the second partial specialization.
6116 //
6117 // Rather than synthesize function templates, we merely perform the
6118 // equivalent partial ordering by performing deduction directly on
6119 // the template arguments of the class template partial
6120 // specializations. This computation is slightly simpler than the
6121 // general problem of function template partial ordering, because
6122 // class template partial specializations are more constrained. We
6123 // know that every template parameter is deducible from the class
6124 // template partial specialization's template arguments, for
6125 // example.
6127
6128 // Determine whether P1 is at least as specialized as P2.
6129 Deduced.resize(P2->getTemplateParameters()->size());
6131 S, P2->getTemplateParameters(), T2, T1, Info, Deduced, TDF_None,
6132 PartialOrderingKind::Call, /*DeducedFromArrayBound=*/false,
6133 /*HasDeducedAnyParam=*/nullptr) != TemplateDeductionResult::Success)
6134 return false;
6135
6136 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
6137 Deduced.end());
6138 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
6139 Info);
6140 if (Inst.isInvalid())
6141 return false;
6142
6143 const auto *TST1 = cast<TemplateSpecializationType>(T1);
6144 bool AtLeastAsSpecialized;
6146 AtLeastAsSpecialized =
6147 FinishTemplateArgumentDeduction(
6148 S, P2, /*IsPartialOrdering=*/true, TST1->template_arguments(),
6149 Deduced, Info) == TemplateDeductionResult::Success;
6150 });
6151 return AtLeastAsSpecialized;
6152}
6153
6154namespace {
6155// A dummy class to return nullptr instead of P2 when performing "more
6156// specialized than primary" check.
6157struct GetP2 {
6158 template <typename T1, typename T2,
6159 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6160 T2 *operator()(T1 *, T2 *P2) {
6161 return P2;
6162 }
6163 template <typename T1, typename T2,
6164 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6165 T1 *operator()(T1 *, T2 *) {
6166 return nullptr;
6167 }
6168};
6169
6170// The assumption is that two template argument lists have the same size.
6171struct TemplateArgumentListAreEqual {
6172 ASTContext &Ctx;
6173 TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
6174
6175 template <typename T1, typename T2,
6176 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6177 bool operator()(T1 *PS1, T2 *PS2) {
6178 ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
6179 Args2 = PS2->getTemplateArgs().asArray();
6180
6181 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6182 // We use profile, instead of structural comparison of the arguments,
6183 // because canonicalization can't do the right thing for dependent
6184 // expressions.
6185 llvm::FoldingSetNodeID IDA, IDB;
6186 Args1[I].Profile(IDA, Ctx);
6187 Args2[I].Profile(IDB, Ctx);
6188 if (IDA != IDB)
6189 return false;
6190 }
6191 return true;
6192 }
6193
6194 template <typename T1, typename T2,
6195 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6196 bool operator()(T1 *Spec, T2 *Primary) {
6197 ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
6198 Args2 = Primary->getInjectedTemplateArgs(Ctx);
6199
6200 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6201 // We use profile, instead of structural comparison of the arguments,
6202 // because canonicalization can't do the right thing for dependent
6203 // expressions.
6204 llvm::FoldingSetNodeID IDA, IDB;
6205 Args1[I].Profile(IDA, Ctx);
6206 // Unlike the specialization arguments, the injected arguments are not
6207 // always canonical.
6208 Ctx.getCanonicalTemplateArgument(Args2[I]).Profile(IDB, Ctx);
6209 if (IDA != IDB)
6210 return false;
6211 }
6212 return true;
6213 }
6214};
6215} // namespace
6216
6217/// Returns the more specialized template specialization between T1/P1 and
6218/// T2/P2.
6219/// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
6220/// specialization and T2/P2 is the primary template.
6221/// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
6222///
6223/// \param T1 the type of the first template partial specialization
6224///
6225/// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
6226/// template partial specialization; otherwise, the type of the
6227/// primary template.
6228///
6229/// \param P1 the first template partial specialization
6230///
6231/// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
6232/// partial specialization; otherwise, the primary template.
6233///
6234/// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
6235/// more specialized, returns nullptr if P1 is not more specialized.
6236/// - otherwise, returns the more specialized template partial
6237/// specialization. If neither partial specialization is more
6238/// specialized, returns NULL.
6239template <typename TemplateLikeDecl, typename PrimaryDel>
6240static TemplateLikeDecl *
6241getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
6242 PrimaryDel *P2, TemplateDeductionInfo &Info) {
6243 constexpr bool IsMoreSpecialThanPrimaryCheck =
6244 !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
6245
6246 bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, Info);
6247 if (IsMoreSpecialThanPrimaryCheck && !Better1)
6248 return nullptr;
6249
6250 bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1, Info);
6251 if (IsMoreSpecialThanPrimaryCheck && !Better2)
6252 return P1;
6253
6254 // C++ [temp.deduct.partial]p10:
6255 // F is more specialized than G if F is at least as specialized as G and G
6256 // is not at least as specialized as F.
6257 if (Better1 != Better2) // We have a clear winner
6258 return Better1 ? P1 : GetP2()(P1, P2);
6259
6260 if (!Better1 && !Better2)
6261 return nullptr;
6262
6263 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
6264 // there is no wording or even resolution for this issue.
6265 auto *TST1 = cast<TemplateSpecializationType>(T1);
6266 auto *TST2 = cast<TemplateSpecializationType>(T2);
6267 const TemplateArgument &TA1 = TST1->template_arguments().back();
6268 if (TA1.getKind() == TemplateArgument::Pack) {
6269 assert(TST1->template_arguments().size() ==
6270 TST2->template_arguments().size());
6271 const TemplateArgument &TA2 = TST2->template_arguments().back();
6272 assert(TA2.getKind() == TemplateArgument::Pack);
6273 unsigned PackSize1 = TA1.pack_size();
6274 unsigned PackSize2 = TA2.pack_size();
6275 bool IsPackExpansion1 =
6276 PackSize1 && TA1.pack_elements().back().isPackExpansion();
6277 bool IsPackExpansion2 =
6278 PackSize2 && TA2.pack_elements().back().isPackExpansion();
6279 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
6280 if (PackSize1 > PackSize2 && IsPackExpansion1)
6281 return GetP2()(P1, P2);
6282 if (PackSize1 < PackSize2 && IsPackExpansion2)
6283 return P1;
6284 }
6285 }
6286
6287 if (!S.Context.getLangOpts().CPlusPlus20)
6288 return nullptr;
6289
6290 // Match GCC on not implementing [temp.func.order]p6.2.1.
6291
6292 // C++20 [temp.func.order]p6:
6293 // If deduction against the other template succeeds for both transformed
6294 // templates, constraints can be considered as follows:
6295
6296 TemplateParameterList *TPL1 = P1->getTemplateParameters();
6297 TemplateParameterList *TPL2 = P2->getTemplateParameters();
6298 if (TPL1->size() != TPL2->size())
6299 return nullptr;
6300
6301 // C++20 [temp.func.order]p6.2.2:
6302 // Otherwise, if the corresponding template-parameters of the
6303 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6304 // function parameters that positionally correspond between the two
6305 // templates are not of the same type, neither template is more specialized
6306 // than the other.
6307 if (!S.TemplateParameterListsAreEqual(TPL1, TPL2, false,
6309 return nullptr;
6310
6311 if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
6312 return nullptr;
6313
6315 P1->getAssociatedConstraints(AC1);
6316 P2->getAssociatedConstraints(AC2);
6317 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6318 if (S.IsAtLeastAsConstrained(P1, AC1, P2, AC2, AtLeastAsConstrained1) ||
6319 (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
6320 return nullptr;
6321 if (S.IsAtLeastAsConstrained(P2, AC2, P1, AC1, AtLeastAsConstrained2))
6322 return nullptr;
6323 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6324 return nullptr;
6325 return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
6326}
6327
6335
6337 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6338}
6339
6342 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
6343 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
6344 QualType PartialT = Spec->getInjectedSpecializationType();
6345
6347 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6348 if (MaybeSpec)
6349 Info.clearSFINAEDiagnostic();
6350 return MaybeSpec;
6351}
6352
6357 // Pretend the variable template specializations are class template
6358 // specializations and form a fake injected class name type for comparison.
6359 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
6360 "the partial specializations being compared should specialize"
6361 " the same template.");
6364 Name, PS1->getTemplateArgs().asArray());
6366 Name, PS2->getTemplateArgs().asArray());
6367
6369 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6370}
6371
6374 VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
6375 TemplateName Name(Primary);
6377 Name, Primary->getInjectedTemplateArgs(Context));
6379 Name, Spec->getTemplateArgs().asArray());
6380
6382 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6383 if (MaybeSpec)
6384 Info.clearSFINAEDiagnostic();
6385 return MaybeSpec;
6386}
6387
6390 const DefaultArguments &DefaultArgs, SourceLocation Loc, bool IsDeduced) {
6391 // C++1z [temp.arg.template]p4: (DR 150)
6392 // A template template-parameter P is at least as specialized as a
6393 // template template-argument A if, given the following rewrite to two
6394 // function templates...
6395
6396 // Rather than synthesize function templates, we merely perform the
6397 // equivalent partial ordering by performing deduction directly on
6398 // the template parameter lists of the template template parameters.
6399 //
6401
6402 // Given an invented class template X with the template parameter list of
6403 // A (including default arguments):
6404 // - Each function template has a single function parameter whose type is
6405 // a specialization of X with template arguments corresponding to the
6406 // template parameters from the respective function template
6408
6409 // Check P's arguments against A's parameter list. This will fill in default
6410 // template arguments as needed. AArgs are already correct by construction.
6411 // We can't just use CheckTemplateIdType because that will expand alias
6412 // templates.
6413 SmallVector<TemplateArgument, 4> PArgs(P->getInjectedTemplateArgs(Context));
6414 {
6415 TemplateArgumentListInfo PArgList(P->getLAngleLoc(),
6416 P->getRAngleLoc());
6417 for (unsigned I = 0, N = P->size(); I != N; ++I) {
6418 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
6419 // expansions, to form an "as written" argument list.
6420 TemplateArgument Arg = PArgs[I];
6421 if (Arg.getKind() == TemplateArgument::Pack) {
6422 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
6423 Arg = *Arg.pack_begin();
6424 }
6426 Arg, QualType(), P->getParam(I)->getLocation()));
6427 }
6428 PArgs.clear();
6429
6430 SFINAETrap Trap(*this);
6431 // C++1z [temp.arg.template]p3:
6432 // If the rewrite produces an invalid type, then P is not at least as
6433 // specialized as A.
6435 if (CheckTemplateArgumentList(AArg, Loc, PArgList, DefaultArgs, false,
6436 SugaredPArgs, PArgs,
6437 /*UpdateArgsWithConversions=*/true,
6438 /*ConstraintsNotSatisfied=*/nullptr,
6439 /*PartialOrderTTP=*/true) ||
6440 Trap.hasErrorOccurred())
6441 return false;
6442 }
6443
6444 // Determine whether P1 is at least as specialized as P2.
6447 Deduced.resize(A->size());
6448
6449 // ... the function template corresponding to P is at least as specialized
6450 // as the function template corresponding to A according to the partial
6451 // ordering rules for function templates.
6452
6453 // Provisional resolution for CWG2398: Regarding temp.arg.template]p4, when
6454 // applying the partial ordering rules for function templates on
6455 // the rewritten template template parameters:
6456 // - In a deduced context, the matching of packs versus fixed-size needs to
6457 // be inverted between Ps and As. On non-deduced context, matching needs to
6458 // happen both ways, according to [temp.arg.template]p3, but this is
6459 // currently implemented as a special case elsewhere.
6460 if (::DeduceTemplateArguments(*this, A, AArgs, PArgs, Info, Deduced,
6461 /*NumberOfArgumentsMustMatch=*/false,
6462 /*PartialOrdering=*/true,
6463 IsDeduced ? PackFold::ArgumentToParameter
6464 : PackFold::ParameterToArgument,
6465 /*HasDeducedAnyParam=*/nullptr) !=
6467 return false;
6468
6469 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
6470 Sema::InstantiatingTemplate Inst(*this, Info.getLocation(), AArg, DeducedArgs,
6471 Info);
6472 if (Inst.isInvalid())
6473 return false;
6474
6475 bool AtLeastAsSpecialized;
6477 AtLeastAsSpecialized =
6478 ::FinishTemplateArgumentDeduction(
6479 *this, AArg, /*IsPartialOrdering=*/true, PArgs, Deduced, Info) ==
6480 TemplateDeductionResult::Success;
6481 });
6482 return AtLeastAsSpecialized;
6483}
6484
6485namespace {
6486struct MarkUsedTemplateParameterVisitor : DynamicRecursiveASTVisitor {
6487 llvm::SmallBitVector &Used;
6488 unsigned Depth;
6489
6490 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used,
6491 unsigned Depth)
6492 : Used(Used), Depth(Depth) { }
6493
6494 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
6495 if (T->getDepth() == Depth)
6496 Used[T->getIndex()] = true;
6497 return true;
6498 }
6499
6500 bool TraverseTemplateName(TemplateName Template) override {
6501 if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
6502 Template.getAsTemplateDecl()))
6503 if (TTP->getDepth() == Depth)
6504 Used[TTP->getIndex()] = true;
6506 return true;
6507 }
6508
6509 bool VisitDeclRefExpr(DeclRefExpr *E) override {
6510 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
6511 if (NTTP->getDepth() == Depth)
6512 Used[NTTP->getIndex()] = true;
6513 return true;
6514 }
6515};
6516}
6517
6518/// Mark the template parameters that are used by the given
6519/// expression.
6520static void
6522 const Expr *E,
6523 bool OnlyDeduced,
6524 unsigned Depth,
6525 llvm::SmallBitVector &Used) {
6526 if (!OnlyDeduced) {
6527 MarkUsedTemplateParameterVisitor(Used, Depth)
6528 .TraverseStmt(const_cast<Expr *>(E));
6529 return;
6530 }
6531
6532 // We can deduce from a pack expansion.
6533 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
6534 E = Expansion->getPattern();
6535
6537 if (!NTTP)
6538 return;
6539
6540 if (NTTP->getDepth() == Depth)
6541 Used[NTTP->getIndex()] = true;
6542
6543 // In C++17 mode, additional arguments may be deduced from the type of a
6544 // non-type argument.
6545 if (Ctx.getLangOpts().CPlusPlus17)
6546 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
6547}
6548
6549/// Mark the template parameters that are used by the given
6550/// nested name specifier.
6551static void
6554 bool OnlyDeduced,
6555 unsigned Depth,
6556 llvm::SmallBitVector &Used) {
6557 if (!NNS)
6558 return;
6559
6560 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
6561 Used);
6563 OnlyDeduced, Depth, Used);
6564}
6565
6566/// Mark the template parameters that are used by the given
6567/// template name.
6568static void
6570 TemplateName Name,
6571 bool OnlyDeduced,
6572 unsigned Depth,
6573 llvm::SmallBitVector &Used) {
6574 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
6576 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
6577 if (TTP->getDepth() == Depth)
6578 Used[TTP->getIndex()] = true;
6579 }
6580 return;
6581 }
6582
6583 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
6584 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
6585 Depth, Used);
6586 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
6587 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
6588 Depth, Used);
6589}
6590
6591/// Mark the template parameters that are used by the given
6592/// type.
6593static void
6595 bool OnlyDeduced,
6596 unsigned Depth,
6597 llvm::SmallBitVector &Used) {
6598 if (T.isNull())
6599 return;
6600
6601 // Non-dependent types have nothing deducible
6602 if (!T->isDependentType())
6603 return;
6604
6605 T = Ctx.getCanonicalType(T);
6606 switch (T->getTypeClass()) {
6607 case Type::Pointer:
6609 cast<PointerType>(T)->getPointeeType(),
6610 OnlyDeduced,
6611 Depth,
6612 Used);
6613 break;
6614
6615 case Type::BlockPointer:
6617 cast<BlockPointerType>(T)->getPointeeType(),
6618 OnlyDeduced,
6619 Depth,
6620 Used);
6621 break;
6622
6623 case Type::LValueReference:
6624 case Type::RValueReference:
6626 cast<ReferenceType>(T)->getPointeeType(),
6627 OnlyDeduced,
6628 Depth,
6629 Used);
6630 break;
6631
6632 case Type::MemberPointer: {
6633 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
6634 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
6635 Depth, Used);
6636 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
6637 OnlyDeduced, Depth, Used);
6638 break;
6639 }
6640
6641 case Type::DependentSizedArray:
6643 cast<DependentSizedArrayType>(T)->getSizeExpr(),
6644 OnlyDeduced, Depth, Used);
6645 // Fall through to check the element type
6646 [[fallthrough]];
6647
6648 case Type::ConstantArray:
6649 case Type::IncompleteArray:
6650 case Type::ArrayParameter:
6652 cast<ArrayType>(T)->getElementType(),
6653 OnlyDeduced, Depth, Used);
6654 break;
6655 case Type::Vector:
6656 case Type::ExtVector:
6658 cast<VectorType>(T)->getElementType(),
6659 OnlyDeduced, Depth, Used);
6660 break;
6661
6662 case Type::DependentVector: {
6663 const auto *VecType = cast<DependentVectorType>(T);
6664 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6665 Depth, Used);
6666 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
6667 Used);
6668 break;
6669 }
6670 case Type::DependentSizedExtVector: {
6671 const DependentSizedExtVectorType *VecType
6672 = cast<DependentSizedExtVectorType>(T);
6673 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6674 Depth, Used);
6675 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
6676 Depth, Used);
6677 break;
6678 }
6679
6680 case Type::DependentAddressSpace: {
6681 const DependentAddressSpaceType *DependentASType =
6682 cast<DependentAddressSpaceType>(T);
6683 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
6684 OnlyDeduced, Depth, Used);
6686 DependentASType->getAddrSpaceExpr(),
6687 OnlyDeduced, Depth, Used);
6688 break;
6689 }
6690
6691 case Type::ConstantMatrix: {
6692 const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T);
6693 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6694 Depth, Used);
6695 break;
6696 }
6697
6698 case Type::DependentSizedMatrix: {
6699 const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(T);
6700 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6701 Depth, Used);
6702 MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
6703 Used);
6704 MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
6705 Depth, Used);
6706 break;
6707 }
6708
6709 case Type::FunctionProto: {
6710 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
6711 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
6712 Used);
6713 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
6714 // C++17 [temp.deduct.type]p5:
6715 // The non-deduced contexts are: [...]
6716 // -- A function parameter pack that does not occur at the end of the
6717 // parameter-declaration-list.
6718 if (!OnlyDeduced || I + 1 == N ||
6719 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
6720 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
6721 Depth, Used);
6722 } else {
6723 // FIXME: C++17 [temp.deduct.call]p1:
6724 // When a function parameter pack appears in a non-deduced context,
6725 // the type of that pack is never deduced.
6726 //
6727 // We should also track a set of "never deduced" parameters, and
6728 // subtract that from the list of deduced parameters after marking.
6729 }
6730 }
6731 if (auto *E = Proto->getNoexceptExpr())
6732 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
6733 break;
6734 }
6735
6736 case Type::TemplateTypeParm: {
6737 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
6738 if (TTP->getDepth() == Depth)
6739 Used[TTP->getIndex()] = true;
6740 break;
6741 }
6742
6743 case Type::SubstTemplateTypeParmPack: {
6745 = cast<SubstTemplateTypeParmPackType>(T);
6746 if (Subst->getReplacedParameter()->getDepth() == Depth)
6747 Used[Subst->getIndex()] = true;
6749 OnlyDeduced, Depth, Used);
6750 break;
6751 }
6752
6753 case Type::InjectedClassName:
6754 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
6755 [[fallthrough]];
6756
6757 case Type::TemplateSpecialization: {
6758 const TemplateSpecializationType *Spec
6759 = cast<TemplateSpecializationType>(T);
6760 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
6761 Depth, Used);
6762
6763 // C++0x [temp.deduct.type]p9:
6764 // If the template argument list of P contains a pack expansion that is
6765 // not the last template argument, the entire template argument list is a
6766 // non-deduced context.
6767 if (OnlyDeduced &&
6769 break;
6770
6771 for (const auto &Arg : Spec->template_arguments())
6772 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6773 break;
6774 }
6775
6776 case Type::Complex:
6777 if (!OnlyDeduced)
6779 cast<ComplexType>(T)->getElementType(),
6780 OnlyDeduced, Depth, Used);
6781 break;
6782
6783 case Type::Atomic:
6784 if (!OnlyDeduced)
6786 cast<AtomicType>(T)->getValueType(),
6787 OnlyDeduced, Depth, Used);
6788 break;
6789
6790 case Type::DependentName:
6791 if (!OnlyDeduced)
6793 cast<DependentNameType>(T)->getQualifier(),
6794 OnlyDeduced, Depth, Used);
6795 break;
6796
6797 case Type::DependentTemplateSpecialization: {
6798 // C++14 [temp.deduct.type]p5:
6799 // The non-deduced contexts are:
6800 // -- The nested-name-specifier of a type that was specified using a
6801 // qualified-id
6802 //
6803 // C++14 [temp.deduct.type]p6:
6804 // When a type name is specified in a way that includes a non-deduced
6805 // context, all of the types that comprise that type name are also
6806 // non-deduced.
6807 if (OnlyDeduced)
6808 break;
6809
6811 = cast<DependentTemplateSpecializationType>(T);
6812
6814 OnlyDeduced, Depth, Used);
6815
6816 for (const auto &Arg : Spec->template_arguments())
6817 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6818 break;
6819 }
6820
6821 case Type::TypeOf:
6822 if (!OnlyDeduced)
6823 MarkUsedTemplateParameters(Ctx, cast<TypeOfType>(T)->getUnmodifiedType(),
6824 OnlyDeduced, Depth, Used);
6825 break;
6826
6827 case Type::TypeOfExpr:
6828 if (!OnlyDeduced)
6830 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
6831 OnlyDeduced, Depth, Used);
6832 break;
6833
6834 case Type::Decltype:
6835 if (!OnlyDeduced)
6837 cast<DecltypeType>(T)->getUnderlyingExpr(),
6838 OnlyDeduced, Depth, Used);
6839 break;
6840
6841 case Type::PackIndexing:
6842 if (!OnlyDeduced) {
6843 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getPattern(),
6844 OnlyDeduced, Depth, Used);
6845 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getIndexExpr(),
6846 OnlyDeduced, Depth, Used);
6847 }
6848 break;
6849
6850 case Type::UnaryTransform:
6851 if (!OnlyDeduced)
6853 cast<UnaryTransformType>(T)->getUnderlyingType(),
6854 OnlyDeduced, Depth, Used);
6855 break;
6856
6857 case Type::PackExpansion:
6859 cast<PackExpansionType>(T)->getPattern(),
6860 OnlyDeduced, Depth, Used);
6861 break;
6862
6863 case Type::Auto:
6864 case Type::DeducedTemplateSpecialization:
6866 cast<DeducedType>(T)->getDeducedType(),
6867 OnlyDeduced, Depth, Used);
6868 break;
6869 case Type::DependentBitInt:
6871 cast<DependentBitIntType>(T)->getNumBitsExpr(),
6872 OnlyDeduced, Depth, Used);
6873 break;
6874
6875 case Type::HLSLAttributedResource:
6877 Ctx, cast<HLSLAttributedResourceType>(T)->getWrappedType(), OnlyDeduced,
6878 Depth, Used);
6879 if (cast<HLSLAttributedResourceType>(T)->hasContainedType())
6881 Ctx, cast<HLSLAttributedResourceType>(T)->getContainedType(),
6882 OnlyDeduced, Depth, Used);
6883 break;
6884
6885 // None of these types have any template parameters in them.
6886 case Type::Builtin:
6887 case Type::VariableArray:
6888 case Type::FunctionNoProto:
6889 case Type::Record:
6890 case Type::Enum:
6891 case Type::ObjCInterface:
6892 case Type::ObjCObject:
6893 case Type::ObjCObjectPointer:
6894 case Type::UnresolvedUsing:
6895 case Type::Pipe:
6896 case Type::BitInt:
6897#define TYPE(Class, Base)
6898#define ABSTRACT_TYPE(Class, Base)
6899#define DEPENDENT_TYPE(Class, Base)
6900#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6901#include "clang/AST/TypeNodes.inc"
6902 break;
6903 }
6904}
6905
6906/// Mark the template parameters that are used by this
6907/// template argument.
6908static void
6911 bool OnlyDeduced,
6912 unsigned Depth,
6913 llvm::SmallBitVector &Used) {
6914 switch (TemplateArg.getKind()) {
6920 break;
6921
6923 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
6924 Depth, Used);
6925 break;
6926
6930 TemplateArg.getAsTemplateOrTemplatePattern(),
6931 OnlyDeduced, Depth, Used);
6932 break;
6933
6935 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
6936 Depth, Used);
6937 break;
6938
6940 for (const auto &P : TemplateArg.pack_elements())
6941 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
6942 break;
6943 }
6944}
6945
6946void
6947Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
6948 unsigned Depth,
6949 llvm::SmallBitVector &Used) {
6950 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
6951}
6952
6953void
6955 bool OnlyDeduced, unsigned Depth,
6956 llvm::SmallBitVector &Used) {
6957 // C++0x [temp.deduct.type]p9:
6958 // If the template argument list of P contains a pack expansion that is not
6959 // the last template argument, the entire template argument list is a
6960 // non-deduced context.
6961 if (OnlyDeduced &&
6962 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
6963 return;
6964
6965 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6966 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
6967 Depth, Used);
6968}
6969
6971 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
6972 llvm::SmallBitVector &Deduced) {
6973 TemplateParameterList *TemplateParams
6974 = FunctionTemplate->getTemplateParameters();
6975 Deduced.clear();
6976 Deduced.resize(TemplateParams->size());
6977
6978 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
6979 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
6980 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
6981 true, TemplateParams->getDepth(), Deduced);
6982}
6983
6985 FunctionTemplateDecl *FunctionTemplate,
6986 QualType T) {
6987 if (!T->isDependentType())
6988 return false;
6989
6990 TemplateParameterList *TemplateParams
6991 = FunctionTemplate->getTemplateParameters();
6992 llvm::SmallBitVector Deduced(TemplateParams->size());
6993 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
6994 Deduced);
6995
6996 return Deduced.any();
6997}
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Provides definitions for the various language-specific address spaces.
const Decl * D
Expr * E
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1172
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
llvm::DenseSet< const void * > Visited
Definition: HTMLLogger.cpp:145
#define X(type, name)
Definition: Value.h:144
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static QualType getUnderlyingType(const SubRegion *R)
SourceLocation Loc
Definition: SemaObjC.cpp:759
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
static bool isSameTemplateArg(ASTContext &Context, TemplateArgument X, const TemplateArgument &Y, bool PartialOrdering, bool PackExpansionMatchesPack=false)
Determine whether two template arguments are the same.
static TemplateDeductionResult DeduceTemplateSpecArguments(Sema &S, TemplateParameterList *TemplateParams, const QualType P, QualType A, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
static TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch(Sema &S, TemplateParameterList *TemplateParams, QualType Param, QualType Arg, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned TDF, PartialOrderingKind POK, bool DeducedFromArrayBound, bool *HasDeducedAnyParam)
Deduce the template arguments by comparing the parameter type and the argument type (C++ [temp....
static PartialOrderingKind degradeCallPartialOrderingKind(PartialOrderingKind POK)
When propagating a partial ordering kind into a NonCall context, this is used to downgrade a 'Call' i...
static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y)
Compare two APSInts, extending and switching the sign as necessary to compare their values regardless...
static TemplateLikeDecl * getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1, PrimaryDel *P2, TemplateDeductionInfo &Info)
Returns the more specialized template specialization between T1/P1 and T2/P2.
static DeducedTemplateArgument checkDeducedTemplateArguments(ASTContext &Context, const DeducedTemplateArgument &X, const DeducedTemplateArgument &Y, bool AggregateCandidateDeduction=false)
Verify that the given, deduced template arguments are compatible.
static bool isSameDeclaration(Decl *X, Decl *Y)
Determine whether two declaration pointers refer to the same declaration.
static TemplateDeductionResult DeduceForEachType(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< QualType > Params, ArrayRef< QualType > Args, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, PartialOrderingKind POK, bool FinishingDeduction, T &&DeductFunc)
static TemplateDeductionResult DeduceTemplateBases(Sema &S, const CXXRecordDecl *RD, TemplateParameterList *TemplateParams, QualType P, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
Attempt to deduce the template arguments by checking the base types according to (C++20 [temp....
static bool hasTemplateArgumentForDeduction(ArrayRef< TemplateArgument > &Args, unsigned &ArgIdx)
Determine whether there is a template argument to be used for deduction.
static DeclContext * getAsDeclContextOrEnclosing(Decl *D)
static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType, QualType ArgType)
Determine whether the parameter has qualifiers that the argument lacks.
static TemplateDeductionResult DeduceNullPtrTemplateArgument(Sema &S, TemplateParameterList *TemplateParams, const NonTypeTemplateParmDecl *NTTP, QualType NullPtrType, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
Deduce the value of the given non-type template parameter from the given null pointer template argume...
static void MarkUsedTemplateParameters(ASTContext &Ctx, const TemplateArgument &TemplateArg, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark the template parameters that are used by this template argument.
static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R, FunctionDecl *Fn)
Gets the type of a function for template-argument-deducton purposes when it's considered as part of a...
static TemplateDeductionResult CheckDeducedArgumentConstraints(Sema &S, TemplateDeclT *Template, ArrayRef< TemplateArgument > SugaredDeducedArgs, ArrayRef< TemplateArgument > CanonicalDeducedArgs, TemplateDeductionInfo &Info)
static const NonTypeTemplateParmDecl * getDeducedParameterFromExpr(const Expr *E, unsigned Depth)
If the given expression is of a form that permits the deduction of a non-type template parameter,...
static TemplateDeductionResult DeduceNonTypeTemplateArgument(Sema &S, TemplateParameterList *TemplateParams, const NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced, QualType ValueType, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
Deduce the value of the given non-type template parameter as the given deduced template argument.
static bool hasPackExpansionBeforeEnd(ArrayRef< TemplateArgument > Args)
Determine whether the given set of template arguments has a pack expansion that is not the last templ...
static bool isSimpleTemplateIdType(QualType T)
Determine whether the given type T is a simple-template-id type.
PartialOrderingKind
The kind of PartialOrdering we're performing template argument deduction for (C++11 [temp....
static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template, TemplateDeductionInfo &Info, bool IsDeduced, SmallVectorImpl< TemplateArgument > &SugaredOutput, SmallVectorImpl< TemplateArgument > &CanonicalOutput)
Convert the given deduced template argument and add it to the set of fully-converted template argumen...
static TemplateParameter makeTemplateParameter(Decl *D)
Helper function to build a TemplateParameter when we don't know its type statically.
static TemplateDeductionResult CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info, Sema::OriginalCallArg OriginalArg, QualType DeducedA)
Check whether the deduced argument type for a call to a function template matches the actual argument...
static unsigned getPackIndexForParam(Sema &S, FunctionTemplateDecl *FunctionTemplate, const MultiLevelTemplateArgumentList &Args, unsigned ParamIdx)
Find the pack index for a particular parameter index in an instantiation of a function template with ...
static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, QualType &ParamType, QualType &ArgType, Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF, TemplateSpecCandidateSet *FailedTSC=nullptr)
Perform the adjustments to the parameter and argument types described in C++ [temp....
static TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, QualType ParamType, QualType ArgType, Expr::Classification ArgClassification, Expr *Arg, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< Sema::OriginalCallArg > &OriginalCallArgs, bool DecomposedParam, unsigned ArgIdx, unsigned TDF, TemplateSpecCandidateSet *FailedTSC=nullptr)
Perform template argument deduction per [temp.deduct.call] for a single parameter / argument pair.
static bool isAtLeastAsSpecializedAs(Sema &S, SourceLocation Loc, FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, TemplatePartialOrderingContext TPOC, ArrayRef< QualType > Args1, ArrayRef< QualType > Args2, bool Args1Offset)
Determine whether the function template FT1 is at least as specialized as FT2.
static QualType GetImplicitObjectParameterType(ASTContext &Context, const CXXMethodDecl *Method, QualType RawType, bool IsOtherRvr)
static TemplateDeductionResult DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType, InitListExpr *ILE, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< Sema::OriginalCallArg > &OriginalCallArgs, unsigned ArgIdx, unsigned TDF)
Attempt template argument deduction from an initializer list deemed to be an argument in a function c...
static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD)
Get the index of the first template parameter that was originally from the innermost template-paramet...
@ ArgumentToParameter
@ ParameterToArgument
static bool DeducedArgsNeedReplacement(TemplateDeclT *Template)
static TemplateDeductionResult CheckDeductionConsistency(Sema &S, FunctionTemplateDecl *FTD, int ArgIdx, QualType P, QualType A, ArrayRef< TemplateArgument > DeducedArgs, bool CheckConsistency)
static QualType ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams, Expr *Arg, QualType ParamType, bool ParamWasReference, TemplateSpecCandidateSet *FailedTSC=nullptr)
Apply the deduction rules for overload sets.
static bool IsPossiblyOpaquelyQualifiedType(QualType T)
Determines whether the given type is an opaque type that might be more qualified when instantiated.
static const TemplateSpecializationType * getLastTemplateSpecType(QualType QT)
Deduce the template arguments by comparing the template parameter type (which is a template-id) with ...
static std::enable_if_t< IsPartialSpecialization< T >::value, TemplateDeductionResult > FinishTemplateArgumentDeduction(Sema &S, T *Partial, bool IsPartialOrdering, ArrayRef< TemplateArgument > TemplateArgs, SmallVectorImpl< DeducedTemplateArgument > &Deduced, TemplateDeductionInfo &Info)
Complete template argument deduction for a partial specialization.
static TemplateDeductionResult instantiateExplicitSpecifierDeferred(Sema &S, FunctionDecl *Specialization, const MultiLevelTemplateArgumentList &SubstArgs, TemplateDeductionInfo &Info, FunctionTemplateDecl *FunctionTemplate, ArrayRef< TemplateArgument > DeducedArgs)
static bool CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type, AutoTypeLoc TypeLoc, QualType Deduced)
static bool IsPossiblyOpaquelyQualifiedTypeInternal(const Type *T)
static bool hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate, QualType T)
static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex)
Determine whether a type denotes a forwarding reference.
bool DeducedArgsNeedReplacement< VarTemplatePartialSpecializationDecl >(VarTemplatePartialSpecializationDecl *Spec)
static TemplateDeductionResult ConvertDeducedTemplateArguments(Sema &S, TemplateDeclT *Template, bool IsDeduced, SmallVectorImpl< DeducedTemplateArgument > &Deduced, TemplateDeductionInfo &Info, SmallVectorImpl< TemplateArgument > &SugaredBuilder, SmallVectorImpl< TemplateArgument > &CanonicalBuilder, LocalInstantiationScope *CurrentInstantiationScope=nullptr, unsigned NumAlreadyConverted=0, bool *IsIncomplete=nullptr)
bool DeducedArgsNeedReplacement< ClassTemplatePartialSpecializationDecl >(ClassTemplatePartialSpecializationDecl *Spec)
static bool isParameterPack(Expr *PackExpression)
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
Allows QualTypes to be sorted and hence used in maps and sets.
C Language Family Type Representation.
__device__ int
#define bool
Definition: amdgpuintrin.h:20
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2915
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
unsigned getIntWidth(QualType T) const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2716
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2732
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
TemplateName getCanonicalTemplateName(TemplateName Name, bool IgnoreDeduced=false) const
Retrieves the "canonical" template name that refers to a given template.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2921
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1188
CanQualType NullPtrTy
Definition: ASTContext.h:1187
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
const LangOptions & getLangOpts() const
Definition: ASTContext.h:834
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
CanQualType BoolTy
Definition: ASTContext.h:1161
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
Definition: ASTContext.h:1169
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2289
LangAS getDefaultOpenCLPointeeAddrSpace()
Returns default address space based on OpenCL version and enabled features.
Definition: ASTContext.h:1528
CanQualType OverloadTy
Definition: ASTContext.h:1188
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2763
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl) const
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2482
CanQualType UnsignedIntTy
Definition: ASTContext.h:1170
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false)
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1681
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y, bool IgnoreDeduced=false) const
Determine whether the given template names refer to the same template.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
TemplateName getDeducedTemplateName(TemplateName Underlying, DefaultArguments DefaultArgs) const
Represents a TemplateName which had some of its default arguments deduced.
const DependentSizedArrayType * getAsDependentSizedArrayType(QualType T) const
Definition: ASTContext.h:2924
The result of parsing/analyzing an expression, statement etc.
Definition: Ownership.h:153
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6561
ArrayRef< TemplateArgument > getTypeConstraintArguments() const
Definition: Type.h:6571
bool isDecltypeAuto() const
Definition: Type.h:6584
ConceptDecl * getTypeConstraintConcept() const
Definition: Type.h:6576
AutoTypeKeyword getKeyword() const
Definition: Type.h:6592
bool isConstrained() const
Definition: Type.h:6580
A fixed int type of a specified bitwidth.
Definition: Type.h:7819
Pointer to a block type.
Definition: Type.h:3408
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2885
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2925
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition: DeclCXX.cpp:2549
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2254
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2239
bool isStatic() const
Definition: DeclCXX.cpp:2280
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
base_class_range bases()
Definition: DeclCXX.h:620
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1688
Declaration of a class template.
QualType getInjectedClassNameSpecialization()
Retrieve the template specialization type of the injected-class-name for this class template.
QualType getInjectedSpecializationType() const
Retrieves the injected specialization type for this partial specialization.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
bool isClassScopeExplicitSpecialization() const
Is this an explicit specialization at class scope (within the class that owns the primary template)?...
Complex values, per C99 6.2.5p11.
Definition: Type.h:3145
Declaration of a C++20 concept.
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:421
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4232
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4253
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4250
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
A POD class for pairing a NamedDecl* with an access specifier.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition: DeclBase.cpp:258
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1215
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:239
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1206
bool isInvalidDecl() const
Definition: DeclBase.h:591
SourceLocation getLocation() const
Definition: DeclBase.h:442
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:229
DeclContext * getDeclContext()
Definition: DeclBase.h:451
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:907
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:967
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:430
Captures a template argument whose value has been deduced via c++ template argument deduction.
Definition: Template.h:327
void setDeducedFromArrayBound(bool Deduced)
Specify whether the given non-type template argument was deduced from an array bound.
Definition: Template.h:354
bool wasDeducedFromArrayBound() const
For a non-type template argument, determine whether the template argument was deduced from an array b...
Definition: Template.h:350
TemplateName getTemplateName() const
Retrieve the name of the template that we are deducing.
Definition: Type.h:6628
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6527
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3920
Expr * getAddrSpaceExpr() const
Definition: Type.h:3931
QualType getPointeeType() const
Definition: Type.h:3932
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3960
QualType getElementType() const
Definition: Type.h:3975
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4291
Expr * getColumnExpr() const
Definition: Type.h:4304
Expr * getRowExpr() const
Definition: Type.h:4303
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:548
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:7081
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:7100
NestedNameSpecifier * getQualifier() const
Definition: Type.h:7097
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4086
Recursive AST visitor that supports extension via dynamic dispatch.
virtual bool TraverseTemplateName(TemplateName Template)
Recursively visit a template name and dispatch to the appropriate method.
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6948
RAII object that enters a new expression evaluation context.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1912
bool isInvalid() const
Determine if the explicit specifier is invalid.
Definition: DeclCXX.h:1941
const Expr * getExpr() const
Definition: DeclCXX.h:1921
The return type of classify().
Definition: Expr.h:330
bool isLValue() const
Definition: Expr.h:380
This represents one expression.
Definition: Expr.h:110
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:276
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:405
QualType getType() const
Definition: Expr.h:142
ExtVectorType - Extended vector type.
Definition: Type.h:4126
Stores a list of template parameters and the associated requires-clause (if any) for a TemplateDecl a...
Definition: DeclTemplate.h:228
Represents a function declaration or definition.
Definition: Decl.h:1935
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4064
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4052
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3741
QualType getReturnType() const
Definition: Decl.h:2720
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:4123
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4188
bool isImmediateEscalating() const
Definition: Decl.cpp:3275
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3989
void getAssociatedConstraints(SmallVectorImpl< const Expr * > &AC) const
Get the associated-constraints of this function declaration.
Definition: Decl.h:2627
size_t param_size() const
Definition: Decl.h:2665
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3210
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5107
param_type_iterator param_type_begin() const
Definition: Type.h:5520
const ExtParameterInfo * getExtParameterInfosOrNull() const
Return a pointer to the beginning of the array of extra parameter information, if present,...
Definition: Type.h:5558
unsigned getNumParams() const
Definition: Type.h:5360
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: Type.h:5500
Qualifiers getMethodQuals() const
Definition: Type.h:5502
QualType getParamType(unsigned i) const
Definition: Type.h:5362
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5393
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5484
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5371
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:5445
param_type_iterator param_type_end() const
Definition: Type.h:5524
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5367
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition: Type.h:5510
Declaration of a template function.
Definition: DeclTemplate.h:959
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
QualType getReturnType() const
Definition: Type.h:4648
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes an C or C++ initializer list.
Definition: Expr.h:5088
unsigned getNumInits() const
Definition: Expr.h:5118
ArrayRef< Expr * > inits()
Definition: Expr.h:5128
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6798
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3483
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
void SetPartiallySubstitutedPack(NamedDecl *Pack, const TemplateArgument *ExplicitArgs, unsigned NumExplicitArgs)
Note that the given parameter pack has been partially substituted via explicit specification of templ...
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: Type.h:4196
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4210
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
QualType getPointeeType() const
Definition: Type.h:3535
const Type * getClass() const
Definition: Type.h:3549
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args)
Replaces the current 'innermost' level with the provided argument list.
Definition: Template.h:237
This represents a decl that may have a name.
Definition: Decl.h:253
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
Class that aids in the construction of nested-name-specifiers along with source-location information ...
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Represents a pointer to an Objective C object.
Definition: Type.h:7585
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition: ExprCXX.h:2983
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition: ExprCXX.h:3135
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3044
SourceLocation getNameLoc() const
Gets the location of the name.
Definition: ExprCXX.h:3096
decls_iterator decls_begin() const
Definition: ExprCXX.h:3076
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition: ExprCXX.h:3155
decls_iterator decls_end() const
Definition: ExprCXX.h:3079
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4180
Represents a pack expansion of types.
Definition: Type.h:7146
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:7167
std::optional< unsigned > getNumExpansions() const
Retrieve the number of expansions that this pack expansion will generate, if known.
Definition: Type.h:7171
bool hasSelectedType() const
Definition: Type.h:5959
QualType getSelectedType() const
Definition: Type.h:5952
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:255
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
A (possibly-)qualified type.
Definition: Type.h:929
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8025
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7936
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8062
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7976
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:8139
QualType getCanonicalType() const
Definition: Type.h:7988
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8030
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:8057
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7982
Represents a template name as written in source code.
Definition: TemplateName.h:491
The collection of all-type qualifiers we support.
Definition: Type.h:324
unsigned getCVRQualifiers() const
Definition: Type.h:481
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:488
GC getObjCGCAttr() const
Definition: Type.h:512
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:347
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:343
void removeObjCLifetime()
Definition: Type.h:544
bool isStrictSupersetOf(Qualifiers Other) const
Determine whether this set of qualifiers is a strict superset of another set of qualifiers,...
Definition: Type.cpp:57
bool hasConst() const
Definition: Type.h:450
bool hasNonTrivialObjCLifetime() const
True if the lifetime is neither None or ExplicitNone.
Definition: Type.h:552
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:720
bool hasAddressSpace() const
Definition: Type.h:563
void removeObjCGCAttr()
Definition: Type.h:516
void removeAddressSpace()
Definition: Type.h:589
bool hasObjCGCAttr() const
Definition: Type.h:511
void setCVRQualifiers(unsigned mask)
Definition: Type.h:484
bool hasObjCLifetime() const
Definition: Type.h:537
ObjCLifetime getObjCLifetime() const
Definition: Type.h:538
Qualifiers withoutObjCLifetime() const
Definition: Type.h:526
LangAS getAddressSpace() const
Definition: Type.h:564
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:541
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3501
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6077
ArrayRef< TemplateArgument > getInjectedTemplateArgs(const ASTContext &Context) const
Retrieve the "injected" template arguments that correspond to the template parameters of this templat...
Definition: DeclTemplate.h:922
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
QualType getPointeeType() const
Definition: Type.h:3457
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:13200
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8048
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3010
A helper class for building up ExtParameterInfos.
Definition: Sema.h:12614
const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams)
Return a pointer (suitable for setting in an ExtProtoInfo) to the ExtParameterInfo array we've built ...
Definition: Sema.h:12633
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12086
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12116
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:464
bool CheckInstantiatedFunctionTemplateConstraints(SourceLocation PointOfInstantiation, FunctionDecl *Decl, ArrayRef< TemplateArgument > TemplateArgs, ConstraintSatisfaction &Satisfaction)
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12643
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
TemplateDeductionResult DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType, sema::TemplateDeductionInfo &Info)
Deduce the template arguments of the given template from FromType.
QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement)
Completely replace the auto in TypeWithAuto by Replacement.
SemaCUDA & CUDA()
Definition: Sema.h:1071
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc)
Looks for the std::initializer_list template and instantiates it with Element, or emits an error if i...
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition: Sema.h:6459
@ CTAK_DeducedFromArrayBound
The template argument was deduced from an array bound via template argument deduction.
Definition: Sema.h:11646
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:11638
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition: Sema.h:11642
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition: Sema.h:909
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
Definition: SemaType.cpp:2633
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
ASTContext & getASTContext() const
Definition: Sema.h:532
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:692
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:817
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition: Sema.h:11820
bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg)
Compare types for equality with respect to possibly compatible function types (noreturn adjustment,...
const LangOptions & getLangOpts() const
Definition: Sema.h:525
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition: Sema.h:14375
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false)
Returns the more specialized function template according to the rules of function template partial or...
std::optional< unsigned > getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs)
Determine the number of arguments in the given pack expansion type.
ExplicitSpecifier instantiateExplicitSpecifier(const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES)
TemplateDeductionResult SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< QualType > &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info)
Substitute the explicitly-provided template arguments into the given function template according to C...
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl * > Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl * > *OutParams, ExtParameterInfoBuilder &ParamInfos)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult)
Given an expression that refers to an overloaded function, try to resolve that function to a single f...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1044
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition: Sema.h:12149
QualType getDecltypeForExpr(Expr *E)
getDecltypeForExpr - Given an expr, will return the decltype for that expression, according to the ru...
Definition: SemaType.cpp:9631
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20971
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef< const Expr * > AC1, NamedDecl *D2, MutableArrayRef< const Expr * > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
TypeSourceInfo * ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:14945
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are used in a given expression.
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr, bool PartialOrderingTTP=false)
Check that the given template arguments can be provided to the given template, converting the argumen...
QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, CallingConv CC)
Get the return type to use for a lambda's conversion function(s) to function pointer type,...
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
Definition: SemaType.cpp:9094
TypeSourceInfo * SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init)
TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, SourceLocation Location)
Get a template argument mapping the given template parameter to itself, e.g.
bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD, SourceLocation Loc)
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
TemplateDeductionResult FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl< OriginalCallArg > const *OriginalCallArgs=nullptr, bool PartialOverloading=false, llvm::function_ref< bool()> CheckNonDependent=[] { return false;})
Finish template argument deduction for a function template, checking the deduced template arguments f...
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:564
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *AArg, const DefaultArguments &DefaultArgs, SourceLocation Loc, bool IsDeduced)
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
Definition: SemaType.cpp:8180
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition: Sema.h:12487
Encodes a location in the source.
A trivial tuple used to represent a source range.
bool isInvalid() const
SourceLocation getEnd() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:6469
TemplateArgument getArgumentPack() const
Definition: Type.cpp:4307
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
Definition: Type.h:6495
const TemplateTypeParmDecl * getReplacedParameter() const
Gets the template parameter declaration that was substituted for.
Definition: Type.cpp:4299
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
A template argument list.
Definition: DeclTemplate.h:250
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:286
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Definition: DeclTemplate.h:271
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
Represents a template argument.
Definition: TemplateBase.h:61
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:331
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
pack_iterator pack_end() const
Iterator referencing one past the last argument of a template argument pack.
Definition: TemplateBase.h:425
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:418
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
Used to insert TemplateArguments into FoldingSets.
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:363
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:337
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
Definition: TemplateBase.h:298
static TemplateArgument getEmptyPack()
Definition: TemplateBase.h:285
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:438
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:432
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
Definition: TemplateBase.h:350
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
bool isTypeAlias() const
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: DeclTemplate.h:443
void getAssociatedConstraints(llvm::SmallVectorImpl< const Expr * > &AC) const
Get the total constraint-expression associated with this template, including constraint-expressions d...
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:418
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
Definition: TemplateName.h:388
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:147
ArrayRef< TemplateArgument > getInjectedTemplateArgs(const ASTContext &Context)
Get the template argument list of the template parameter list.
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
ArrayRef< NamedDecl * > asArray()
Definition: DeclTemplate.h:142
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6666
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6734
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6732
QualType desugar() const
Definition: Type.h:6743
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
unsigned getDepth() const
Retrieve the depth of the template parameter.
Wrapper for template type parameters.
Definition: TypeLoc.h:758
unsigned getIndex() const
Definition: Type.h:6348
unsigned getDepth() const
Definition: Type.h:6347
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
const Type * getTypeForDecl() const
Definition: Decl.h:3409
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void reserve(size_t Requested)
Ensures that this buffer has at least as much capacity as described.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:159
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:164
void copy(TypeLoc other)
Copies the other type loc into this one.
Definition: TypeLoc.cpp:168
A container of type source information.
Definition: Type.h:7907
SourceLocation getNameLoc() const
Definition: TypeLoc.h:535
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
The base class of the type hierarchy.
Definition: Type.h:1828
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isVoidType() const
Definition: Type.h:8515
bool isIncompleteArrayType() const
Definition: Type.h:8271
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:8491
bool isRValueReferenceType() const
Definition: Type.h:8217
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8673
bool isArrayType() const
Definition: Type.h:8263
bool isFunctionPointerType() const
Definition: Type.h:8231
bool isPointerType() const
Definition: Type.h:8191
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8805
bool isReferenceType() const
Definition: Type.h:8209
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2811
bool isLValueReferenceType() const
Definition: Type.h:8213
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
QualType getCanonicalTypeInternal() const
Definition: Type.h:2989
bool isMemberPointerType() const
Definition: Type.h:8245
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:5048
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8649
bool isFunctionType() const
Definition: Type.h:8187
bool isObjCObjectPointerType() const
Definition: Type.h:8333
bool isMemberFunctionPointerType() const
Definition: Type.h:8249
bool isAnyPointerType() const
Definition: Type.h:8199
TypeClass getTypeClass() const
Definition: Type.h:2341
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2367
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8736
bool isRecordType() const
Definition: Type.h:8291
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
QualType getType() const
Definition: Decl.h:682
QualType getType() const
Definition: Value.cpp:234
Represents a variable declaration or definition.
Definition: Decl.h:882
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1522
Declaration of a variable template.
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the variable template specialization.
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
Represents a GCC generic vector type.
Definition: Type.h:4034
Provides information about an attempted template argument deduction, whose success or failure was des...
void setExplicitArgs(TemplateArgumentList *NewDeducedSugared, TemplateArgumentList *NewDeducedCanonical)
Provide an initial template argument list that contains the explicitly-specified arguments.
TemplateArgumentList * takeCanonical()
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
SourceLocation getLocation() const
Returns the location at which template argument is occurring.
void clearSFINAEDiagnostic()
Discard any SFINAE diagnostics.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
diag_iterator diag_end() const
Returns an iterator at the end of the sequence of suppressed diagnostics.
void reset(TemplateArgumentList *NewDeducedSugared, TemplateArgumentList *NewDeducedCanonical)
Provide a new template argument list that contains the results of template argument deduction.
unsigned getDeducedDepth() const
The depth of template parameters for which deduction is being performed.
diag_iterator diag_begin() const
Returns an iterator at the beginning of the sequence of suppressed diagnostics.
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
The JSON file list parser is used to communicate input to InstallAPI.
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
bool isTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:77
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1768
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1774
unsigned toTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:81
@ Result
The result type of a method or function.
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:61
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:65
std::optional< unsigned > getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition: ASTLambda.h:62
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
TPOC
The context in which partial ordering of function templates occurs.
Definition: Template.h:298
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition: Template.h:304
@ TPOC_Other
Partial ordering of function templates in other contexts, e.g., taking the address of a function temp...
Definition: Template.h:309
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition: Template.h:300
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1274
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:365
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Invalid
The declaration was invalid; do nothing.
@ Success
Template argument deduction was successful.
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ EST_Uninstantiated
not instantiated yet
@ EST_None
no exception specification
TemplateDeductionFlags
Various flags that control template argument deduction.
@ TDF_None
No template argument deduction flags, which indicates the strictest results for template argument ded...
@ TDF_DerivedClass
Within template argument deduction from a function call, we are matching in a case where we can perfo...
@ TDF_TopLevelParameterTypeList
Whether we are performing template argument deduction for parameters and arguments in a top-level tem...
@ TDF_IgnoreQualifiers
Within template argument deduction from a function call, we are matching in a case where we ignore cv...
@ TDF_ParamWithReferenceType
Within template argument deduction from a function call, we are matching with a parameter type for wh...
@ TDF_SkipNonDependent
Allow non-dependent types to differ, e.g., when performing template argument deduction from a functio...
@ TDF_AllowCompatibleFunctionType
Within template argument deduction from overload resolution per C++ [over.over] allow matching functi...
@ TDF_ArgWithReferenceType
Within template argument deduction for a conversion function, we are matching with an argument type f...
ActionResult< CXXBaseSpecifier * > BaseResult
Definition: Ownership.h:251
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
Definition: TemplateBase.h:691
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
Definition: TemplateBase.h:688
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:705
A pack that we're currently deducing.
SmallVector< DeducedTemplateArgument, 4 > New
DeducedTemplateArgument Saved
DeducedTemplateArgument DeferredDeduction
Holds information about the various types of exception specification.
Definition: Type.h:5164
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5166
Extra information about a function prototype.
Definition: Type.h:5192
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:5200
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5193
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition: Sema.h:12681
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:12688
A stack object to be created when performing template instantiation.
Definition: Sema.h:12845
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:12999
brief A function argument from which we performed template argument
Definition: Sema.h:12249
Location information for a TemplateArgument.
Definition: TemplateBase.h:472