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