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 if (auto *Expansion = dyn_cast<PackExpansionType>(NTTP->getType()))
861 ExtraDeductions.push_back(Expansion->getPattern());
862 }
863 // FIXME: Also collect the unexpanded packs in any type and template
864 // parameter packs that are pack expansions.
865 };
866
867 auto Collect = [&](TemplateArgument Pattern) {
869 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
870 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
871 unsigned Depth, Index;
872 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
873 if (Depth == Info.getDeducedDepth())
874 AddPack(Index);
875 }
876 };
877
878 // Look for unexpanded packs in the pattern.
879 Collect(Pattern);
880 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
881
882 unsigned NumNamedPacks = Packs.size();
883
884 // Also look for unexpanded packs that are indirectly deduced by deducing
885 // the sizes of the packs in this pattern.
886 while (!ExtraDeductions.empty())
887 Collect(ExtraDeductions.pop_back_val());
888
889 return NumNamedPacks;
890 }
891
892 void finishConstruction(unsigned NumNamedPacks) {
893 // Dig out the partially-substituted pack, if there is one.
894 const TemplateArgument *PartialPackArgs = nullptr;
895 unsigned NumPartialPackArgs = 0;
896 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
897 if (auto *Scope = S.CurrentInstantiationScope)
898 if (auto *Partial = Scope->getPartiallySubstitutedPack(
899 &PartialPackArgs, &NumPartialPackArgs))
900 PartialPackDepthIndex = getDepthAndIndex(Partial);
901
902 // This pack expansion will have been partially or fully expanded if
903 // it only names explicitly-specified parameter packs (including the
904 // partially-substituted one, if any).
905 bool IsExpanded = true;
906 for (unsigned I = 0; I != NumNamedPacks; ++I) {
907 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
908 IsExpanded = false;
909 IsPartiallyExpanded = false;
910 break;
911 }
912 if (PartialPackDepthIndex ==
913 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
914 IsPartiallyExpanded = true;
915 }
916 }
917
918 // Skip over the pack elements that were expanded into separate arguments.
919 // If we partially expanded, this is the number of partial arguments.
920 // FIXME: `&& FixedNumExpansions` is a workaround for UB described in
921 // https://github.com/llvm/llvm-project/issues/100095
922 if (IsPartiallyExpanded)
923 PackElements += NumPartialPackArgs;
924 else if (IsExpanded && FixedNumExpansions)
925 PackElements += *FixedNumExpansions;
926
927 for (auto &Pack : Packs) {
928 if (Info.PendingDeducedPacks.size() > Pack.Index)
929 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
930 else
931 Info.PendingDeducedPacks.resize(Pack.Index + 1);
932 Info.PendingDeducedPacks[Pack.Index] = &Pack;
933
934 if (PartialPackDepthIndex ==
935 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
936 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
937 // We pre-populate the deduced value of the partially-substituted
938 // pack with the specified value. This is not entirely correct: the
939 // value is supposed to have been substituted, not deduced, but the
940 // cases where this is observable require an exact type match anyway.
941 //
942 // FIXME: If we could represent a "depth i, index j, pack elem k"
943 // parameter, we could substitute the partially-substituted pack
944 // everywhere and avoid this.
945 if (!FinishingDeduction && !IsPartiallyExpanded)
946 Deduced[Pack.Index] = Pack.New[PackElements];
947 }
948 }
949 }
950
951public:
952 ~PackDeductionScope() {
953 for (auto &Pack : Packs)
954 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
955 }
956
957 // Return the size of the saved packs if all of them has the same size.
958 std::optional<unsigned> getSavedPackSizeIfAllEqual() const {
959 unsigned PackSize = Packs[0].Saved.pack_size();
960
961 if (std::all_of(Packs.begin() + 1, Packs.end(), [&PackSize](const auto &P) {
962 return P.Saved.pack_size() == PackSize;
963 }))
964 return PackSize;
965 return {};
966 }
967
968 /// Determine whether this pack has already been deduced from a previous
969 /// argument.
970 bool isDeducedFromEarlierParameter() const {
971 return DeducedFromEarlierParameter;
972 }
973
974 /// Determine whether this pack has already been partially expanded into a
975 /// sequence of (prior) function parameters / template arguments.
976 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
977
978 /// Determine whether this pack expansion scope has a known, fixed arity.
979 /// This happens if it involves a pack from an outer template that has
980 /// (notionally) already been expanded.
981 bool hasFixedArity() { return FixedNumExpansions.has_value(); }
982
983 /// Determine whether the next element of the argument is still part of this
984 /// pack. This is the case unless the pack is already expanded to a fixed
985 /// length.
986 bool hasNextElement() {
987 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
988 }
989
990 /// Move to deducing the next element in each pack that is being deduced.
991 void nextPackElement() {
992 // Capture the deduced template arguments for each parameter pack expanded
993 // by this pack expansion, add them to the list of arguments we've deduced
994 // for that pack, then clear out the deduced argument.
995 if (!FinishingDeduction) {
996 for (auto &Pack : Packs) {
997 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
998 if (!Pack.New.empty() || !DeducedArg.isNull()) {
999 while (Pack.New.size() < PackElements)
1000 Pack.New.push_back(DeducedTemplateArgument());
1001 if (Pack.New.size() == PackElements)
1002 Pack.New.push_back(DeducedArg);
1003 else
1004 Pack.New[PackElements] = DeducedArg;
1005 DeducedArg = Pack.New.size() > PackElements + 1
1006 ? Pack.New[PackElements + 1]
1008 }
1009 }
1010 }
1011 ++PackElements;
1012 }
1013
1014 /// Finish template argument deduction for a set of argument packs,
1015 /// producing the argument packs and checking for consistency with prior
1016 /// deductions.
1017 TemplateDeductionResult finish() {
1018 if (FinishingDeduction)
1019 return TemplateDeductionResult::Success;
1020 // Build argument packs for each of the parameter packs expanded by this
1021 // pack expansion.
1022 for (auto &Pack : Packs) {
1023 // Put back the old value for this pack.
1024 if (!FinishingDeduction)
1025 Deduced[Pack.Index] = Pack.Saved;
1026
1027 // Always make sure the size of this pack is correct, even if we didn't
1028 // deduce any values for it.
1029 //
1030 // FIXME: This isn't required by the normative wording, but substitution
1031 // and post-substitution checking will always fail if the arity of any
1032 // pack is not equal to the number of elements we processed. (Either that
1033 // or something else has gone *very* wrong.) We're permitted to skip any
1034 // hard errors from those follow-on steps by the intent (but not the
1035 // wording) of C++ [temp.inst]p8:
1036 //
1037 // If the function selected by overload resolution can be determined
1038 // without instantiating a class template definition, it is unspecified
1039 // whether that instantiation actually takes place
1040 Pack.New.resize(PackElements);
1041
1042 // Build or find a new value for this pack.
1044 if (Pack.New.empty()) {
1045 // If we deduced an empty argument pack, create it now.
1047 } else {
1048 TemplateArgument *ArgumentPack =
1049 new (S.Context) TemplateArgument[Pack.New.size()];
1050 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
1051 NewPack = DeducedTemplateArgument(
1052 TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())),
1053 // FIXME: This is wrong, it's possible that some pack elements are
1054 // deduced from an array bound and others are not:
1055 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
1056 // g({1, 2, 3}, {{}, {}});
1057 // ... should deduce T = {int, size_t (from array bound)}.
1058 Pack.New[0].wasDeducedFromArrayBound());
1059 }
1060
1061 // Pick where we're going to put the merged pack.
1063 if (Pack.Outer) {
1064 if (Pack.Outer->DeferredDeduction.isNull()) {
1065 // Defer checking this pack until we have a complete pack to compare
1066 // it against.
1067 Pack.Outer->DeferredDeduction = NewPack;
1068 continue;
1069 }
1070 Loc = &Pack.Outer->DeferredDeduction;
1071 } else {
1072 Loc = &Deduced[Pack.Index];
1073 }
1074
1075 // Check the new pack matches any previous value.
1076 DeducedTemplateArgument OldPack = *Loc;
1078 S.Context, OldPack, NewPack, DeducePackIfNotAlreadyDeduced);
1079
1080 Info.AggregateDeductionCandidateHasMismatchedArity =
1081 OldPack.getKind() == TemplateArgument::Pack &&
1082 NewPack.getKind() == TemplateArgument::Pack &&
1083 OldPack.pack_size() != NewPack.pack_size() && !Result.isNull();
1084
1085 // If we deferred a deduction of this pack, check that one now too.
1086 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
1087 OldPack = Result;
1088 NewPack = Pack.DeferredDeduction;
1089 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
1090 }
1091
1092 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
1093 if (Result.isNull()) {
1094 Info.Param = makeTemplateParameter(Param);
1095 Info.FirstArg = OldPack;
1096 Info.SecondArg = NewPack;
1097 return TemplateDeductionResult::Inconsistent;
1098 }
1099
1100 // If we have a pre-expanded pack and we didn't deduce enough elements
1101 // for it, fail deduction.
1102 if (std::optional<unsigned> Expansions = getExpandedPackSize(Param)) {
1103 if (*Expansions != PackElements) {
1104 Info.Param = makeTemplateParameter(Param);
1105 Info.FirstArg = Result;
1106 return TemplateDeductionResult::IncompletePack;
1107 }
1108 }
1109
1110 *Loc = Result;
1111 }
1112
1113 return TemplateDeductionResult::Success;
1114 }
1115
1116private:
1117 Sema &S;
1118 TemplateParameterList *TemplateParams;
1121 unsigned PackElements = 0;
1122 bool IsPartiallyExpanded = false;
1123 bool DeducePackIfNotAlreadyDeduced = false;
1124 bool DeducedFromEarlierParameter = false;
1125 bool FinishingDeduction = false;
1126 /// The number of expansions, if we have a fully-expanded pack in this scope.
1127 std::optional<unsigned> FixedNumExpansions;
1128
1130};
1131
1132} // namespace
1133
1134template <class T>
1136 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1139 bool FinishingDeduction, T &&DeductFunc) {
1140 // C++0x [temp.deduct.type]p10:
1141 // Similarly, if P has a form that contains (T), then each parameter type
1142 // Pi of the respective parameter-type- list of P is compared with the
1143 // corresponding parameter type Ai of the corresponding parameter-type-list
1144 // of A. [...]
1145 unsigned ArgIdx = 0, ParamIdx = 0;
1146 for (; ParamIdx != Params.size(); ++ParamIdx) {
1147 // Check argument types.
1148 const PackExpansionType *Expansion
1149 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1150 if (!Expansion) {
1151 // Simple case: compare the parameter and argument types at this point.
1152
1153 // Make sure we have an argument.
1154 if (ArgIdx >= Args.size())
1155 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1156
1157 if (isa<PackExpansionType>(Args[ArgIdx])) {
1158 // C++0x [temp.deduct.type]p22:
1159 // If the original function parameter associated with A is a function
1160 // parameter pack and the function parameter associated with P is not
1161 // a function parameter pack, then template argument deduction fails.
1162 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1163 }
1164
1165 if (TemplateDeductionResult Result =
1166 DeductFunc(S, TemplateParams, ParamIdx, ArgIdx,
1167 Params[ParamIdx].getUnqualifiedType(),
1168 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, POK);
1169 Result != TemplateDeductionResult::Success)
1170 return Result;
1171
1172 ++ArgIdx;
1173 continue;
1174 }
1175
1176 // C++0x [temp.deduct.type]p10:
1177 // If the parameter-declaration corresponding to Pi is a function
1178 // parameter pack, then the type of its declarator- id is compared with
1179 // each remaining parameter type in the parameter-type-list of A. Each
1180 // comparison deduces template arguments for subsequent positions in the
1181 // template parameter packs expanded by the function parameter pack.
1182
1183 QualType Pattern = Expansion->getPattern();
1184 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern,
1185 /*DeducePackIfNotAlreadyDeduced=*/false,
1186 FinishingDeduction);
1187
1188 // A pack scope with fixed arity is not really a pack any more, so is not
1189 // a non-deduced context.
1190 if (ParamIdx + 1 == Params.size() || PackScope.hasFixedArity()) {
1191 for (; ArgIdx < Args.size() && PackScope.hasNextElement(); ++ArgIdx) {
1192 // Deduce template arguments from the pattern.
1193 if (TemplateDeductionResult Result = DeductFunc(
1194 S, TemplateParams, ParamIdx, ArgIdx,
1195 Pattern.getUnqualifiedType(), Args[ArgIdx].getUnqualifiedType(),
1196 Info, Deduced, POK);
1197 Result != TemplateDeductionResult::Success)
1198 return Result;
1199 PackScope.nextPackElement();
1200 }
1201 } else {
1202 // C++0x [temp.deduct.type]p5:
1203 // The non-deduced contexts are:
1204 // - A function parameter pack that does not occur at the end of the
1205 // parameter-declaration-clause.
1206 //
1207 // FIXME: There is no wording to say what we should do in this case. We
1208 // choose to resolve this by applying the same rule that is applied for a
1209 // function call: that is, deduce all contained packs to their
1210 // explicitly-specified values (or to <> if there is no such value).
1211 //
1212 // This is seemingly-arbitrarily different from the case of a template-id
1213 // with a non-trailing pack-expansion in its arguments, which renders the
1214 // entire template-argument-list a non-deduced context.
1215
1216 // If the parameter type contains an explicitly-specified pack that we
1217 // could not expand, skip the number of parameters notionally created
1218 // by the expansion.
1219 std::optional<unsigned> NumExpansions = Expansion->getNumExpansions();
1220 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1221 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
1222 ++I, ++ArgIdx)
1223 PackScope.nextPackElement();
1224 }
1225 }
1226
1227 // Build argument packs for each of the parameter packs expanded by this
1228 // pack expansion.
1229 if (auto Result = PackScope.finish();
1230 Result != TemplateDeductionResult::Success)
1231 return Result;
1232 }
1233
1234 // DR692, DR1395
1235 // C++0x [temp.deduct.type]p10:
1236 // If the parameter-declaration corresponding to P_i ...
1237 // During partial ordering, if Ai was originally a function parameter pack:
1238 // - if P does not contain a function parameter type corresponding to Ai then
1239 // Ai is ignored;
1240 if (POK == PartialOrderingKind::Call && ArgIdx + 1 == Args.size() &&
1241 isa<PackExpansionType>(Args[ArgIdx]))
1242 return TemplateDeductionResult::Success;
1243
1244 // Make sure we don't have any extra arguments.
1245 if (ArgIdx < Args.size())
1246 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1247
1248 return TemplateDeductionResult::Success;
1249}
1250
1251/// Deduce the template arguments by comparing the list of parameter
1252/// types to the list of argument types, as in the parameter-type-lists of
1253/// function types (C++ [temp.deduct.type]p10).
1254///
1255/// \param S The semantic analysis object within which we are deducing
1256///
1257/// \param TemplateParams The template parameters that we are deducing
1258///
1259/// \param Params The list of parameter types
1260///
1261/// \param Args The list of argument types
1262///
1263/// \param Info information about the template argument deduction itself
1264///
1265/// \param Deduced the deduced template arguments
1266///
1267/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1268/// how template argument deduction is performed.
1269///
1270/// \param PartialOrdering If true, we are performing template argument
1271/// deduction for during partial ordering for a call
1272/// (C++0x [temp.deduct.partial]).
1273///
1274/// \param HasDeducedAnyParam If set, the object pointed at will indicate
1275/// whether any template parameter was deduced.
1276///
1277/// \param HasDeducedParam If set, the bit vector will be used to represent
1278/// which template parameters were deduced, in order.
1279///
1280/// \returns the result of template argument deduction so far. Note that a
1281/// "success" result means that template argument deduction has not yet failed,
1282/// but it may still fail, later, for other reasons.
1284 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1286 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1287 PartialOrderingKind POK, bool *HasDeducedAnyParam,
1288 llvm::SmallBitVector *HasDeducedParam) {
1289 return ::DeduceForEachType(
1290 S, TemplateParams, Params, Args, Info, Deduced, POK,
1291 /*FinishingDeduction=*/false,
1292 [&](Sema &S, TemplateParameterList *TemplateParams, int ParamIdx,
1293 int ArgIdx, QualType P, QualType A, TemplateDeductionInfo &Info,
1295 PartialOrderingKind POK) {
1296 bool HasDeducedAnyParamCopy = false;
1298 S, TemplateParams, P, A, Info, Deduced, TDF, POK,
1299 /*DeducedFromArrayBound=*/false, &HasDeducedAnyParamCopy);
1300 if (HasDeducedAnyParam && HasDeducedAnyParamCopy)
1301 *HasDeducedAnyParam = true;
1302 if (HasDeducedParam && HasDeducedAnyParamCopy)
1303 (*HasDeducedParam)[ParamIdx] = true;
1304 return TDR;
1305 });
1306}
1307
1308/// Determine whether the parameter has qualifiers that the argument
1309/// lacks. Put another way, determine whether there is no way to add
1310/// a deduced set of qualifiers to the ParamType that would result in
1311/// its qualifiers matching those of the ArgType.
1313 QualType ArgType) {
1314 Qualifiers ParamQs = ParamType.getQualifiers();
1315 Qualifiers ArgQs = ArgType.getQualifiers();
1316
1317 if (ParamQs == ArgQs)
1318 return false;
1319
1320 // Mismatched (but not missing) Objective-C GC attributes.
1321 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1322 ParamQs.hasObjCGCAttr())
1323 return true;
1324
1325 // Mismatched (but not missing) address spaces.
1326 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1327 ParamQs.hasAddressSpace())
1328 return true;
1329
1330 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1331 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1332 ParamQs.hasObjCLifetime())
1333 return true;
1334
1335 // CVR qualifiers inconsistent or a superset.
1336 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1337}
1338
1340 const FunctionType *PF = P->getAs<FunctionType>(),
1341 *AF = A->getAs<FunctionType>();
1342
1343 // Just compare if not functions.
1344 if (!PF || !AF)
1345 return Context.hasSameType(P, A);
1346
1347 // Noreturn and noexcept adjustment.
1348 if (QualType AdjustedParam; IsFunctionConversion(P, A, AdjustedParam))
1349 P = AdjustedParam;
1350
1351 // FIXME: Compatible calling conventions.
1353}
1354
1355/// Get the index of the first template parameter that was originally from the
1356/// innermost template-parameter-list. This is 0 except when we concatenate
1357/// the template parameter lists of a class template and a constructor template
1358/// when forming an implicit deduction guide.
1360 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1361 if (!Guide || !Guide->isImplicit())
1362 return 0;
1363 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1364}
1365
1366/// Determine whether a type denotes a forwarding reference.
1367static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1368 // C++1z [temp.deduct.call]p3:
1369 // A forwarding reference is an rvalue reference to a cv-unqualified
1370 // template parameter that does not represent a template parameter of a
1371 // class template.
1372 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1373 if (ParamRef->getPointeeType().getQualifiers())
1374 return false;
1375 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1376 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1377 }
1378 return false;
1379}
1380
1381/// Attempt to deduce the template arguments by checking the base types
1382/// according to (C++20 [temp.deduct.call] p4b3.
1383///
1384/// \param S the semantic analysis object within which we are deducing.
1385///
1386/// \param RD the top level record object we are deducing against.
1387///
1388/// \param TemplateParams the template parameters that we are deducing.
1389///
1390/// \param P the template specialization parameter type.
1391///
1392/// \param Info information about the template argument deduction itself.
1393///
1394/// \param Deduced the deduced template arguments.
1395///
1396/// \returns the result of template argument deduction with the bases. "invalid"
1397/// means no matches, "success" found a single item, and the
1398/// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
1401 TemplateParameterList *TemplateParams, QualType P,
1404 bool *HasDeducedAnyParam) {
1405 // C++14 [temp.deduct.call] p4b3:
1406 // If P is a class and P has the form simple-template-id, then the
1407 // transformed A can be a derived class of the deduced A. Likewise if
1408 // P is a pointer to a class of the form simple-template-id, the
1409 // transformed A can be a pointer to a derived class pointed to by the
1410 // deduced A. However, if there is a class C that is a (direct or
1411 // indirect) base class of D and derived (directly or indirectly) from a
1412 // class B and that would be a valid deduced A, the deduced A cannot be
1413 // B or pointer to B, respectively.
1414 //
1415 // These alternatives are considered only if type deduction would
1416 // otherwise fail. If they yield more than one possible deduced A, the
1417 // type deduction fails.
1418
1419 // Use a breadth-first search through the bases to collect the set of
1420 // successful matches. Visited contains the set of nodes we have already
1421 // visited, while ToVisit is our stack of records that we still need to
1422 // visit. Matches contains a list of matches that have yet to be
1423 // disqualified.
1426 // We iterate over this later, so we have to use MapVector to ensure
1427 // determinism.
1428 struct MatchValue {
1430 bool HasDeducedAnyParam;
1431 };
1432 llvm::MapVector<const CXXRecordDecl *, MatchValue> Matches;
1433
1434 auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
1435 for (const auto &Base : RD->bases()) {
1436 QualType T = Base.getType();
1437 assert(T->isRecordType() && "Base class that isn't a record?");
1438 if (Visited.insert(T->getAsCXXRecordDecl()).second)
1439 ToVisit.push_back(T);
1440 }
1441 };
1442
1443 // Set up the loop by adding all the bases.
1444 AddBases(RD);
1445
1446 // Search each path of bases until we either run into a successful match
1447 // (where all bases of it are invalid), or we run out of bases.
1448 while (!ToVisit.empty()) {
1449 QualType NextT = ToVisit.pop_back_val();
1450
1451 SmallVector<DeducedTemplateArgument, 8> DeducedCopy(Deduced.begin(),
1452 Deduced.end());
1454 bool HasDeducedAnyParamCopy = false;
1456 S, TemplateParams, P, NextT, BaseInfo, PartialOrdering, DeducedCopy,
1457 &HasDeducedAnyParamCopy);
1458
1459 // If this was a successful deduction, add it to the list of matches,
1460 // otherwise we need to continue searching its bases.
1461 const CXXRecordDecl *RD = NextT->getAsCXXRecordDecl();
1463 Matches.insert({RD, {DeducedCopy, HasDeducedAnyParamCopy}});
1464 else
1465 AddBases(RD);
1466 }
1467
1468 // At this point, 'Matches' contains a list of seemingly valid bases, however
1469 // in the event that we have more than 1 match, it is possible that the base
1470 // of one of the matches might be disqualified for being a base of another
1471 // valid match. We can count on cyclical instantiations being invalid to
1472 // simplify the disqualifications. That is, if A & B are both matches, and B
1473 // inherits from A (disqualifying A), we know that A cannot inherit from B.
1474 if (Matches.size() > 1) {
1475 Visited.clear();
1476 for (const auto &Match : Matches)
1477 AddBases(Match.first);
1478
1479 // We can give up once we have a single item (or have run out of things to
1480 // search) since cyclical inheritance isn't valid.
1481 while (Matches.size() > 1 && !ToVisit.empty()) {
1482 const CXXRecordDecl *RD = ToVisit.pop_back_val()->getAsCXXRecordDecl();
1483 Matches.erase(RD);
1484
1485 // Always add all bases, since the inheritance tree can contain
1486 // disqualifications for multiple matches.
1487 AddBases(RD);
1488 }
1489 }
1490
1491 if (Matches.empty())
1493 if (Matches.size() > 1)
1495
1496 std::swap(Matches.front().second.Deduced, Deduced);
1497 if (bool HasDeducedAnyParamCopy = Matches.front().second.HasDeducedAnyParam;
1498 HasDeducedAnyParamCopy && HasDeducedAnyParam)
1499 *HasDeducedAnyParam = HasDeducedAnyParamCopy;
1501}
1502
1503/// When propagating a partial ordering kind into a NonCall context,
1504/// this is used to downgrade a 'Call' into a 'NonCall', so that
1505/// the kind still reflects whether we are in a partial ordering context.
1508 return std::min(POK, PartialOrderingKind::NonCall);
1509}
1510
1511/// Deduce the template arguments by comparing the parameter type and
1512/// the argument type (C++ [temp.deduct.type]).
1513///
1514/// \param S the semantic analysis object within which we are deducing
1515///
1516/// \param TemplateParams the template parameters that we are deducing
1517///
1518/// \param P the parameter type
1519///
1520/// \param A the argument type
1521///
1522/// \param Info information about the template argument deduction itself
1523///
1524/// \param Deduced the deduced template arguments
1525///
1526/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1527/// how template argument deduction is performed.
1528///
1529/// \param PartialOrdering Whether we're performing template argument deduction
1530/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1531///
1532/// \returns the result of template argument deduction so far. Note that a
1533/// "success" result means that template argument deduction has not yet failed,
1534/// but it may still fail, later, for other reasons.
1536 Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
1538 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1539 PartialOrderingKind POK, bool DeducedFromArrayBound,
1540 bool *HasDeducedAnyParam) {
1541
1542 // If the argument type is a pack expansion, look at its pattern.
1543 // This isn't explicitly called out
1544 if (const auto *AExp = dyn_cast<PackExpansionType>(A))
1545 A = AExp->getPattern();
1546 assert(!isa<PackExpansionType>(A.getCanonicalType()));
1547
1548 if (POK == PartialOrderingKind::Call) {
1549 // C++11 [temp.deduct.partial]p5:
1550 // Before the partial ordering is done, certain transformations are
1551 // performed on the types used for partial ordering:
1552 // - If P is a reference type, P is replaced by the type referred to.
1553 const ReferenceType *PRef = P->getAs<ReferenceType>();
1554 if (PRef)
1555 P = PRef->getPointeeType();
1556
1557 // - If A is a reference type, A is replaced by the type referred to.
1558 const ReferenceType *ARef = A->getAs<ReferenceType>();
1559 if (ARef)
1560 A = A->getPointeeType();
1561
1562 if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
1563 // C++11 [temp.deduct.partial]p9:
1564 // If, for a given type, deduction succeeds in both directions (i.e.,
1565 // the types are identical after the transformations above) and both
1566 // P and A were reference types [...]:
1567 // - if [one type] was an lvalue reference and [the other type] was
1568 // not, [the other type] is not considered to be at least as
1569 // specialized as [the first type]
1570 // - if [one type] is more cv-qualified than [the other type],
1571 // [the other type] is not considered to be at least as specialized
1572 // as [the first type]
1573 // Objective-C ARC adds:
1574 // - [one type] has non-trivial lifetime, [the other type] has
1575 // __unsafe_unretained lifetime, and the types are otherwise
1576 // identical
1577 //
1578 // A is "considered to be at least as specialized" as P iff deduction
1579 // succeeds, so we model this as a deduction failure. Note that
1580 // [the first type] is P and [the other type] is A here; the standard
1581 // gets this backwards.
1582 Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
1583 if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
1584 PQuals.isStrictSupersetOf(AQuals) ||
1585 (PQuals.hasNonTrivialObjCLifetime() &&
1586 AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1587 PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
1588 Info.FirstArg = TemplateArgument(P);
1589 Info.SecondArg = TemplateArgument(A);
1591 }
1592 }
1593 Qualifiers DiscardedQuals;
1594 // C++11 [temp.deduct.partial]p7:
1595 // Remove any top-level cv-qualifiers:
1596 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1597 // version of P.
1598 P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
1599 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1600 // version of A.
1601 A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
1602 } else {
1603 // C++0x [temp.deduct.call]p4 bullet 1:
1604 // - If the original P is a reference type, the deduced A (i.e., the type
1605 // referred to by the reference) can be more cv-qualified than the
1606 // transformed A.
1607 if (TDF & TDF_ParamWithReferenceType) {
1608 Qualifiers Quals;
1609 QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
1611 P = S.Context.getQualifiedType(UnqualP, Quals);
1612 }
1613
1614 if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
1615 // C++0x [temp.deduct.type]p10:
1616 // If P and A are function types that originated from deduction when
1617 // taking the address of a function template (14.8.2.2) or when deducing
1618 // template arguments from a function declaration (14.8.2.6) and Pi and
1619 // Ai are parameters of the top-level parameter-type-list of P and A,
1620 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1621 // is an lvalue reference, in
1622 // which case the type of Pi is changed to be the template parameter
1623 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1624 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1625 // deduced as X&. - end note ]
1626 TDF &= ~TDF_TopLevelParameterTypeList;
1627 if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
1629 P = P->getPointeeType();
1630 }
1631 }
1632
1633 // C++ [temp.deduct.type]p9:
1634 // A template type argument T, a template template argument TT or a
1635 // template non-type argument i can be deduced if P and A have one of
1636 // the following forms:
1637 //
1638 // T
1639 // cv-list T
1640 if (const auto *TTP = P->getAs<TemplateTypeParmType>()) {
1641 // Just skip any attempts to deduce from a placeholder type or a parameter
1642 // at a different depth.
1643 if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
1645
1646 unsigned Index = TTP->getIndex();
1647
1648 // If the argument type is an array type, move the qualifiers up to the
1649 // top level, so they can be matched with the qualifiers on the parameter.
1650 if (A->isArrayType()) {
1651 Qualifiers Quals;
1652 A = S.Context.getUnqualifiedArrayType(A, Quals);
1653 if (Quals)
1654 A = S.Context.getQualifiedType(A, Quals);
1655 }
1656
1657 // The argument type can not be less qualified than the parameter
1658 // type.
1659 if (!(TDF & TDF_IgnoreQualifiers) &&
1661 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1662 Info.FirstArg = TemplateArgument(P);
1663 Info.SecondArg = TemplateArgument(A);
1665 }
1666
1667 // Do not match a function type with a cv-qualified type.
1668 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1669 if (A->isFunctionType() && P.hasQualifiers())
1671
1672 assert(TTP->getDepth() == Info.getDeducedDepth() &&
1673 "saw template type parameter with wrong depth");
1674 assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&
1675 "Unresolved overloaded function");
1677
1678 // Remove any qualifiers on the parameter from the deduced type.
1679 // We checked the qualifiers for consistency above.
1680 Qualifiers DeducedQs = DeducedType.getQualifiers();
1681 Qualifiers ParamQs = P.getQualifiers();
1682 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1683 if (ParamQs.hasObjCGCAttr())
1684 DeducedQs.removeObjCGCAttr();
1685 if (ParamQs.hasAddressSpace())
1686 DeducedQs.removeAddressSpace();
1687 if (ParamQs.hasObjCLifetime())
1688 DeducedQs.removeObjCLifetime();
1689
1690 // Objective-C ARC:
1691 // If template deduction would produce a lifetime qualifier on a type
1692 // that is not a lifetime type, template argument deduction fails.
1693 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1695 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1696 Info.FirstArg = TemplateArgument(P);
1697 Info.SecondArg = TemplateArgument(A);
1699 }
1700
1701 // Objective-C ARC:
1702 // If template deduction would produce an argument type with lifetime type
1703 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1704 if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
1705 !DeducedQs.hasObjCLifetime())
1707
1708 DeducedType =
1709 S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
1710
1711 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1713 checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
1714 if (Result.isNull()) {
1715 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1716 Info.FirstArg = Deduced[Index];
1717 Info.SecondArg = NewDeduced;
1719 }
1720
1721 Deduced[Index] = Result;
1722 if (HasDeducedAnyParam)
1723 *HasDeducedAnyParam = true;
1725 }
1726
1727 // Set up the template argument deduction information for a failure.
1728 Info.FirstArg = TemplateArgument(P);
1729 Info.SecondArg = TemplateArgument(A);
1730
1731 // If the parameter is an already-substituted template parameter
1732 // pack, do nothing: we don't know which of its arguments to look
1733 // at, so we have to wait until all of the parameter packs in this
1734 // expansion have arguments.
1735 if (P->getAs<SubstTemplateTypeParmPackType>())
1737
1738 // Check the cv-qualifiers on the parameter and argument types.
1739 if (!(TDF & TDF_IgnoreQualifiers)) {
1740 if (TDF & TDF_ParamWithReferenceType) {
1743 } else if (TDF & TDF_ArgWithReferenceType) {
1744 // C++ [temp.deduct.conv]p4:
1745 // If the original A is a reference type, A can be more cv-qualified
1746 // than the deduced A
1747 if (!A.getQualifiers().compatiblyIncludes(P.getQualifiers(),
1748 S.getASTContext()))
1750
1751 // Strip out all extra qualifiers from the argument to figure out the
1752 // type we're converting to, prior to the qualification conversion.
1753 Qualifiers Quals;
1754 A = S.Context.getUnqualifiedArrayType(A, Quals);
1755 A = S.Context.getQualifiedType(A, P.getQualifiers());
1756 } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
1757 if (P.getCVRQualifiers() != A.getCVRQualifiers())
1759 }
1760 }
1761
1762 // If the parameter type is not dependent, there is nothing to deduce.
1763 if (!P->isDependentType()) {
1764 if (TDF & TDF_SkipNonDependent)
1767 : S.Context.hasSameType(P, A))
1772 if (!(TDF & TDF_IgnoreQualifiers))
1774 // Otherwise, when ignoring qualifiers, the types not having the same
1775 // unqualified type does not mean they do not match, so in this case we
1776 // must keep going and analyze with a non-dependent parameter type.
1777 }
1778
1779 switch (P.getCanonicalType()->getTypeClass()) {
1780 // Non-canonical types cannot appear here.
1781#define NON_CANONICAL_TYPE(Class, Base) \
1782 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1783#define TYPE(Class, Base)
1784#include "clang/AST/TypeNodes.inc"
1785
1786 case Type::TemplateTypeParm:
1787 case Type::SubstTemplateTypeParmPack:
1788 llvm_unreachable("Type nodes handled above");
1789
1790 case Type::Auto:
1791 // C++23 [temp.deduct.funcaddr]/3:
1792 // A placeholder type in the return type of a function template is a
1793 // non-deduced context.
1794 // There's no corresponding wording for [temp.deduct.decl], but we treat
1795 // it the same to match other compilers.
1796 if (P->isDependentType())
1798 [[fallthrough]];
1799 case Type::Builtin:
1800 case Type::VariableArray:
1801 case Type::Vector:
1802 case Type::FunctionNoProto:
1803 case Type::Record:
1804 case Type::Enum:
1805 case Type::ObjCObject:
1806 case Type::ObjCInterface:
1807 case Type::ObjCObjectPointer:
1808 case Type::BitInt:
1809 return (TDF & TDF_SkipNonDependent) ||
1810 ((TDF & TDF_IgnoreQualifiers)
1812 : S.Context.hasSameType(P, A))
1815
1816 // _Complex T [placeholder extension]
1817 case Type::Complex: {
1818 const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
1819 if (!CA)
1822 S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
1823 Deduced, TDF, degradeCallPartialOrderingKind(POK),
1824 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1825 }
1826
1827 // _Atomic T [extension]
1828 case Type::Atomic: {
1829 const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
1830 if (!AA)
1833 S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
1834 Deduced, TDF, degradeCallPartialOrderingKind(POK),
1835 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1836 }
1837
1838 // T *
1839 case Type::Pointer: {
1840 QualType PointeeType;
1841 if (const auto *PA = A->getAs<PointerType>()) {
1842 PointeeType = PA->getPointeeType();
1843 } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
1844 PointeeType = PA->getPointeeType();
1845 } else {
1847 }
1849 S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
1850 PointeeType, Info, Deduced,
1853 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1854 }
1855
1856 // T &
1857 case Type::LValueReference: {
1858 const auto *RP = P->castAs<LValueReferenceType>(),
1859 *RA = A->getAs<LValueReferenceType>();
1860 if (!RA)
1862
1864 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1865 Deduced, 0, degradeCallPartialOrderingKind(POK),
1866 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1867 }
1868
1869 // T && [C++0x]
1870 case Type::RValueReference: {
1871 const auto *RP = P->castAs<RValueReferenceType>(),
1872 *RA = A->getAs<RValueReferenceType>();
1873 if (!RA)
1875
1877 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1878 Deduced, 0, degradeCallPartialOrderingKind(POK),
1879 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1880 }
1881
1882 // T [] (implied, but not stated explicitly)
1883 case Type::IncompleteArray: {
1884 const auto *IAA = S.Context.getAsIncompleteArrayType(A);
1885 if (!IAA)
1887
1888 const auto *IAP = S.Context.getAsIncompleteArrayType(P);
1889 assert(IAP && "Template parameter not of incomplete array type");
1890
1892 S, TemplateParams, IAP->getElementType(), IAA->getElementType(), Info,
1893 Deduced, TDF & TDF_IgnoreQualifiers,
1895 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1896 }
1897
1898 // T [integer-constant]
1899 case Type::ConstantArray: {
1900 const auto *CAA = S.Context.getAsConstantArrayType(A),
1902 assert(CAP);
1903 if (!CAA || CAA->getSize() != CAP->getSize())
1905
1907 S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
1908 Deduced, TDF & TDF_IgnoreQualifiers,
1910 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1911 }
1912
1913 // type [i]
1914 case Type::DependentSizedArray: {
1915 const auto *AA = S.Context.getAsArrayType(A);
1916 if (!AA)
1918
1919 // Check the element type of the arrays
1920 const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
1921 assert(DAP);
1923 S, TemplateParams, DAP->getElementType(), AA->getElementType(),
1924 Info, Deduced, TDF & TDF_IgnoreQualifiers,
1926 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1928 return Result;
1929
1930 // Determine the array bound is something we can deduce.
1931 const NonTypeTemplateParmDecl *NTTP =
1932 getDeducedParameterFromExpr(Info, DAP->getSizeExpr());
1933 if (!NTTP)
1935
1936 // We can perform template argument deduction for the given non-type
1937 // template parameter.
1938 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1939 "saw non-type template parameter with wrong depth");
1940 if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
1941 llvm::APSInt Size(CAA->getSize());
1943 S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
1944 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
1945 Deduced, HasDeducedAnyParam);
1946 }
1947 if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
1948 if (DAA->getSizeExpr())
1950 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info,
1951 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
1952
1953 // Incomplete type does not match a dependently-sized array type
1955 }
1956
1957 // type(*)(T)
1958 // T(*)()
1959 // T(*)(T)
1960 case Type::FunctionProto: {
1961 const auto *FPP = P->castAs<FunctionProtoType>(),
1962 *FPA = A->getAs<FunctionProtoType>();
1963 if (!FPA)
1965
1966 if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
1967 FPP->getRefQualifier() != FPA->getRefQualifier() ||
1968 FPP->isVariadic() != FPA->isVariadic())
1970
1971 // Check return types.
1973 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
1974 Info, Deduced, 0, degradeCallPartialOrderingKind(POK),
1975 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1977 return Result;
1978
1979 // Check parameter types.
1981 S, TemplateParams, FPP->param_types(), FPA->param_types(), Info,
1982 Deduced, TDF & TDF_TopLevelParameterTypeList, POK,
1983 HasDeducedAnyParam,
1984 /*HasDeducedParam=*/nullptr);
1986 return Result;
1987
1990
1991 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1992 // deducing through the noexcept-specifier if it's part of the canonical
1993 // type. libstdc++ relies on this.
1994 Expr *NoexceptExpr = FPP->getNoexceptExpr();
1995 if (const NonTypeTemplateParmDecl *NTTP =
1996 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
1997 : nullptr) {
1998 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1999 "saw non-type template parameter with wrong depth");
2000
2001 llvm::APSInt Noexcept(1);
2002 switch (FPA->canThrow()) {
2003 case CT_Cannot:
2004 Noexcept = 1;
2005 [[fallthrough]];
2006
2007 case CT_Can:
2008 // We give E in noexcept(E) the "deduced from array bound" treatment.
2009 // FIXME: Should we?
2011 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
2012 /*DeducedFromArrayBound=*/true, Info,
2013 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2014
2015 case CT_Dependent:
2016 if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
2018 S, TemplateParams, NTTP, ArgNoexceptExpr, Info,
2019 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2020 // Can't deduce anything from throw(T...).
2021 break;
2022 }
2023 }
2024 // FIXME: Detect non-deduced exception specification mismatches?
2025 //
2026 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
2027 // top-level differences in noexcept-specifications.
2028
2030 }
2031
2032 case Type::InjectedClassName:
2033 // Treat a template's injected-class-name as if the template
2034 // specialization type had been used.
2035
2036 // template-name<T> (where template-name refers to a class template)
2037 // template-name<i>
2038 // TT<T>
2039 // TT<i>
2040 // TT<>
2041 case Type::TemplateSpecialization: {
2042 // When Arg cannot be a derived class, we can just try to deduce template
2043 // arguments from the template-id.
2044 if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
2045 return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
2046 POK != PartialOrderingKind::None,
2047 Deduced, HasDeducedAnyParam);
2048
2049 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
2050 Deduced.end());
2051
2053 S, TemplateParams, P, A, Info, POK != PartialOrderingKind::None,
2054 Deduced, HasDeducedAnyParam);
2056 return Result;
2057
2058 // We cannot inspect base classes as part of deduction when the type
2059 // is incomplete, so either instantiate any templates necessary to
2060 // complete the type, or skip over it if it cannot be completed.
2061 if (!S.isCompleteType(Info.getLocation(), A))
2062 return Result;
2063
2064 const CXXRecordDecl *RD = A->getAsCXXRecordDecl();
2065 if (RD->isInvalidDecl())
2066 return Result;
2067
2068 // Reset the incorrectly deduced argument from above.
2069 Deduced = DeducedOrig;
2070
2071 // Check bases according to C++14 [temp.deduct.call] p4b3:
2072 auto BaseResult = DeduceTemplateBases(S, RD, TemplateParams, P, Info,
2073 POK != PartialOrderingKind::None,
2074 Deduced, HasDeducedAnyParam);
2076 : Result;
2077 }
2078
2079 // T type::*
2080 // T T::*
2081 // T (type::*)()
2082 // type (T::*)()
2083 // type (type::*)(T)
2084 // type (T::*)(T)
2085 // T (type::*)(T)
2086 // T (T::*)()
2087 // T (T::*)(T)
2088 case Type::MemberPointer: {
2089 const auto *MPP = P->castAs<MemberPointerType>(),
2090 *MPA = A->getAs<MemberPointerType>();
2091 if (!MPA)
2093
2094 QualType PPT = MPP->getPointeeType();
2095 if (PPT->isFunctionType())
2096 S.adjustMemberFunctionCC(PPT, /*HasThisPointer=*/false,
2097 /*IsCtorOrDtor=*/false, Info.getLocation());
2098 QualType APT = MPA->getPointeeType();
2099 if (APT->isFunctionType())
2100 S.adjustMemberFunctionCC(APT, /*HasThisPointer=*/false,
2101 /*IsCtorOrDtor=*/false, Info.getLocation());
2102
2103 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
2105 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF,
2107 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2109 return Result;
2111 S, TemplateParams, QualType(MPP->getClass(), 0),
2112 QualType(MPA->getClass(), 0), Info, Deduced, SubTDF,
2114 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2115 }
2116
2117 // (clang extension)
2118 //
2119 // type(^)(T)
2120 // T(^)()
2121 // T(^)(T)
2122 case Type::BlockPointer: {
2123 const auto *BPP = P->castAs<BlockPointerType>(),
2124 *BPA = A->getAs<BlockPointerType>();
2125 if (!BPA)
2128 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
2129 Deduced, 0, degradeCallPartialOrderingKind(POK),
2130 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2131 }
2132
2133 // (clang extension)
2134 //
2135 // T __attribute__(((ext_vector_type(<integral constant>))))
2136 case Type::ExtVector: {
2137 const auto *VP = P->castAs<ExtVectorType>();
2138 QualType ElementType;
2139 if (const auto *VA = A->getAs<ExtVectorType>()) {
2140 // Make sure that the vectors have the same number of elements.
2141 if (VP->getNumElements() != VA->getNumElements())
2143 ElementType = VA->getElementType();
2144 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2145 // We can't check the number of elements, since the argument has a
2146 // dependent number of elements. This can only occur during partial
2147 // ordering.
2148 ElementType = VA->getElementType();
2149 } else {
2151 }
2152 // Perform deduction on the element types.
2154 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
2156 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2157 }
2158
2159 case Type::DependentVector: {
2160 const auto *VP = P->castAs<DependentVectorType>();
2161
2162 if (const auto *VA = A->getAs<VectorType>()) {
2163 // Perform deduction on the element types.
2165 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2166 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2167 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2169 return Result;
2170
2171 // Perform deduction on the vector size, if we can.
2172 const NonTypeTemplateParmDecl *NTTP =
2173 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2174 if (!NTTP)
2176
2177 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2178 ArgSize = VA->getNumElements();
2179 // Note that we use the "array bound" rules here; just like in that
2180 // case, we don't have any particular type for the vector size, but
2181 // we can provide one if necessary.
2183 S, TemplateParams, NTTP, ArgSize, S.Context.UnsignedIntTy, true,
2184 Info, POK != PartialOrderingKind::None, Deduced,
2185 HasDeducedAnyParam);
2186 }
2187
2188 if (const auto *VA = A->getAs<DependentVectorType>()) {
2189 // Perform deduction on the element types.
2191 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2192 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2193 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2195 return Result;
2196
2197 // Perform deduction on the vector size, if we can.
2198 const NonTypeTemplateParmDecl *NTTP =
2199 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2200 if (!NTTP)
2202
2204 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2205 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2206 }
2207
2209 }
2210
2211 // (clang extension)
2212 //
2213 // T __attribute__(((ext_vector_type(N))))
2214 case Type::DependentSizedExtVector: {
2215 const auto *VP = P->castAs<DependentSizedExtVectorType>();
2216
2217 if (const auto *VA = A->getAs<ExtVectorType>()) {
2218 // Perform deduction on the element types.
2220 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2221 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2222 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2224 return Result;
2225
2226 // Perform deduction on the vector size, if we can.
2227 const NonTypeTemplateParmDecl *NTTP =
2228 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2229 if (!NTTP)
2231
2232 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2233 ArgSize = VA->getNumElements();
2234 // Note that we use the "array bound" rules here; just like in that
2235 // case, we don't have any particular type for the vector size, but
2236 // we can provide one if necessary.
2238 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2239 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2240 }
2241
2242 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2243 // Perform deduction on the element types.
2245 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2246 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2247 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2249 return Result;
2250
2251 // Perform deduction on the vector size, if we can.
2252 const NonTypeTemplateParmDecl *NTTP =
2253 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2254 if (!NTTP)
2256
2258 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2259 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2260 }
2261
2263 }
2264
2265 // (clang extension)
2266 //
2267 // T __attribute__((matrix_type(<integral constant>,
2268 // <integral constant>)))
2269 case Type::ConstantMatrix: {
2270 const auto *MP = P->castAs<ConstantMatrixType>(),
2271 *MA = A->getAs<ConstantMatrixType>();
2272 if (!MA)
2274
2275 // Check that the dimensions are the same
2276 if (MP->getNumRows() != MA->getNumRows() ||
2277 MP->getNumColumns() != MA->getNumColumns()) {
2279 }
2280 // Perform deduction on element types.
2282 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2283 Deduced, TDF, degradeCallPartialOrderingKind(POK),
2284 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2285 }
2286
2287 case Type::DependentSizedMatrix: {
2288 const auto *MP = P->castAs<DependentSizedMatrixType>();
2289 const auto *MA = A->getAs<MatrixType>();
2290 if (!MA)
2292
2293 // Check the element type of the matrixes.
2295 S, TemplateParams, MP->getElementType(), MA->getElementType(),
2296 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2297 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2299 return Result;
2300
2301 // Try to deduce a matrix dimension.
2302 auto DeduceMatrixArg =
2303 [&S, &Info, &Deduced, &TemplateParams, &HasDeducedAnyParam, POK](
2304 Expr *ParamExpr, const MatrixType *A,
2305 unsigned (ConstantMatrixType::*GetArgDimension)() const,
2306 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2307 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2308 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
2309 if (!ParamExpr->isValueDependent()) {
2310 std::optional<llvm::APSInt> ParamConst =
2311 ParamExpr->getIntegerConstantExpr(S.Context);
2312 if (!ParamConst)
2314
2315 if (ACM) {
2316 if ((ACM->*GetArgDimension)() == *ParamConst)
2319 }
2320
2321 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2322 if (std::optional<llvm::APSInt> ArgConst =
2323 ArgExpr->getIntegerConstantExpr(S.Context))
2324 if (*ArgConst == *ParamConst)
2327 }
2328
2329 const NonTypeTemplateParmDecl *NTTP =
2330 getDeducedParameterFromExpr(Info, ParamExpr);
2331 if (!NTTP)
2333
2334 if (ACM) {
2335 llvm::APSInt ArgConst(
2337 ArgConst = (ACM->*GetArgDimension)();
2339 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
2340 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
2341 Deduced, HasDeducedAnyParam);
2342 }
2343
2345 S, TemplateParams, NTTP, (ADM->*GetArgDimensionExpr)(), Info,
2346 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2347 };
2348
2349 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
2353 return Result;
2354
2355 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2358 }
2359
2360 // (clang extension)
2361 //
2362 // T __attribute__(((address_space(N))))
2363 case Type::DependentAddressSpace: {
2364 const auto *ASP = P->castAs<DependentAddressSpaceType>();
2365
2366 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
2367 // Perform deduction on the pointer type.
2369 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2370 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2371 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2373 return Result;
2374
2375 // Perform deduction on the address space, if we can.
2376 const NonTypeTemplateParmDecl *NTTP =
2377 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2378 if (!NTTP)
2380
2382 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info,
2383 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2384 }
2385
2387 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2388 false);
2389 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
2390
2391 // Perform deduction on the pointer types.
2393 S, TemplateParams, ASP->getPointeeType(),
2394 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF,
2396 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2398 return Result;
2399
2400 // Perform deduction on the address space, if we can.
2401 const NonTypeTemplateParmDecl *NTTP =
2402 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2403 if (!NTTP)
2405
2407 S, TemplateParams, NTTP, ArgAddressSpace, S.Context.IntTy, true,
2408 Info, POK != PartialOrderingKind::None, Deduced,
2409 HasDeducedAnyParam);
2410 }
2411
2413 }
2414 case Type::DependentBitInt: {
2415 const auto *IP = P->castAs<DependentBitIntType>();
2416
2417 if (const auto *IA = A->getAs<BitIntType>()) {
2418 if (IP->isUnsigned() != IA->isUnsigned())
2420
2421 const NonTypeTemplateParmDecl *NTTP =
2422 getDeducedParameterFromExpr(Info, IP->getNumBitsExpr());
2423 if (!NTTP)
2425
2426 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2427 ArgSize = IA->getNumBits();
2428
2430 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2431 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2432 }
2433
2434 if (const auto *IA = A->getAs<DependentBitIntType>()) {
2435 if (IP->isUnsigned() != IA->isUnsigned())
2438 }
2439
2441 }
2442
2443 case Type::TypeOfExpr:
2444 case Type::TypeOf:
2445 case Type::DependentName:
2446 case Type::UnresolvedUsing:
2447 case Type::Decltype:
2448 case Type::UnaryTransform:
2449 case Type::DeducedTemplateSpecialization:
2450 case Type::DependentTemplateSpecialization:
2451 case Type::PackExpansion:
2452 case Type::Pipe:
2453 case Type::ArrayParameter:
2454 case Type::HLSLAttributedResource:
2455 // No template argument deduction for these types
2457
2458 case Type::PackIndexing: {
2459 const PackIndexingType *PIT = P->getAs<PackIndexingType>();
2460 if (PIT->hasSelectedType()) {
2462 S, TemplateParams, PIT->getSelectedType(), A, Info, Deduced, TDF,
2464 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2465 }
2467 }
2468 }
2469
2470 llvm_unreachable("Invalid Type Class!");
2471}
2472
2478 bool *HasDeducedAnyParam) {
2479 // If the template argument is a pack expansion, perform template argument
2480 // deduction against the pattern of that expansion. This only occurs during
2481 // partial ordering.
2482 if (A.isPackExpansion())
2484
2485 switch (P.getKind()) {
2487 llvm_unreachable("Null template argument in parameter list");
2488
2492 S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0,
2493 PartialOrdering ? PartialOrderingKind::NonCall
2494 : PartialOrderingKind::None,
2495 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2496 Info.FirstArg = P;
2497 Info.SecondArg = A;
2499
2501 // PartialOrdering does not matter here, since template specializations are
2502 // not being deduced.
2505 S, TemplateParams, P.getAsTemplate(), A.getAsTemplate(), Info,
2506 /*DefaultArguments=*/{}, /*PartialOrdering=*/false, Deduced,
2507 HasDeducedAnyParam);
2508 Info.FirstArg = P;
2509 Info.SecondArg = A;
2511
2513 llvm_unreachable("caller should handle pack expansions");
2514
2517 isSameDeclaration(P.getAsDecl(), A.getAsDecl()))
2519
2520 Info.FirstArg = P;
2521 Info.SecondArg = A;
2523
2526 S.Context.hasSameType(P.getNullPtrType(), A.getNullPtrType()))
2528
2529 Info.FirstArg = P;
2530 Info.SecondArg = A;
2532
2535 if (hasSameExtendedValue(P.getAsIntegral(), A.getAsIntegral()))
2537 }
2538 Info.FirstArg = P;
2539 Info.SecondArg = A;
2541
2546
2547 Info.FirstArg = P;
2548 Info.SecondArg = A;
2550
2552 if (const NonTypeTemplateParmDecl *NTTP =
2553 getDeducedParameterFromExpr(Info, P.getAsExpr())) {
2554 switch (A.getKind()) {
2559 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2561 HasDeducedAnyParam);
2562
2565 S, TemplateParams, NTTP, A.getNullPtrType(), Info, PartialOrdering,
2566 Deduced, HasDeducedAnyParam);
2567
2570 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
2571 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
2572
2578 Info.FirstArg = P;
2579 Info.SecondArg = A;
2581 }
2582 llvm_unreachable("Unknown template argument kind");
2583 }
2584
2585 // Can't deduce anything, but that's okay.
2588 llvm_unreachable("Argument packs should be expanded by the caller!");
2589 }
2590
2591 llvm_unreachable("Invalid TemplateArgument Kind!");
2592}
2593
2594/// Determine whether there is a template argument to be used for
2595/// deduction.
2596///
2597/// This routine "expands" argument packs in-place, overriding its input
2598/// parameters so that \c Args[ArgIdx] will be the available template argument.
2599///
2600/// \returns true if there is another template argument (which will be at
2601/// \c Args[ArgIdx]), false otherwise.
2603 unsigned &ArgIdx) {
2604 if (ArgIdx == Args.size())
2605 return false;
2606
2607 const TemplateArgument &Arg = Args[ArgIdx];
2608 if (Arg.getKind() != TemplateArgument::Pack)
2609 return true;
2610
2611 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2612 Args = Arg.pack_elements();
2613 ArgIdx = 0;
2614 return ArgIdx < Args.size();
2615}
2616
2617/// Determine whether the given set of template arguments has a pack
2618/// expansion that is not the last template argument.
2620 bool FoundPackExpansion = false;
2621 for (const auto &A : Args) {
2622 if (FoundPackExpansion)
2623 return true;
2624
2625 if (A.getKind() == TemplateArgument::Pack)
2626 return hasPackExpansionBeforeEnd(A.pack_elements());
2627
2628 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2629 // templates, it should not be treated as a pack expansion.
2630 if (A.isPackExpansion())
2631 FoundPackExpansion = true;
2632 }
2633
2634 return false;
2635}
2636
2643 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
2644 PackFold PackFold, bool *HasDeducedAnyParam) {
2645 if (PackFold == PackFold::ArgumentToParameter)
2646 std::swap(Ps, As);
2647 // C++0x [temp.deduct.type]p9:
2648 // If the template argument list of P contains a pack expansion that is not
2649 // the last template argument, the entire template argument list is a
2650 // non-deduced context.
2653
2654 // C++0x [temp.deduct.type]p9:
2655 // If P has a form that contains <T> or <i>, then each argument Pi of the
2656 // respective template argument list P is compared with the corresponding
2657 // argument Ai of the corresponding template argument list of A.
2658 unsigned ArgIdx = 0, ParamIdx = 0;
2660 const TemplateArgument &P = Ps[ParamIdx];
2661 if (!P.isPackExpansion()) {
2662 // The simple case: deduce template arguments by matching Pi and Ai.
2663
2664 // Check whether we have enough arguments.
2665 if (!hasTemplateArgumentForDeduction(As, ArgIdx))
2666 return NumberOfArgumentsMustMatch
2669
2670 // C++1z [temp.deduct.type]p9:
2671 // During partial ordering, if Ai was originally a pack expansion [and]
2672 // Pi is not a pack expansion, template argument deduction fails.
2673 if (As[ArgIdx].isPackExpansion())
2675
2676 // Perform deduction for this Pi/Ai pair.
2677 TemplateArgument Pi = P, Ai = As[ArgIdx];
2678 if (PackFold == PackFold::ArgumentToParameter)
2679 std::swap(Pi, Ai);
2680 if (auto Result = DeduceTemplateArguments(S, TemplateParams, Pi, Ai, Info,
2681 PartialOrdering, Deduced,
2682 HasDeducedAnyParam);
2684 return Result;
2685
2686 // Move to the next argument.
2687 ++ArgIdx;
2688 continue;
2689 }
2690
2691 // The parameter is a pack expansion.
2692
2693 // C++0x [temp.deduct.type]p9:
2694 // If Pi is a pack expansion, then the pattern of Pi is compared with
2695 // each remaining argument in the template argument list of A. Each
2696 // comparison deduces template arguments for subsequent positions in the
2697 // template parameter packs expanded by Pi.
2698 TemplateArgument Pattern = P.getPackExpansionPattern();
2699
2700 // Prepare to deduce the packs within the pattern.
2701 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2702
2703 // Keep track of the deduced template arguments for each parameter pack
2704 // expanded by this pack expansion (the outer index) and for each
2705 // template argument (the inner SmallVectors).
2706 for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
2707 PackScope.hasNextElement();
2708 ++ArgIdx) {
2709 TemplateArgument Pi = Pattern, Ai = As[ArgIdx];
2710 if (PackFold == PackFold::ArgumentToParameter)
2711 std::swap(Pi, Ai);
2712 // Deduce template arguments from the pattern.
2713 if (auto Result = DeduceTemplateArguments(S, TemplateParams, Pi, Ai, Info,
2714 PartialOrdering, Deduced,
2715 HasDeducedAnyParam);
2717 return Result;
2718
2719 PackScope.nextPackElement();
2720 }
2721
2722 // Build argument packs for each of the parameter packs expanded by this
2723 // pack expansion.
2724 if (auto Result = PackScope.finish();
2726 return Result;
2727 }
2728
2730}
2731
2736 bool NumberOfArgumentsMustMatch) {
2737 return ::DeduceTemplateArguments(
2738 *this, TemplateParams, Ps, As, Info, Deduced, NumberOfArgumentsMustMatch,
2739 /*PartialOrdering=*/false, PackFold::ParameterToArgument,
2740 /*HasDeducedAnyParam=*/nullptr);
2741}
2742
2743/// Determine whether two template arguments are the same.
2744static bool isSameTemplateArg(ASTContext &Context,
2746 const TemplateArgument &Y,
2747 bool PartialOrdering,
2748 bool PackExpansionMatchesPack = false) {
2749 // If we're checking deduced arguments (X) against original arguments (Y),
2750 // we will have flattened packs to non-expansions in X.
2751 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2752 X = X.getPackExpansionPattern();
2753
2754 if (X.getKind() != Y.getKind())
2755 return false;
2756
2757 switch (X.getKind()) {
2759 llvm_unreachable("Comparing NULL template argument");
2760
2762 return Context.getCanonicalType(X.getAsType()) ==
2763 Context.getCanonicalType(Y.getAsType());
2764
2766 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
2767
2769 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2770
2773 return Context.getCanonicalTemplateName(
2774 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2777
2779 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2780
2782 return X.structurallyEquals(Y);
2783
2785 llvm::FoldingSetNodeID XID, YID;
2786 X.getAsExpr()->Profile(XID, Context, true);
2787 Y.getAsExpr()->Profile(YID, Context, true);
2788 return XID == YID;
2789 }
2790
2792 unsigned PackIterationSize = X.pack_size();
2793 if (X.pack_size() != Y.pack_size()) {
2794 if (!PartialOrdering)
2795 return false;
2796
2797 // C++0x [temp.deduct.type]p9:
2798 // During partial ordering, if Ai was originally a pack expansion:
2799 // - if P does not contain a template argument corresponding to Ai
2800 // then Ai is ignored;
2801 bool XHasMoreArg = X.pack_size() > Y.pack_size();
2802 if (!(XHasMoreArg && X.pack_elements().back().isPackExpansion()) &&
2803 !(!XHasMoreArg && Y.pack_elements().back().isPackExpansion()))
2804 return false;
2805
2806 if (XHasMoreArg)
2807 PackIterationSize = Y.pack_size();
2808 }
2809
2810 ArrayRef<TemplateArgument> XP = X.pack_elements();
2812 for (unsigned i = 0; i < PackIterationSize; ++i)
2813 if (!isSameTemplateArg(Context, XP[i], YP[i], PartialOrdering,
2814 PackExpansionMatchesPack))
2815 return false;
2816 return true;
2817 }
2818 }
2819
2820 llvm_unreachable("Invalid TemplateArgument Kind!");
2821}
2822
2825 QualType NTTPType, SourceLocation Loc,
2827 switch (Arg.getKind()) {
2829 llvm_unreachable("Can't get a NULL template argument here");
2830
2832 return TemplateArgumentLoc(
2834
2836 if (NTTPType.isNull())
2837 NTTPType = Arg.getParamTypeForDecl();
2840 .getAs<Expr>();
2842 }
2843
2845 if (NTTPType.isNull())
2846 NTTPType = Arg.getNullPtrType();
2848 .getAs<Expr>();
2849 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2850 E);
2851 }
2852
2857 }
2858
2864 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2865 else if (QualifiedTemplateName *QTN =
2866 Template.getAsQualifiedTemplateName())
2867 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2868
2870 return TemplateArgumentLoc(Context, Arg,
2871 Builder.getWithLocInContext(Context), Loc);
2872
2873 return TemplateArgumentLoc(
2874 Context, Arg, Builder.getWithLocInContext(Context), Loc, Loc);
2875 }
2876
2878 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2879
2882 }
2883
2884 llvm_unreachable("Invalid TemplateArgument Kind!");
2885}
2886
2889 SourceLocation Location) {
2891 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2892}
2893
2894/// Convert the given deduced template argument and add it to the set of
2895/// fully-converted template arguments.
2897 Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template,
2898 TemplateDeductionInfo &Info, bool IsDeduced,
2899 SmallVectorImpl<TemplateArgument> &SugaredOutput,
2900 SmallVectorImpl<TemplateArgument> &CanonicalOutput) {
2901 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2902 unsigned ArgumentPackIndex) {
2903 // Convert the deduced template argument into a template
2904 // argument that we can check, almost as if the user had written
2905 // the template argument explicitly.
2907 Arg, QualType(), Info.getLocation(), Param);
2908
2909 // Check the template argument, converting it as necessary.
2910 return S.CheckTemplateArgument(
2911 Param, ArgLoc, Template, Template->getLocation(),
2912 Template->getSourceRange().getEnd(), ArgumentPackIndex, SugaredOutput,
2913 CanonicalOutput,
2914 IsDeduced
2918 };
2919
2920 if (Arg.getKind() == TemplateArgument::Pack) {
2921 // This is a template argument pack, so check each of its arguments against
2922 // the template parameter.
2923 SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
2924 CanonicalPackedArgsBuilder;
2925 for (const auto &P : Arg.pack_elements()) {
2926 // When converting the deduced template argument, append it to the
2927 // general output list. We need to do this so that the template argument
2928 // checking logic has all of the prior template arguments available.
2929 DeducedTemplateArgument InnerArg(P);
2931 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2932 "deduced nested pack");
2933 if (P.isNull()) {
2934 // We deduced arguments for some elements of this pack, but not for
2935 // all of them. This happens if we get a conditionally-non-deduced
2936 // context in a pack expansion (such as an overload set in one of the
2937 // arguments).
2938 S.Diag(Param->getLocation(),
2939 diag::err_template_arg_deduced_incomplete_pack)
2940 << Arg << Param;
2941 return true;
2942 }
2943 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
2944 return true;
2945
2946 // Move the converted template argument into our argument pack.
2947 SugaredPackedArgsBuilder.push_back(SugaredOutput.pop_back_val());
2948 CanonicalPackedArgsBuilder.push_back(CanonicalOutput.pop_back_val());
2949 }
2950
2951 // If the pack is empty, we still need to substitute into the parameter
2952 // itself, in case that substitution fails.
2953 if (SugaredPackedArgsBuilder.empty()) {
2955 MultiLevelTemplateArgumentList Args(Template, SugaredOutput,
2956 /*Final=*/true);
2957
2958 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2959 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2960 NTTP, SugaredOutput,
2961 Template->getSourceRange());
2962 if (Inst.isInvalid() ||
2963 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2964 NTTP->getDeclName()).isNull())
2965 return true;
2966 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2967 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2968 TTP, SugaredOutput,
2969 Template->getSourceRange());
2970 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2971 return true;
2972 }
2973 // For type parameters, no substitution is ever required.
2974 }
2975
2976 // Create the resulting argument pack.
2977 SugaredOutput.push_back(
2978 TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
2979 CanonicalOutput.push_back(TemplateArgument::CreatePackCopy(
2980 S.Context, CanonicalPackedArgsBuilder));
2981 return false;
2982 }
2983
2984 return ConvertArg(Arg, 0);
2985}
2986
2987// FIXME: This should not be a template, but
2988// ClassTemplatePartialSpecializationDecl sadly does not derive from
2989// TemplateDecl.
2990/// \param IsIncomplete When used, we only consider template parameters that
2991/// were deduced, disregarding any default arguments. After the function
2992/// finishes, the object pointed at will contain a value indicating if the
2993/// conversion was actually incomplete.
2994template <typename TemplateDeclT>
2996 Sema &S, TemplateDeclT *Template, bool IsDeduced,
2999 SmallVectorImpl<TemplateArgument> &SugaredBuilder,
3000 SmallVectorImpl<TemplateArgument> &CanonicalBuilder,
3001 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
3002 unsigned NumAlreadyConverted = 0, bool *IsIncomplete = nullptr) {
3003 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3004
3005 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3006 NamedDecl *Param = TemplateParams->getParam(I);
3007
3008 // C++0x [temp.arg.explicit]p3:
3009 // A trailing template parameter pack (14.5.3) not otherwise deduced will
3010 // be deduced to an empty sequence of template arguments.
3011 // FIXME: Where did the word "trailing" come from?
3012 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
3013 if (auto Result =
3014 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish();
3016 return Result;
3017 }
3018
3019 if (!Deduced[I].isNull()) {
3020 if (I < NumAlreadyConverted) {
3021 // We may have had explicitly-specified template arguments for a
3022 // template parameter pack (that may or may not have been extended
3023 // via additional deduced arguments).
3024 if (Param->isParameterPack() && CurrentInstantiationScope &&
3025 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
3026 // Forget the partially-substituted pack; its substitution is now
3027 // complete.
3028 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
3029 // We still need to check the argument in case it was extended by
3030 // deduction.
3031 } else {
3032 // We have already fully type-checked and converted this
3033 // argument, because it was explicitly-specified. Just record the
3034 // presence of this argument.
3035 SugaredBuilder.push_back(Deduced[I]);
3036 CanonicalBuilder.push_back(
3038 continue;
3039 }
3040 }
3041
3042 // We may have deduced this argument, so it still needs to be
3043 // checked and converted.
3044 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
3045 IsDeduced, SugaredBuilder,
3046 CanonicalBuilder)) {
3047 Info.Param = makeTemplateParameter(Param);
3048 // FIXME: These template arguments are temporary. Free them!
3049 Info.reset(
3050 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3051 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3053 }
3054
3055 continue;
3056 }
3057
3058 // [C++26][temp.deduct.partial]p12 - When partial ordering, it's ok for
3059 // template parameters to remain not deduced. As a provisional fix for a
3060 // core issue that does not exist yet, which may be related to CWG2160, only
3061 // consider template parameters that were deduced, disregarding any default
3062 // arguments.
3063 if (IsIncomplete) {
3064 *IsIncomplete = true;
3065 SugaredBuilder.push_back({});
3066 CanonicalBuilder.push_back({});
3067 continue;
3068 }
3069
3070 // Substitute into the default template argument, if available.
3071 bool HasDefaultArg = false;
3072 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
3073 if (!TD) {
3074 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
3075 isa<VarTemplatePartialSpecializationDecl>(Template));
3077 }
3078
3079 TemplateArgumentLoc DefArg;
3080 {
3081 Qualifiers ThisTypeQuals;
3082 CXXRecordDecl *ThisContext = nullptr;
3083 if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
3084 if (Rec->isLambda())
3085 if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
3086 ThisContext = Method->getParent();
3087 ThisTypeQuals = Method->getMethodQualifiers();
3088 }
3089
3090 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
3091 S.getLangOpts().CPlusPlus17);
3092
3094 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param,
3095 SugaredBuilder, CanonicalBuilder, HasDefaultArg);
3096 }
3097
3098 // If there was no default argument, deduction is incomplete.
3099 if (DefArg.getArgument().isNull()) {
3101 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
3102 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3103 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3104
3107 }
3108
3109 // Check whether we can actually use the default argument.
3111 Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
3112 0, SugaredBuilder, CanonicalBuilder, Sema::CTAK_Specified)) {
3114 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
3115 // FIXME: These template arguments are temporary. Free them!
3116 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3117 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3119 }
3120
3121 // If we get here, we successfully used the default template argument.
3122 }
3123
3125}
3126
3128 if (auto *DC = dyn_cast<DeclContext>(D))
3129 return DC;
3130 return D->getDeclContext();
3131}
3132
3133template<typename T> struct IsPartialSpecialization {
3134 static constexpr bool value = false;
3135};
3136template<>
3138 static constexpr bool value = true;
3139};
3140template<>
3142 static constexpr bool value = true;
3143};
3144template <typename TemplateDeclT>
3145static bool DeducedArgsNeedReplacement(TemplateDeclT *Template) {
3146 return false;
3147}
3148template <>
3151 return !Spec->isClassScopeExplicitSpecialization();
3152}
3153template <>
3156 return !Spec->isClassScopeExplicitSpecialization();
3157}
3158
3159template <typename TemplateDeclT>
3161CheckDeducedArgumentConstraints(Sema &S, TemplateDeclT *Template,
3162 ArrayRef<TemplateArgument> SugaredDeducedArgs,
3163 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
3164 TemplateDeductionInfo &Info) {
3165 llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
3166 Template->getAssociatedConstraints(AssociatedConstraints);
3167
3168 std::optional<ArrayRef<TemplateArgument>> Innermost;
3169 // If we don't need to replace the deduced template arguments,
3170 // we can add them immediately as the inner-most argument list.
3171 if (!DeducedArgsNeedReplacement(Template))
3172 Innermost = CanonicalDeducedArgs;
3173
3175 Template, Template->getDeclContext(), /*Final=*/false, Innermost,
3176 /*RelativeToPrimary=*/true, /*Pattern=*/
3177 nullptr, /*ForConstraintInstantiation=*/true);
3178
3179 // getTemplateInstantiationArgs picks up the non-deduced version of the
3180 // template args when this is a variable template partial specialization and
3181 // not class-scope explicit specialization, so replace with Deduced Args
3182 // instead of adding to inner-most.
3183 if (!Innermost)
3184 MLTAL.replaceInnermostTemplateArguments(Template, CanonicalDeducedArgs);
3185
3186 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
3187 Info.getLocation(),
3190 Info.reset(
3191 TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
3192 TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
3194 }
3196}
3197
3198/// Complete template argument deduction for a partial specialization.
3199template <typename T>
3200static std::enable_if_t<IsPartialSpecialization<T>::value,
3203 Sema &S, T *Partial, bool IsPartialOrdering,
3204 ArrayRef<TemplateArgument> TemplateArgs,
3206 TemplateDeductionInfo &Info) {
3207 // Unevaluated SFINAE context.
3210 Sema::SFINAETrap Trap(S);
3211
3212 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
3213
3214 // C++ [temp.deduct.type]p2:
3215 // [...] or if any template argument remains neither deduced nor
3216 // explicitly specified, template argument deduction fails.
3217 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3219 S, Partial, IsPartialOrdering, Deduced, Info, SugaredBuilder,
3220 CanonicalBuilder);
3222 return Result;
3223
3224 // Form the template argument list from the deduced template arguments.
3225 TemplateArgumentList *SugaredDeducedArgumentList =
3226 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
3227 TemplateArgumentList *CanonicalDeducedArgumentList =
3228 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
3229
3230 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3231
3232 // Substitute the deduced template arguments into the template
3233 // arguments of the class template partial specialization, and
3234 // verify that the instantiated template arguments are both valid
3235 // and are equivalent to the template arguments originally provided
3236 // to the class template.
3237 LocalInstantiationScope InstScope(S);
3238 auto *Template = Partial->getSpecializedTemplate();
3239 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
3240 Partial->getTemplateArgsAsWritten();
3241
3242 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
3243 PartialTemplArgInfo->RAngleLoc);
3244
3245 if (S.SubstTemplateArguments(PartialTemplArgInfo->arguments(),
3247 SugaredBuilder,
3248 /*Final=*/true),
3249 InstArgs)) {
3250 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
3251 if (ParamIdx >= Partial->getTemplateParameters()->size())
3252 ParamIdx = Partial->getTemplateParameters()->size() - 1;
3253
3254 Decl *Param = const_cast<NamedDecl *>(
3255 Partial->getTemplateParameters()->getParam(ParamIdx));
3256 Info.Param = makeTemplateParameter(Param);
3257 Info.FirstArg = (*PartialTemplArgInfo)[ArgIdx].getArgument();
3259 }
3260
3262 SmallVector<TemplateArgument, 4> SugaredConvertedInstArgs,
3263 CanonicalConvertedInstArgs;
3265 Template, Partial->getLocation(), InstArgs, /*DefaultArgs=*/{}, false,
3266 SugaredConvertedInstArgs, CanonicalConvertedInstArgs,
3267 /*UpdateArgsWithConversions=*/true, &ConstraintsNotSatisfied))
3271
3272 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3273 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3274 TemplateArgument InstArg = SugaredConvertedInstArgs.data()[I];
3275 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
3276 IsPartialOrdering)) {
3277 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3278 Info.FirstArg = TemplateArgs[I];
3279 Info.SecondArg = InstArg;
3281 }
3282 }
3283
3284 if (Trap.hasErrorOccurred())
3286
3287 if (!IsPartialOrdering) {
3289 S, Partial, SugaredBuilder, CanonicalBuilder, Info);
3291 return Result;
3292 }
3293
3295}
3296
3297/// Complete template argument deduction for a class or variable template,
3298/// when partial ordering against a partial specialization.
3299// FIXME: Factor out duplication with partial specialization version above.
3301 Sema &S, TemplateDecl *Template, bool PartialOrdering,
3302 ArrayRef<TemplateArgument> TemplateArgs,
3304 TemplateDeductionInfo &Info) {
3305 // Unevaluated SFINAE context.
3308 Sema::SFINAETrap Trap(S);
3309
3310 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
3311
3312 // C++ [temp.deduct.type]p2:
3313 // [...] or if any template argument remains neither deduced nor
3314 // explicitly specified, template argument deduction fails.
3315 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3317 S, Template, /*IsDeduced*/ PartialOrdering, Deduced, Info,
3318 SugaredBuilder, CanonicalBuilder,
3319 /*CurrentInstantiationScope=*/nullptr,
3320 /*NumAlreadyConverted=*/0U);
3322 return Result;
3323
3324 // Check that we produced the correct argument list.
3325 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3326 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3327 TemplateArgument InstArg = CanonicalBuilder[I];
3328 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg, PartialOrdering,
3329 /*PackExpansionMatchesPack=*/true)) {
3330 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3331 Info.FirstArg = TemplateArgs[I];
3332 Info.SecondArg = InstArg;
3334 }
3335 }
3336
3337 if (Trap.hasErrorOccurred())
3339
3340 if (!PartialOrdering) {
3342 S, Template, SugaredBuilder, CanonicalBuilder, Info);
3344 return Result;
3345 }
3346
3348}
3349
3350/// Complete template argument deduction for DeduceTemplateArgumentsFromType.
3351/// FIXME: this is mostly duplicated with the above two versions. Deduplicate
3352/// the three implementations.
3354 Sema &S, TemplateDecl *TD,
3356 TemplateDeductionInfo &Info) {
3357 // Unevaluated SFINAE context.
3360 Sema::SFINAETrap Trap(S);
3361
3363
3364 // C++ [temp.deduct.type]p2:
3365 // [...] or if any template argument remains neither deduced nor
3366 // explicitly specified, template argument deduction fails.
3367 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3369 S, TD, /*IsPartialOrdering=*/false, Deduced, Info, SugaredBuilder,
3370 CanonicalBuilder);
3372 return Result;
3373
3374 if (Trap.hasErrorOccurred())
3376
3377 if (auto Result = CheckDeducedArgumentConstraints(S, TD, SugaredBuilder,
3378 CanonicalBuilder, Info);
3380 return Result;
3381
3383}
3384
3385/// Perform template argument deduction to determine whether the given template
3386/// arguments match the given class or variable template partial specialization
3387/// per C++ [temp.class.spec.match].
3388template <typename T>
3389static std::enable_if_t<IsPartialSpecialization<T>::value,
3392 ArrayRef<TemplateArgument> TemplateArgs,
3393 TemplateDeductionInfo &Info) {
3394 if (Partial->isInvalidDecl())
3396
3397 // C++ [temp.class.spec.match]p2:
3398 // A partial specialization matches a given actual template
3399 // argument list if the template arguments of the partial
3400 // specialization can be deduced from the actual template argument
3401 // list (14.8.2).
3402
3403 // Unevaluated SFINAE context.
3406 Sema::SFINAETrap Trap(S);
3407
3408 // This deduction has no relation to any outer instantiation we might be
3409 // performing.
3410 LocalInstantiationScope InstantiationScope(S);
3411
3413 Deduced.resize(Partial->getTemplateParameters()->size());
3415 S, Partial->getTemplateParameters(),
3416 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3417 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/false,
3418 PackFold::ParameterToArgument,
3419 /*HasDeducedAnyParam=*/nullptr);
3421 return Result;
3422
3423 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3424 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs,
3425 Info);
3426 if (Inst.isInvalid())
3428
3429 if (Trap.hasErrorOccurred())
3431
3434 Result = ::FinishTemplateArgumentDeduction(S, Partial,
3435 /*IsPartialOrdering=*/false,
3436 TemplateArgs, Deduced, Info);
3437 });
3438 return Result;
3439}
3440
3443 ArrayRef<TemplateArgument> TemplateArgs,
3444 TemplateDeductionInfo &Info) {
3445 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3446}
3449 ArrayRef<TemplateArgument> TemplateArgs,
3450 TemplateDeductionInfo &Info) {
3451 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3452}
3453
3457 if (TD->isInvalidDecl())
3459
3460 QualType PType;
3461 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
3462 // Use the InjectedClassNameType.
3463 PType = Context.getTypeDeclType(CTD->getTemplatedDecl());
3464 } else if (const auto *AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(TD)) {
3465 PType = AliasTemplate->getTemplatedDecl()->getUnderlyingType();
3466 } else {
3467 assert(false && "Expected a class or alias template");
3468 }
3469
3470 // Unevaluated SFINAE context.
3473 SFINAETrap Trap(*this);
3474
3475 // This deduction has no relation to any outer instantiation we might be
3476 // performing.
3477 LocalInstantiationScope InstantiationScope(*this);
3478
3480 TD->getTemplateParameters()->size());
3483 if (auto DeducedResult = DeduceTemplateArguments(
3484 TD->getTemplateParameters(), PArgs, AArgs, Info, Deduced, false);
3485 DeducedResult != TemplateDeductionResult::Success) {
3486 return DeducedResult;
3487 }
3488
3489 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3490 InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs, Info);
3491 if (Inst.isInvalid())
3493
3494 if (Trap.hasErrorOccurred())
3496
3499 Result = ::FinishTemplateArgumentDeduction(*this, TD, Deduced, Info);
3500 });
3501 return Result;
3502}
3503
3504/// Determine whether the given type T is a simple-template-id type.
3506 if (const TemplateSpecializationType *Spec
3508 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
3509
3510 // C++17 [temp.local]p2:
3511 // the injected-class-name [...] is equivalent to the template-name followed
3512 // by the template-arguments of the class template specialization or partial
3513 // specialization enclosed in <>
3514 // ... which means it's equivalent to a simple-template-id.
3515 //
3516 // This only arises during class template argument deduction for a copy
3517 // deduction candidate, where it permits slicing.
3519 return true;
3520
3521 return false;
3522}
3523
3525 FunctionTemplateDecl *FunctionTemplate,
3526 TemplateArgumentListInfo &ExplicitTemplateArgs,
3529 TemplateDeductionInfo &Info) {
3530 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3531 TemplateParameterList *TemplateParams
3532 = FunctionTemplate->getTemplateParameters();
3533
3534 if (ExplicitTemplateArgs.size() == 0) {
3535 // No arguments to substitute; just copy over the parameter types and
3536 // fill in the function type.
3537 for (auto *P : Function->parameters())
3538 ParamTypes.push_back(P->getType());
3539
3540 if (FunctionType)
3541 *FunctionType = Function->getType();
3543 }
3544
3545 // Unevaluated SFINAE context.
3548 SFINAETrap Trap(*this);
3549
3550 // C++ [temp.arg.explicit]p3:
3551 // Template arguments that are present shall be specified in the
3552 // declaration order of their corresponding template-parameters. The
3553 // template argument list shall not specify more template-arguments than
3554 // there are corresponding template-parameters.
3555 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3556
3557 // Enter a new template instantiation context where we check the
3558 // explicitly-specified template arguments against this function template,
3559 // and then substitute them into the function parameter types.
3562 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3564 if (Inst.isInvalid())
3566
3568 ExplicitTemplateArgs, /*DefaultArgs=*/{}, true,
3569 SugaredBuilder, CanonicalBuilder,
3570 /*UpdateArgsWithConversions=*/false) ||
3571 Trap.hasErrorOccurred()) {
3572 unsigned Index = SugaredBuilder.size();
3573 if (Index >= TemplateParams->size())
3575 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3577 }
3578
3579 // Form the template argument list from the explicitly-specified
3580 // template arguments.
3581 TemplateArgumentList *SugaredExplicitArgumentList =
3583 TemplateArgumentList *CanonicalExplicitArgumentList =
3584 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3585 Info.setExplicitArgs(SugaredExplicitArgumentList,
3586 CanonicalExplicitArgumentList);
3587
3588 // Template argument deduction and the final substitution should be
3589 // done in the context of the templated declaration. Explicit
3590 // argument substitution, on the other hand, needs to happen in the
3591 // calling context.
3592 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3593
3594 // If we deduced template arguments for a template parameter pack,
3595 // note that the template argument pack is partially substituted and record
3596 // the explicit template arguments. They'll be used as part of deduction
3597 // for this template parameter pack.
3598 unsigned PartiallySubstitutedPackIndex = -1u;
3599 if (!SugaredBuilder.empty()) {
3600 const TemplateArgument &Arg = SugaredBuilder.back();
3601 if (Arg.getKind() == TemplateArgument::Pack) {
3602 auto *Param = TemplateParams->getParam(SugaredBuilder.size() - 1);
3603 // If this is a fully-saturated fixed-size pack, it should be
3604 // fully-substituted, not partially-substituted.
3605 std::optional<unsigned> Expansions = getExpandedPackSize(Param);
3606 if (!Expansions || Arg.pack_size() < *Expansions) {
3607 PartiallySubstitutedPackIndex = SugaredBuilder.size() - 1;
3609 Param, Arg.pack_begin(), Arg.pack_size());
3610 }
3611 }
3612 }
3613
3614 const FunctionProtoType *Proto
3615 = Function->getType()->getAs<FunctionProtoType>();
3616 assert(Proto && "Function template does not have a prototype?");
3617
3618 // Isolate our substituted parameters from our caller.
3619 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3620
3621 ExtParameterInfoBuilder ExtParamInfos;
3622
3624 SugaredExplicitArgumentList->asArray(),
3625 /*Final=*/true);
3626
3627 // Instantiate the types of each of the function parameters given the
3628 // explicitly-specified template arguments. If the function has a trailing
3629 // return type, substitute it after the arguments to ensure we substitute
3630 // in lexical order.
3631 if (Proto->hasTrailingReturn()) {
3632 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3633 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3634 /*params=*/nullptr, ExtParamInfos))
3636 }
3637
3638 // Instantiate the return type.
3639 QualType ResultType;
3640 {
3641 // C++11 [expr.prim.general]p3:
3642 // If a declaration declares a member function or member function
3643 // template of a class X, the expression this is a prvalue of type
3644 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3645 // and the end of the function-definition, member-declarator, or
3646 // declarator.
3647 Qualifiers ThisTypeQuals;
3648 CXXRecordDecl *ThisContext = nullptr;
3649 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3650 ThisContext = Method->getParent();
3651 ThisTypeQuals = Method->getMethodQualifiers();
3652 }
3653
3654 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3656
3657 ResultType =
3658 SubstType(Proto->getReturnType(), MLTAL,
3659 Function->getTypeSpecStartLoc(), Function->getDeclName());
3660 if (ResultType.isNull() || Trap.hasErrorOccurred())
3662 // CUDA: Kernel function must have 'void' return type.
3663 if (getLangOpts().CUDA)
3664 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3665 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3666 << Function->getType() << Function->getSourceRange();
3668 }
3669 }
3670
3671 // Instantiate the types of each of the function parameters given the
3672 // explicitly-specified template arguments if we didn't do so earlier.
3673 if (!Proto->hasTrailingReturn() &&
3674 SubstParmTypes(Function->getLocation(), Function->parameters(),
3675 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3676 /*params*/ nullptr, ExtParamInfos))
3678
3679 if (FunctionType) {
3680 auto EPI = Proto->getExtProtoInfo();
3681 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3682 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3683 Function->getLocation(),
3684 Function->getDeclName(),
3685 EPI);
3686 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3688 }
3689
3690 // C++ [temp.arg.explicit]p2:
3691 // Trailing template arguments that can be deduced (14.8.2) may be
3692 // omitted from the list of explicit template-arguments. If all of the
3693 // template arguments can be deduced, they may all be omitted; in this
3694 // case, the empty template argument list <> itself may also be omitted.
3695 //
3696 // Take all of the explicitly-specified arguments and put them into
3697 // the set of deduced template arguments. The partially-substituted
3698 // parameter pack, however, will be set to NULL since the deduction
3699 // mechanism handles the partially-substituted argument pack directly.
3700 Deduced.reserve(TemplateParams->size());
3701 for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3702 const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
3703 if (I == PartiallySubstitutedPackIndex)
3704 Deduced.push_back(DeducedTemplateArgument());
3705 else
3706 Deduced.push_back(Arg);
3707 }
3708
3710}
3711
3712/// Check whether the deduced argument type for a call to a function
3713/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3716 Sema::OriginalCallArg OriginalArg,
3717 QualType DeducedA) {
3718 ASTContext &Context = S.Context;
3719
3720 auto Failed = [&]() -> TemplateDeductionResult {
3721 Info.FirstArg = TemplateArgument(DeducedA);
3722 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3723 Info.CallArgIndex = OriginalArg.ArgIdx;
3724 return OriginalArg.DecomposedParam
3727 };
3728
3729 QualType A = OriginalArg.OriginalArgType;
3730 QualType OriginalParamType = OriginalArg.OriginalParamType;
3731
3732 // Check for type equality (top-level cv-qualifiers are ignored).
3733 if (Context.hasSameUnqualifiedType(A, DeducedA))
3735
3736 // Strip off references on the argument types; they aren't needed for
3737 // the following checks.
3738 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3739 DeducedA = DeducedARef->getPointeeType();
3740 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3741 A = ARef->getPointeeType();
3742
3743 // C++ [temp.deduct.call]p4:
3744 // [...] However, there are three cases that allow a difference:
3745 // - If the original P is a reference type, the deduced A (i.e., the
3746 // type referred to by the reference) can be more cv-qualified than
3747 // the transformed A.
3748 if (const ReferenceType *OriginalParamRef
3749 = OriginalParamType->getAs<ReferenceType>()) {
3750 // We don't want to keep the reference around any more.
3751 OriginalParamType = OriginalParamRef->getPointeeType();
3752
3753 // FIXME: Resolve core issue (no number yet): if the original P is a
3754 // reference type and the transformed A is function type "noexcept F",
3755 // the deduced A can be F.
3756 QualType Tmp;
3757 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
3759
3760 Qualifiers AQuals = A.getQualifiers();
3761 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3762
3763 // Under Objective-C++ ARC, the deduced type may have implicitly
3764 // been given strong or (when dealing with a const reference)
3765 // unsafe_unretained lifetime. If so, update the original
3766 // qualifiers to include this lifetime.
3767 if (S.getLangOpts().ObjCAutoRefCount &&
3768 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3770 (DeducedAQuals.hasConst() &&
3771 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3772 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3773 }
3774
3775 if (AQuals == DeducedAQuals) {
3776 // Qualifiers match; there's nothing to do.
3777 } else if (!DeducedAQuals.compatiblyIncludes(AQuals, S.getASTContext())) {
3778 return Failed();
3779 } else {
3780 // Qualifiers are compatible, so have the argument type adopt the
3781 // deduced argument type's qualifiers as if we had performed the
3782 // qualification conversion.
3783 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3784 }
3785 }
3786
3787 // - The transformed A can be another pointer or pointer to member
3788 // type that can be converted to the deduced A via a function pointer
3789 // conversion and/or a qualification conversion.
3790 //
3791 // Also allow conversions which merely strip __attribute__((noreturn)) from
3792 // function types (recursively).
3793 bool ObjCLifetimeConversion = false;
3794 QualType ResultTy;
3795 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3796 (S.IsQualificationConversion(A, DeducedA, false,
3797 ObjCLifetimeConversion) ||
3798 S.IsFunctionConversion(A, DeducedA, ResultTy)))
3800
3801 // - If P is a class and P has the form simple-template-id, then the
3802 // transformed A can be a derived class of the deduced A. [...]
3803 // [...] Likewise, if P is a pointer to a class of the form
3804 // simple-template-id, the transformed A can be a pointer to a
3805 // derived class pointed to by the deduced A.
3806 if (const PointerType *OriginalParamPtr
3807 = OriginalParamType->getAs<PointerType>()) {
3808 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3809 if (const PointerType *APtr = A->getAs<PointerType>()) {
3810 if (A->getPointeeType()->isRecordType()) {
3811 OriginalParamType = OriginalParamPtr->getPointeeType();
3812 DeducedA = DeducedAPtr->getPointeeType();
3813 A = APtr->getPointeeType();
3814 }
3815 }
3816 }
3817 }
3818
3819 if (Context.hasSameUnqualifiedType(A, DeducedA))
3821
3822 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3823 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3825
3826 return Failed();
3827}
3828
3829/// Find the pack index for a particular parameter index in an instantiation of
3830/// a function template with specific arguments.
3831///
3832/// \return The pack index for whichever pack produced this parameter, or -1
3833/// if this was not produced by a parameter. Intended to be used as the
3834/// ArgumentPackSubstitutionIndex for further substitutions.
3835// FIXME: We should track this in OriginalCallArgs so we don't need to
3836// reconstruct it here.
3837static unsigned getPackIndexForParam(Sema &S,
3838 FunctionTemplateDecl *FunctionTemplate,
3840 unsigned ParamIdx) {
3841 unsigned Idx = 0;
3842 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3843 if (PD->isParameterPack()) {
3844 unsigned NumExpansions =
3845 S.getNumArgumentsInExpansion(PD->getType(), Args).value_or(1);
3846 if (Idx + NumExpansions > ParamIdx)
3847 return ParamIdx - Idx;
3848 Idx += NumExpansions;
3849 } else {
3850 if (Idx == ParamIdx)
3851 return -1; // Not a pack expansion
3852 ++Idx;
3853 }
3854 }
3855
3856 llvm_unreachable("parameter index would not be produced from template");
3857}
3858
3859// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`,
3860// we'll try to instantiate and update its explicit specifier after constraint
3861// checking.
3864 const MultiLevelTemplateArgumentList &SubstArgs,
3865 TemplateDeductionInfo &Info, FunctionTemplateDecl *FunctionTemplate,
3866 ArrayRef<TemplateArgument> DeducedArgs) {
3867 auto GetExplicitSpecifier = [](FunctionDecl *D) {
3868 return isa<CXXConstructorDecl>(D)
3869 ? cast<CXXConstructorDecl>(D)->getExplicitSpecifier()
3870 : cast<CXXConversionDecl>(D)->getExplicitSpecifier();
3871 };
3872 auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) {
3873 isa<CXXConstructorDecl>(D)
3874 ? cast<CXXConstructorDecl>(D)->setExplicitSpecifier(ES)
3875 : cast<CXXConversionDecl>(D)->setExplicitSpecifier(ES);
3876 };
3877
3878 ExplicitSpecifier ES = GetExplicitSpecifier(Specialization);
3879 Expr *ExplicitExpr = ES.getExpr();
3880 if (!ExplicitExpr)
3882 if (!ExplicitExpr->isValueDependent())
3884
3886 S, Info.getLocation(), FunctionTemplate, DeducedArgs,
3888 if (Inst.isInvalid())
3890 Sema::SFINAETrap Trap(S);
3891 const ExplicitSpecifier InstantiatedES =
3892 S.instantiateExplicitSpecifier(SubstArgs, ES);
3893 if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) {
3894 Specialization->setInvalidDecl(true);
3896 }
3897 SetExplicitSpecifier(Specialization, InstantiatedES);
3899}
3900
3902 FunctionTemplateDecl *FunctionTemplate,
3904 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3906 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3907 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
3908 // Unevaluated SFINAE context.
3911 SFINAETrap Trap(*this);
3912
3913 // Enter a new template instantiation context while we instantiate the
3914 // actual function declaration.
3915 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3917 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3919 if (Inst.isInvalid())
3921
3922 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3923
3924 // C++ [temp.deduct.type]p2:
3925 // [...] or if any template argument remains neither deduced nor
3926 // explicitly specified, template argument deduction fails.
3927 bool IsIncomplete = false;
3928 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3930 *this, FunctionTemplate, /*IsDeduced*/ true, Deduced, Info,
3931 SugaredBuilder, CanonicalBuilder, CurrentInstantiationScope,
3932 NumExplicitlySpecified, PartialOverloading ? &IsIncomplete : nullptr);
3934 return Result;
3935
3936 // C++ [temp.deduct.call]p10: [DR1391]
3937 // If deduction succeeds for all parameters that contain
3938 // template-parameters that participate in template argument deduction,
3939 // and all template arguments are explicitly specified, deduced, or
3940 // obtained from default template arguments, remaining parameters are then
3941 // compared with the corresponding arguments. For each remaining parameter
3942 // P with a type that was non-dependent before substitution of any
3943 // explicitly-specified template arguments, if the corresponding argument
3944 // A cannot be implicitly converted to P, deduction fails.
3945 if (CheckNonDependent())
3947
3948 // Form the template argument list from the deduced template arguments.
3949 TemplateArgumentList *SugaredDeducedArgumentList =
3951 TemplateArgumentList *CanonicalDeducedArgumentList =
3952 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3953 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3954
3955 // Substitute the deduced template arguments into the function template
3956 // declaration to produce the function template specialization.
3957 DeclContext *Owner = FunctionTemplate->getDeclContext();
3958 if (FunctionTemplate->getFriendObjectKind())
3959 Owner = FunctionTemplate->getLexicalDeclContext();
3960 FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
3961 // additional check for inline friend,
3962 // ```
3963 // template <class F1> int foo(F1 X);
3964 // template <int A1> struct A {
3965 // template <class F1> friend int foo(F1 X) { return A1; }
3966 // };
3967 // template struct A<1>;
3968 // int a = foo(1.0);
3969 // ```
3970 const FunctionDecl *FDFriend;
3972 FD->isDefined(FDFriend, /*CheckForPendingFriendDefinition*/ true) &&
3974 FD = const_cast<FunctionDecl *>(FDFriend);
3975 Owner = FD->getLexicalDeclContext();
3976 }
3978 FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
3979 /*Final=*/false);
3980 Specialization = cast_or_null<FunctionDecl>(
3981 SubstDecl(FD, Owner, SubstArgs));
3982 if (!Specialization || Specialization->isInvalidDecl())
3984
3985 assert(isSameDeclaration(Specialization->getPrimaryTemplate(),
3987
3988 // If the template argument list is owned by the function template
3989 // specialization, release it.
3990 if (Specialization->getTemplateSpecializationArgs() ==
3991 CanonicalDeducedArgumentList &&
3992 !Trap.hasErrorOccurred())
3993 Info.takeCanonical();
3994
3995 // There may have been an error that did not prevent us from constructing a
3996 // declaration. Mark the declaration invalid and return with a substitution
3997 // failure.
3998 if (Trap.hasErrorOccurred()) {
3999 Specialization->setInvalidDecl(true);
4001 }
4002
4003 // C++2a [temp.deduct]p5
4004 // [...] When all template arguments have been deduced [...] all uses of
4005 // template parameters [...] are replaced with the corresponding deduced
4006 // or default argument values.
4007 // [...] If the function template has associated constraints
4008 // ([temp.constr.decl]), those constraints are checked for satisfaction
4009 // ([temp.constr.constr]). If the constraints are not satisfied, type
4010 // deduction fails.
4011 if (!IsIncomplete) {
4013 Info.getLocation(), Specialization, CanonicalBuilder,
4016
4018 Info.reset(Info.takeSugared(),
4019 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder));
4021 }
4022 }
4023
4024 // We skipped the instantiation of the explicit-specifier during the
4025 // substitution of `FD` before. So, we try to instantiate it back if
4026 // `Specialization` is either a constructor or a conversion function.
4027 if (isa<CXXConstructorDecl, CXXConversionDecl>(Specialization)) {
4030 Info, FunctionTemplate,
4031 DeducedArgs)) {
4033 }
4034 }
4035
4036 if (OriginalCallArgs) {
4037 // C++ [temp.deduct.call]p4:
4038 // In general, the deduction process attempts to find template argument
4039 // values that will make the deduced A identical to A (after the type A
4040 // is transformed as described above). [...]
4041 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
4042 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
4043 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
4044
4045 auto ParamIdx = OriginalArg.ArgIdx;
4046 unsigned ExplicitOffset =
4047 Specialization->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
4048 if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset)
4049 // FIXME: This presumably means a pack ended up smaller than we
4050 // expected while deducing. Should this not result in deduction
4051 // failure? Can it even happen?
4052 continue;
4053
4054 QualType DeducedA;
4055 if (!OriginalArg.DecomposedParam) {
4056 // P is one of the function parameters, just look up its substituted
4057 // type.
4058 DeducedA =
4059 Specialization->getParamDecl(ParamIdx + ExplicitOffset)->getType();
4060 } else {
4061 // P is a decomposed element of a parameter corresponding to a
4062 // braced-init-list argument. Substitute back into P to find the
4063 // deduced A.
4064 QualType &CacheEntry =
4065 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
4066 if (CacheEntry.isNull()) {
4068 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
4069 ParamIdx));
4070 CacheEntry =
4071 SubstType(OriginalArg.OriginalParamType, SubstArgs,
4072 Specialization->getTypeSpecStartLoc(),
4073 Specialization->getDeclName());
4074 }
4075 DeducedA = CacheEntry;
4076 }
4077
4078 if (auto TDK =
4079 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
4081 return TDK;
4082 }
4083 }
4084
4085 // If we suppressed any diagnostics while performing template argument
4086 // deduction, and if we haven't already instantiated this declaration,
4087 // keep track of these diagnostics. They'll be emitted if this specialization
4088 // is actually used.
4089 if (Info.diag_begin() != Info.diag_end()) {
4090 auto [Pos, Inserted] =
4091 SuppressedDiagnostics.try_emplace(Specialization->getCanonicalDecl());
4092 if (Inserted)
4093 Pos->second.append(Info.diag_begin(), Info.diag_end());
4094 }
4095
4097}
4098
4099/// Gets the type of a function for template-argument-deducton
4100/// purposes when it's considered as part of an overload set.
4102 FunctionDecl *Fn) {
4103 // We may need to deduce the return type of the function now.
4104 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
4105 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
4106 return {};
4107
4108 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
4109 if (Method->isImplicitObjectMemberFunction()) {
4110 // An instance method that's referenced in a form that doesn't
4111 // look like a member pointer is just invalid.
4113 return {};
4114
4115 return S.Context.getMemberPointerType(Fn->getType(),
4116 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
4117 }
4118
4119 if (!R.IsAddressOfOperand) return Fn->getType();
4120 return S.Context.getPointerType(Fn->getType());
4121}
4122
4123/// Apply the deduction rules for overload sets.
4124///
4125/// \return the null type if this argument should be treated as an
4126/// undeduced context
4127static QualType
4129 Expr *Arg, QualType ParamType,
4130 bool ParamWasReference,
4131 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4132
4134
4135 OverloadExpr *Ovl = R.Expression;
4136
4137 // C++0x [temp.deduct.call]p4
4138 unsigned TDF = 0;
4139 if (ParamWasReference)
4141 if (R.IsAddressOfOperand)
4142 TDF |= TDF_IgnoreQualifiers;
4143
4144 // C++0x [temp.deduct.call]p6:
4145 // When P is a function type, pointer to function type, or pointer
4146 // to member function type:
4147
4148 if (!ParamType->isFunctionType() &&
4149 !ParamType->isFunctionPointerType() &&
4150 !ParamType->isMemberFunctionPointerType()) {
4151 if (Ovl->hasExplicitTemplateArgs()) {
4152 // But we can still look for an explicit specialization.
4153 if (FunctionDecl *ExplicitSpec =
4155 Ovl, /*Complain=*/false,
4156 /*FoundDeclAccessPair=*/nullptr, FailedTSC))
4157 return GetTypeOfFunction(S, R, ExplicitSpec);
4158 }
4159
4160 DeclAccessPair DAP;
4161 if (FunctionDecl *Viable =
4163 return GetTypeOfFunction(S, R, Viable);
4164
4165 return {};
4166 }
4167
4168 // Gather the explicit template arguments, if any.
4169 TemplateArgumentListInfo ExplicitTemplateArgs;
4170 if (Ovl->hasExplicitTemplateArgs())
4171 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4172 QualType Match;
4173 for (UnresolvedSetIterator I = Ovl->decls_begin(),
4174 E = Ovl->decls_end(); I != E; ++I) {
4175 NamedDecl *D = (*I)->getUnderlyingDecl();
4176
4177 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
4178 // - If the argument is an overload set containing one or more
4179 // function templates, the parameter is treated as a
4180 // non-deduced context.
4181 if (!Ovl->hasExplicitTemplateArgs())
4182 return {};
4183
4184 // Otherwise, see if we can resolve a function type
4185 FunctionDecl *Specialization = nullptr;
4186 TemplateDeductionInfo Info(Ovl->getNameLoc());
4187 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
4190 continue;
4191
4192 D = Specialization;
4193 }
4194
4195 FunctionDecl *Fn = cast<FunctionDecl>(D);
4196 QualType ArgType = GetTypeOfFunction(S, R, Fn);
4197 if (ArgType.isNull()) continue;
4198
4199 // Function-to-pointer conversion.
4200 if (!ParamWasReference && ParamType->isPointerType() &&
4201 ArgType->isFunctionType())
4202 ArgType = S.Context.getPointerType(ArgType);
4203
4204 // - If the argument is an overload set (not containing function
4205 // templates), trial argument deduction is attempted using each
4206 // of the members of the set. If deduction succeeds for only one
4207 // of the overload set members, that member is used as the
4208 // argument value for the deduction. If deduction succeeds for
4209 // more than one member of the overload set the parameter is
4210 // treated as a non-deduced context.
4211
4212 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
4213 // Type deduction is done independently for each P/A pair, and
4214 // the deduced template argument values are then combined.
4215 // So we do not reject deductions which were made elsewhere.
4217 Deduced(TemplateParams->size());
4218 TemplateDeductionInfo Info(Ovl->getNameLoc());
4220 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4221 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4222 /*HasDeducedAnyParam=*/nullptr);
4224 continue;
4225 if (!Match.isNull())
4226 return {};
4227 Match = ArgType;
4228 }
4229
4230 return Match;
4231}
4232
4233/// Perform the adjustments to the parameter and argument types
4234/// described in C++ [temp.deduct.call].
4235///
4236/// \returns true if the caller should not attempt to perform any template
4237/// argument deduction based on this P/A pair because the argument is an
4238/// overloaded function set that could not be resolved.
4240 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4241 QualType &ParamType, QualType &ArgType,
4242 Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
4243 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4244 // C++0x [temp.deduct.call]p3:
4245 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
4246 // are ignored for type deduction.
4247 if (ParamType.hasQualifiers())
4248 ParamType = ParamType.getUnqualifiedType();
4249
4250 // [...] If P is a reference type, the type referred to by P is
4251 // used for type deduction.
4252 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
4253 if (ParamRefType)
4254 ParamType = ParamRefType->getPointeeType();
4255
4256 // Overload sets usually make this parameter an undeduced context,
4257 // but there are sometimes special circumstances. Typically
4258 // involving a template-id-expr.
4259 if (ArgType == S.Context.OverloadTy) {
4260 assert(Arg && "expected a non-null arg expression");
4261 ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType,
4262 ParamRefType != nullptr, FailedTSC);
4263 if (ArgType.isNull())
4264 return true;
4265 }
4266
4267 if (ParamRefType) {
4268 // If the argument has incomplete array type, try to complete its type.
4269 if (ArgType->isIncompleteArrayType()) {
4270 assert(Arg && "expected a non-null arg expression");
4271 ArgType = S.getCompletedType(Arg);
4272 }
4273
4274 // C++1z [temp.deduct.call]p3:
4275 // If P is a forwarding reference and the argument is an lvalue, the type
4276 // "lvalue reference to A" is used in place of A for type deduction.
4277 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
4278 ArgClassification.isLValue()) {
4279 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
4280 ArgType = S.Context.getAddrSpaceQualType(
4282 ArgType = S.Context.getLValueReferenceType(ArgType);
4283 }
4284 } else {
4285 // C++ [temp.deduct.call]p2:
4286 // If P is not a reference type:
4287 // - If A is an array type, the pointer type produced by the
4288 // array-to-pointer standard conversion (4.2) is used in place of
4289 // A for type deduction; otherwise,
4290 // - If A is a function type, the pointer type produced by the
4291 // function-to-pointer standard conversion (4.3) is used in place
4292 // of A for type deduction; otherwise,
4293 if (ArgType->canDecayToPointerType())
4294 ArgType = S.Context.getDecayedType(ArgType);
4295 else {
4296 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
4297 // type are ignored for type deduction.
4298 ArgType = ArgType.getUnqualifiedType();
4299 }
4300 }
4301
4302 // C++0x [temp.deduct.call]p4:
4303 // In general, the deduction process attempts to find template argument
4304 // values that will make the deduced A identical to A (after the type A
4305 // is transformed as described above). [...]
4307
4308 // - If the original P is a reference type, the deduced A (i.e., the
4309 // type referred to by the reference) can be more cv-qualified than
4310 // the transformed A.
4311 if (ParamRefType)
4313 // - The transformed A can be another pointer or pointer to member
4314 // type that can be converted to the deduced A via a qualification
4315 // conversion (4.4).
4316 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
4317 ArgType->isObjCObjectPointerType())
4318 TDF |= TDF_IgnoreQualifiers;
4319 // - If P is a class and P has the form simple-template-id, then the
4320 // transformed A can be a derived class of the deduced A. Likewise,
4321 // if P is a pointer to a class of the form simple-template-id, the
4322 // transformed A can be a pointer to a derived class pointed to by
4323 // the deduced A.
4324 if (isSimpleTemplateIdType(ParamType) ||
4325 (isa<PointerType>(ParamType) &&
4327 ParamType->castAs<PointerType>()->getPointeeType())))
4328 TDF |= TDF_DerivedClass;
4329
4330 return false;
4331}
4332
4333static bool
4335 QualType T);
4336
4338 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4339 QualType ParamType, QualType ArgType,
4340 Expr::Classification ArgClassification, Expr *Arg,
4344 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4345 TemplateSpecCandidateSet *FailedTSC = nullptr);
4346
4347/// Attempt template argument deduction from an initializer list
4348/// deemed to be an argument in a function call.
4350 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
4353 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
4354 unsigned TDF) {
4355 // C++ [temp.deduct.call]p1: (CWG 1591)
4356 // If removing references and cv-qualifiers from P gives
4357 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
4358 // a non-empty initializer list, then deduction is performed instead for
4359 // each element of the initializer list, taking P0 as a function template
4360 // parameter type and the initializer element as its argument
4361 //
4362 // We've already removed references and cv-qualifiers here.
4363 if (!ILE->getNumInits())
4365
4366 QualType ElTy;
4367 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
4368 if (ArrTy)
4369 ElTy = ArrTy->getElementType();
4370 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
4371 // Otherwise, an initializer list argument causes the parameter to be
4372 // considered a non-deduced context
4374 }
4375
4376 // Resolving a core issue: a braced-init-list containing any designators is
4377 // a non-deduced context.
4378 for (Expr *E : ILE->inits())
4379 if (isa<DesignatedInitExpr>(E))
4381
4382 // Deduction only needs to be done for dependent types.
4383 if (ElTy->isDependentType()) {
4384 for (Expr *E : ILE->inits()) {
4386 S, TemplateParams, 0, ElTy, E->getType(),
4387 E->Classify(S.getASTContext()), E, Info, Deduced,
4388 OriginalCallArgs, true, ArgIdx, TDF);
4390 return Result;
4391 }
4392 }
4393
4394 // in the P0[N] case, if N is a non-type template parameter, N is deduced
4395 // from the length of the initializer list.
4396 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
4397 // Determine the array bound is something we can deduce.
4398 if (const NonTypeTemplateParmDecl *NTTP =
4399 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
4400 // We can perform template argument deduction for the given non-type
4401 // template parameter.
4402 // C++ [temp.deduct.type]p13:
4403 // The type of N in the type T[N] is std::size_t.
4405 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
4407 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
4408 /*ArrayBound=*/true, Info, /*PartialOrdering=*/false, Deduced,
4409 /*HasDeducedAnyParam=*/nullptr);
4411 return Result;
4412 }
4413 }
4414
4416}
4417
4418/// Perform template argument deduction per [temp.deduct.call] for a
4419/// single parameter / argument pair.
4421 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4422 QualType ParamType, QualType ArgType,
4423 Expr::Classification ArgClassification, Expr *Arg,
4427 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4428 TemplateSpecCandidateSet *FailedTSC) {
4429
4430 QualType OrigParamType = ParamType;
4431
4432 // If P is a reference type [...]
4433 // If P is a cv-qualified type [...]
4435 S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
4436 ArgClassification, Arg, TDF, FailedTSC))
4438
4439 // If [...] the argument is a non-empty initializer list [...]
4440 if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
4441 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
4442 Deduced, OriginalCallArgs, ArgIdx, TDF);
4443
4444 // [...] the deduction process attempts to find template argument values
4445 // that will make the deduced A identical to A
4446 //
4447 // Keep track of the argument type and corresponding parameter index,
4448 // so we can check for compatibility between the deduced A and A.
4449 if (Arg)
4450 OriginalCallArgs.push_back(
4451 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
4453 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4454 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4455 /*HasDeducedAnyParam=*/nullptr);
4456}
4457
4459 FunctionTemplateDecl *FunctionTemplate,
4460 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4462 bool PartialOverloading, bool AggregateDeductionCandidate,
4463 QualType ObjectType, Expr::Classification ObjectClassification,
4464 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
4465 if (FunctionTemplate->isInvalidDecl())
4467
4468 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4469 unsigned NumParams = Function->getNumParams();
4470 bool HasExplicitObject = false;
4471 int ExplicitObjectOffset = 0;
4472 if (Function->hasCXXExplicitFunctionObjectParameter()) {
4473 HasExplicitObject = true;
4474 ExplicitObjectOffset = 1;
4475 }
4476
4477 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
4478
4479 // C++ [temp.deduct.call]p1:
4480 // Template argument deduction is done by comparing each function template
4481 // parameter type (call it P) with the type of the corresponding argument
4482 // of the call (call it A) as described below.
4483 if (Args.size() < Function->getMinRequiredExplicitArguments() &&
4484 !PartialOverloading)
4486 else if (TooManyArguments(NumParams, Args.size() + ExplicitObjectOffset,
4487 PartialOverloading)) {
4488 const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
4489 if (Proto->isTemplateVariadic())
4490 /* Do nothing */;
4491 else if (!Proto->isVariadic())
4493 }
4494
4495 // The types of the parameters from which we will perform template argument
4496 // deduction.
4497 LocalInstantiationScope InstScope(*this);
4498 TemplateParameterList *TemplateParams
4499 = FunctionTemplate->getTemplateParameters();
4501 SmallVector<QualType, 8> ParamTypes;
4502 unsigned NumExplicitlySpecified = 0;
4503 if (ExplicitTemplateArgs) {
4506 Result = SubstituteExplicitTemplateArguments(
4507 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4508 Info);
4509 });
4511 return Result;
4512
4513 NumExplicitlySpecified = Deduced.size();
4514 } else {
4515 // Just fill in the parameter types from the function declaration.
4516 for (unsigned I = 0; I != NumParams; ++I)
4517 ParamTypes.push_back(Function->getParamDecl(I)->getType());
4518 }
4519
4520 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
4521
4522 // Deduce an argument of type ParamType from an expression with index ArgIdx.
4523 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx,
4524 bool ExplicitObjectArgument) {
4525 // C++ [demp.deduct.call]p1: (DR1391)
4526 // Template argument deduction is done by comparing each function template
4527 // parameter that contains template-parameters that participate in
4528 // template argument deduction ...
4529 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4531
4532 if (ExplicitObjectArgument) {
4533 // ... with the type of the corresponding argument
4535 *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
4536 ObjectClassification,
4537 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4538 /*Decomposed*/ false, ArgIdx, /*TDF*/ 0);
4539 }
4540
4541 // ... with the type of the corresponding argument
4543 *this, TemplateParams, FirstInnerIndex, ParamType,
4544 Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()),
4545 Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false,
4546 ArgIdx, /*TDF*/ 0);
4547 };
4548
4549 // Deduce template arguments from the function parameters.
4550 Deduced.resize(TemplateParams->size());
4551 SmallVector<QualType, 8> ParamTypesForArgChecking;
4552 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4553 ParamIdx != NumParamTypes; ++ParamIdx) {
4554 QualType ParamType = ParamTypes[ParamIdx];
4555
4556 const PackExpansionType *ParamExpansion =
4557 dyn_cast<PackExpansionType>(ParamType);
4558 if (!ParamExpansion) {
4559 // Simple case: matching a function parameter to a function argument.
4560 if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0))
4561 break;
4562
4563 ParamTypesForArgChecking.push_back(ParamType);
4564
4565 if (ParamIdx == 0 && HasExplicitObject) {
4566 if (ObjectType.isNull())
4568
4569 if (auto Result = DeduceCallArgument(ParamType, 0,
4570 /*ExplicitObjectArgument=*/true);
4572 return Result;
4573 continue;
4574 }
4575
4576 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4577 /*ExplicitObjectArgument=*/false);
4579 return Result;
4580
4581 continue;
4582 }
4583
4584 bool IsTrailingPack = ParamIdx + 1 == NumParamTypes;
4585
4586 QualType ParamPattern = ParamExpansion->getPattern();
4587 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
4588 ParamPattern,
4589 AggregateDeductionCandidate && IsTrailingPack);
4590
4591 // C++0x [temp.deduct.call]p1:
4592 // For a function parameter pack that occurs at the end of the
4593 // parameter-declaration-list, the type A of each remaining argument of
4594 // the call is compared with the type P of the declarator-id of the
4595 // function parameter pack. Each comparison deduces template arguments
4596 // for subsequent positions in the template parameter packs expanded by
4597 // the function parameter pack. When a function parameter pack appears
4598 // in a non-deduced context [not at the end of the list], the type of
4599 // that parameter pack is never deduced.
4600 //
4601 // FIXME: The above rule allows the size of the parameter pack to change
4602 // after we skip it (in the non-deduced case). That makes no sense, so
4603 // we instead notionally deduce the pack against N arguments, where N is
4604 // the length of the explicitly-specified pack if it's expanded by the
4605 // parameter pack and 0 otherwise, and we treat each deduction as a
4606 // non-deduced context.
4607 if (IsTrailingPack || PackScope.hasFixedArity()) {
4608 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4609 PackScope.nextPackElement(), ++ArgIdx) {
4610 ParamTypesForArgChecking.push_back(ParamPattern);
4611 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4612 /*ExplicitObjectArgument=*/false);
4614 return Result;
4615 }
4616 } else {
4617 // If the parameter type contains an explicitly-specified pack that we
4618 // could not expand, skip the number of parameters notionally created
4619 // by the expansion.
4620 std::optional<unsigned> NumExpansions =
4621 ParamExpansion->getNumExpansions();
4622 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4623 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4624 ++I, ++ArgIdx) {
4625 ParamTypesForArgChecking.push_back(ParamPattern);
4626 // FIXME: Should we add OriginalCallArgs for these? What if the
4627 // corresponding argument is a list?
4628 PackScope.nextPackElement();
4629 }
4630 } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4631 PackScope.isDeducedFromEarlierParameter()) {
4632 // [temp.deduct.general#3]
4633 // When all template arguments have been deduced
4634 // or obtained from default template arguments, all uses of template
4635 // parameters in the template parameter list of the template are
4636 // replaced with the corresponding deduced or default argument values
4637 //
4638 // If we have a trailing parameter pack, that has been deduced
4639 // previously we substitute the pack here in a similar fashion as
4640 // above with the trailing parameter packs. The main difference here is
4641 // that, in this case we are not processing all of the remaining
4642 // arguments. We are only process as many arguments as we have in
4643 // the already deduced parameter.
4644 std::optional<unsigned> ArgPosAfterSubstitution =
4645 PackScope.getSavedPackSizeIfAllEqual();
4646 if (!ArgPosAfterSubstitution)
4647 continue;
4648
4649 unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4650 for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4651 ParamTypesForArgChecking.push_back(ParamPattern);
4652 if (auto Result =
4653 DeduceCallArgument(ParamPattern, ArgIdx,
4654 /*ExplicitObjectArgument=*/false);
4656 return Result;
4657
4658 PackScope.nextPackElement();
4659 }
4660 }
4661 }
4662
4663 // Build argument packs for each of the parameter packs expanded by this
4664 // pack expansion.
4665 if (auto Result = PackScope.finish();
4667 return Result;
4668 }
4669
4670 // Capture the context in which the function call is made. This is the context
4671 // that is needed when the accessibility of template arguments is checked.
4672 DeclContext *CallingCtx = CurContext;
4673
4676 Result = FinishTemplateArgumentDeduction(
4677 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4678 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
4679 ContextRAII SavedContext(*this, CallingCtx);
4680 return CheckNonDependent(ParamTypesForArgChecking);
4681 });
4682 });
4683 return Result;
4684}
4685
4688 bool AdjustExceptionSpec) {
4689 if (ArgFunctionType.isNull())
4690 return ArgFunctionType;
4691
4692 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4693 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4694 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4695 bool Rebuild = false;
4696
4697 CallingConv CC = FunctionTypeP->getCallConv();
4698 if (EPI.ExtInfo.getCC() != CC) {
4699 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4700 Rebuild = true;
4701 }
4702
4703 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4704 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4705 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4706 Rebuild = true;
4707 }
4708
4709 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4710 ArgFunctionTypeP->hasExceptionSpec())) {
4711 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4712 Rebuild = true;
4713 }
4714
4715 if (!Rebuild)
4716 return ArgFunctionType;
4717
4718 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4719 ArgFunctionTypeP->getParamTypes(), EPI);
4720}
4721
4723 FunctionTemplateDecl *FunctionTemplate,
4724 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4726 bool IsAddressOfFunction) {
4727 if (FunctionTemplate->isInvalidDecl())
4729
4730 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4731 TemplateParameterList *TemplateParams
4732 = FunctionTemplate->getTemplateParameters();
4733 QualType FunctionType = Function->getType();
4734
4735 // Substitute any explicit template arguments.
4736 LocalInstantiationScope InstScope(*this);
4738 unsigned NumExplicitlySpecified = 0;
4739 SmallVector<QualType, 4> ParamTypes;
4740 if (ExplicitTemplateArgs) {
4743 Result = SubstituteExplicitTemplateArguments(
4744 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4745 &FunctionType, Info);
4746 });
4748 return Result;
4749
4750 NumExplicitlySpecified = Deduced.size();
4751 }
4752
4753 // When taking the address of a function, we require convertibility of
4754 // the resulting function type. Otherwise, we allow arbitrary mismatches
4755 // of calling convention and noreturn.
4756 if (!IsAddressOfFunction)
4757 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4758 /*AdjustExceptionSpec*/false);
4759
4760 // Unevaluated SFINAE context.
4763 SFINAETrap Trap(*this);
4764
4765 Deduced.resize(TemplateParams->size());
4766
4767 // If the function has a deduced return type, substitute it for a dependent
4768 // type so that we treat it as a non-deduced context in what follows.
4769 bool HasDeducedReturnType = false;
4770 if (getLangOpts().CPlusPlus14 &&
4771 Function->getReturnType()->getContainedAutoType()) {
4773 HasDeducedReturnType = true;
4774 }
4775
4776 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
4777 unsigned TDF =
4779 // Deduce template arguments from the function type.
4781 *this, TemplateParams, FunctionType, ArgFunctionType, Info, Deduced,
4782 TDF, PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4783 /*HasDeducedAnyParam=*/nullptr);
4785 return Result;
4786 }
4787
4790 Result = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
4791 NumExplicitlySpecified,
4792 Specialization, Info);
4793 });
4795 return Result;
4796
4797 // If the function has a deduced return type, deduce it now, so we can check
4798 // that the deduced function type matches the requested type.
4799 if (HasDeducedReturnType && IsAddressOfFunction &&
4800 Specialization->getReturnType()->isUndeducedType() &&
4803
4804 // [C++26][expr.const]/p17
4805 // An expression or conversion is immediate-escalating if it is not initially
4806 // in an immediate function context and it is [...]
4807 // a potentially-evaluated id-expression that denotes an immediate function.
4808 if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
4809 Specialization->isImmediateEscalating() &&
4810 parentEvaluationContext().isPotentiallyEvaluated() &&
4812 Info.getLocation()))
4814
4815 // Adjust the exception specification of the argument to match the
4816 // substituted and resolved type we just formed. (Calling convention and
4817 // noreturn can't be dependent, so we don't actually need this for them
4818 // right now.)
4819 QualType SpecializationType = Specialization->getType();
4820 if (!IsAddressOfFunction) {
4821 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4822 /*AdjustExceptionSpec*/true);
4823
4824 // Revert placeholder types in the return type back to undeduced types so
4825 // that the comparison below compares the declared return types.
4826 if (HasDeducedReturnType) {
4827 SpecializationType = SubstAutoType(SpecializationType, QualType());
4828 ArgFunctionType = SubstAutoType(ArgFunctionType, QualType());
4829 }
4830 }
4831
4832 // If the requested function type does not match the actual type of the
4833 // specialization with respect to arguments of compatible pointer to function
4834 // types, template argument deduction fails.
4835 if (!ArgFunctionType.isNull()) {
4836 if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
4837 SpecializationType, ArgFunctionType)
4839 SpecializationType, ArgFunctionType)) {
4840 Info.FirstArg = TemplateArgument(SpecializationType);
4841 Info.SecondArg = TemplateArgument(ArgFunctionType);
4843 }
4844 }
4845
4847}
4848
4850 FunctionTemplateDecl *ConversionTemplate, QualType ObjectType,
4851 Expr::Classification ObjectClassification, QualType A,
4853 if (ConversionTemplate->isInvalidDecl())
4855
4856 CXXConversionDecl *ConversionGeneric
4857 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4858
4859 QualType P = ConversionGeneric->getConversionType();
4860 bool IsReferenceP = P->isReferenceType();
4861 bool IsReferenceA = A->isReferenceType();
4862
4863 // C++0x [temp.deduct.conv]p2:
4864 // If P is a reference type, the type referred to by P is used for
4865 // type deduction.
4866 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4867 P = PRef->getPointeeType();
4868
4869 // C++0x [temp.deduct.conv]p4:
4870 // [...] If A is a reference type, the type referred to by A is used
4871 // for type deduction.
4872 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4873 A = ARef->getPointeeType();
4874 // We work around a defect in the standard here: cv-qualifiers are also
4875 // removed from P and A in this case, unless P was a reference type. This
4876 // seems to mostly match what other compilers are doing.
4877 if (!IsReferenceP) {
4878 A = A.getUnqualifiedType();
4879 P = P.getUnqualifiedType();
4880 }
4881
4882 // C++ [temp.deduct.conv]p3:
4883 //
4884 // If A is not a reference type:
4885 } else {
4886 assert(!A->isReferenceType() && "Reference types were handled above");
4887
4888 // - If P is an array type, the pointer type produced by the
4889 // array-to-pointer standard conversion (4.2) is used in place
4890 // of P for type deduction; otherwise,
4891 if (P->isArrayType())
4893 // - If P is a function type, the pointer type produced by the
4894 // function-to-pointer standard conversion (4.3) is used in
4895 // place of P for type deduction; otherwise,
4896 else if (P->isFunctionType())
4898 // - If P is a cv-qualified type, the top level cv-qualifiers of
4899 // P's type are ignored for type deduction.
4900 else
4901 P = P.getUnqualifiedType();
4902
4903 // C++0x [temp.deduct.conv]p4:
4904 // If A is a cv-qualified type, the top level cv-qualifiers of A's
4905 // type are ignored for type deduction. If A is a reference type, the type
4906 // referred to by A is used for type deduction.
4907 A = A.getUnqualifiedType();
4908 }
4909
4910 // Unevaluated SFINAE context.
4913 SFINAETrap Trap(*this);
4914
4915 // C++ [temp.deduct.conv]p1:
4916 // Template argument deduction is done by comparing the return
4917 // type of the template conversion function (call it P) with the
4918 // type that is required as the result of the conversion (call it
4919 // A) as described in 14.8.2.4.
4920 TemplateParameterList *TemplateParams
4921 = ConversionTemplate->getTemplateParameters();
4923 Deduced.resize(TemplateParams->size());
4924
4925 // C++0x [temp.deduct.conv]p4:
4926 // In general, the deduction process attempts to find template
4927 // argument values that will make the deduced A identical to
4928 // A. However, there are two cases that allow a difference:
4929 unsigned TDF = 0;
4930 // - If the original A is a reference type, A can be more
4931 // cv-qualified than the deduced A (i.e., the type referred to
4932 // by the reference)
4933 if (IsReferenceA)
4935 // - The deduced A can be another pointer or pointer to member
4936 // type that can be converted to A via a qualification
4937 // conversion.
4938 //
4939 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4940 // both P and A are pointers or member pointers. In this case, we
4941 // just ignore cv-qualifiers completely).
4942 if ((P->isPointerType() && A->isPointerType()) ||
4943 (P->isMemberPointerType() && A->isMemberPointerType()))
4944 TDF |= TDF_IgnoreQualifiers;
4945
4947 if (ConversionGeneric->isExplicitObjectMemberFunction()) {
4948 QualType ParamType = ConversionGeneric->getParamDecl(0)->getType();
4951 *this, TemplateParams, getFirstInnerIndex(ConversionTemplate),
4952 ParamType, ObjectType, ObjectClassification,
4953 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4954 /*Decomposed*/ false, 0, /*TDF*/ 0);
4956 return Result;
4957 }
4958
4960 *this, TemplateParams, P, A, Info, Deduced, TDF,
4961 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4962 /*HasDeducedAnyParam=*/nullptr);
4964 return Result;
4965
4966 // Create an Instantiation Scope for finalizing the operator.
4967 LocalInstantiationScope InstScope(*this);
4968 // Finish template argument deduction.
4969 FunctionDecl *ConversionSpecialized = nullptr;
4972 Result = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
4973 ConversionSpecialized, Info,
4974 &OriginalCallArgs);
4975 });
4976 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
4977 return Result;
4978}
4979
4982 TemplateArgumentListInfo *ExplicitTemplateArgs,
4985 bool IsAddressOfFunction) {
4986 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
4987 QualType(), Specialization, Info,
4988 IsAddressOfFunction);
4989}
4990
4991namespace {
4992 struct DependentAuto { bool IsPack; };
4993
4994 /// Substitute the 'auto' specifier or deduced template specialization type
4995 /// specifier within a type for a given replacement type.
4996 class SubstituteDeducedTypeTransform :
4997 public TreeTransform<SubstituteDeducedTypeTransform> {
4998 QualType Replacement;
4999 bool ReplacementIsPack;
5000 bool UseTypeSugar;
5002
5003 public:
5004 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
5005 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5006 ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
5007
5008 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
5009 bool UseTypeSugar = true)
5010 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5011 Replacement(Replacement), ReplacementIsPack(false),
5012 UseTypeSugar(UseTypeSugar) {}
5013
5014 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
5015 assert(isa<TemplateTypeParmType>(Replacement) &&
5016 "unexpected unsugared replacement kind");
5017 QualType Result = Replacement;
5019 NewTL.setNameLoc(TL.getNameLoc());
5020 return Result;
5021 }
5022
5023 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
5024 // If we're building the type pattern to deduce against, don't wrap the
5025 // substituted type in an AutoType. Certain template deduction rules
5026 // apply only when a template type parameter appears directly (and not if
5027 // the parameter is found through desugaring). For instance:
5028 // auto &&lref = lvalue;
5029 // must transform into "rvalue reference to T" not "rvalue reference to
5030 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
5031 //
5032 // FIXME: Is this still necessary?
5033 if (!UseTypeSugar)
5034 return TransformDesugared(TLB, TL);
5035
5036 QualType Result = SemaRef.Context.getAutoType(
5037 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
5038 ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(),
5040 auto NewTL = TLB.push<AutoTypeLoc>(Result);
5041 NewTL.copy(TL);
5042 return Result;
5043 }
5044
5045 QualType TransformDeducedTemplateSpecializationType(
5047 if (!UseTypeSugar)
5048 return TransformDesugared(TLB, TL);
5049
5050 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
5052 Replacement, Replacement.isNull());
5053 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5054 NewTL.setNameLoc(TL.getNameLoc());
5055 return Result;
5056 }
5057
5058 ExprResult TransformLambdaExpr(LambdaExpr *E) {
5059 // Lambdas never need to be transformed.
5060 return E;
5061 }
5062 bool TransformExceptionSpec(SourceLocation Loc,
5064 SmallVectorImpl<QualType> &Exceptions,
5065 bool &Changed) {
5066 if (ESI.Type == EST_Uninstantiated) {
5067 ESI.instantiate();
5068 Changed = true;
5069 }
5070 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
5071 }
5072
5073 QualType Apply(TypeLoc TL) {
5074 // Create some scratch storage for the transformed type locations.
5075 // FIXME: We're just going to throw this information away. Don't build it.
5076 TypeLocBuilder TLB;
5077 TLB.reserve(TL.getFullDataSize());
5078 return TransformType(TLB, TL);
5079 }
5080 };
5081
5082} // namespace
5083
5086 QualType Deduced) {
5087 ConstraintSatisfaction Satisfaction;
5088 ConceptDecl *Concept = Type.getTypeConstraintConcept();
5089 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
5090 TypeLoc.getRAngleLoc());
5091 TemplateArgs.addArgument(
5094 Deduced, TypeLoc.getNameLoc())));
5095 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
5096 TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
5097
5098 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
5100 Concept, SourceLocation(), TemplateArgs, /*DefaultArgs=*/{},
5101 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
5102 return true;
5103 MultiLevelTemplateArgumentList MLTAL(Concept, CanonicalConverted,
5104 /*Final=*/false);
5105 // Build up an EvaluationContext with an ImplicitConceptSpecializationDecl so
5106 // that the template arguments of the constraint can be preserved. For
5107 // example:
5108 //
5109 // template <class T>
5110 // concept C = []<D U = void>() { return true; }();
5111 //
5112 // We need the argument for T while evaluating type constraint D in
5113 // building the CallExpr to the lambda.
5117 S.getASTContext(), Concept->getDeclContext(), Concept->getLocation(),
5118 CanonicalConverted));
5119 if (S.CheckConstraintSatisfaction(Concept, {Concept->getConstraintExpr()},
5121 Satisfaction))
5122 return true;
5123 if (!Satisfaction.IsSatisfied) {
5124 std::string Buf;
5125 llvm::raw_string_ostream OS(Buf);
5126 OS << "'" << Concept->getName();
5127 if (TypeLoc.hasExplicitTemplateArgs()) {
5129 OS, Type.getTypeConstraintArguments(), S.getPrintingPolicy(),
5130 Type.getTypeConstraintConcept()->getTemplateParameters());
5131 }
5132 OS << "'";
5133 S.Diag(TypeLoc.getConceptNameLoc(),
5134 diag::err_placeholder_constraints_not_satisfied)
5135 << Deduced << Buf << TypeLoc.getLocalSourceRange();
5136 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
5137 return true;
5138 }
5139 return false;
5140}
5141
5144 TemplateDeductionInfo &Info, bool DependentDeduction,
5145 bool IgnoreConstraints,
5146 TemplateSpecCandidateSet *FailedTSC) {
5147 assert(DependentDeduction || Info.getDeducedDepth() == 0);
5148 if (Init->containsErrors())
5150
5151 const AutoType *AT = Type.getType()->getContainedAutoType();
5152 assert(AT);
5153
5154 if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
5155 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
5156 if (NonPlaceholder.isInvalid())
5158 Init = NonPlaceholder.get();
5159 }
5160
5161 DependentAuto DependentResult = {
5162 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
5163
5164 if (!DependentDeduction &&
5165 (Type.getType()->isDependentType() || Init->isTypeDependent() ||
5166 Init->containsUnexpandedParameterPack())) {
5167 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5168 assert(!Result.isNull() && "substituting DependentTy can't fail");
5170 }
5171
5172 // Make sure that we treat 'char[]' equaly as 'char*' in C23 mode.
5173 auto *String = dyn_cast<StringLiteral>(Init);
5174 if (getLangOpts().C23 && String && Type.getType()->isArrayType()) {
5175 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5176 TypeLoc TL = TypeLoc(Init->getType(), Type.getOpaqueData());
5177 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(TL);
5178 assert(!Result.isNull() && "substituting DependentTy can't fail");
5180 }
5181
5182 // Emit a warning if 'auto*' is used in pedantic and in C23 mode.
5183 if (getLangOpts().C23 && Type.getType()->isPointerType()) {
5184 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5185 }
5186
5187 auto *InitList = dyn_cast<InitListExpr>(Init);
5188 if (!getLangOpts().CPlusPlus && InitList) {
5189 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c)
5190 << (int)AT->getKeyword() << getLangOpts().C23;
5192 }
5193
5194 // Deduce type of TemplParam in Func(Init)
5196 Deduced.resize(1);
5197
5198 // If deduction failed, don't diagnose if the initializer is dependent; it
5199 // might acquire a matching type in the instantiation.
5200 auto DeductionFailed = [&](TemplateDeductionResult TDK) {
5201 if (Init->isTypeDependent()) {
5202 Result =
5203 SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5204 assert(!Result.isNull() && "substituting DependentTy can't fail");
5206 }
5207 return TDK;
5208 };
5209
5210 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
5211
5213 // If this is a 'decltype(auto)' specifier, do the decltype dance.
5214 if (AT->isDecltypeAuto()) {
5215 if (InitList) {
5216 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
5218 }
5219
5221 assert(!DeducedType.isNull());
5222 } else {
5223 LocalInstantiationScope InstScope(*this);
5224
5225 // Build template<class TemplParam> void Func(FuncParam);
5226 SourceLocation Loc = Init->getExprLoc();
5228 Context, nullptr, SourceLocation(), Loc, Info.getDeducedDepth(), 0,
5229 nullptr, false, false, false);
5230 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
5231 NamedDecl *TemplParamPtr = TemplParam;
5233 Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
5234
5235 if (InitList) {
5236 // Notionally, we substitute std::initializer_list<T> for 'auto' and
5237 // deduce against that. Such deduction only succeeds if removing
5238 // cv-qualifiers and references results in std::initializer_list<T>.
5239 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
5241
5242 SourceRange DeducedFromInitRange;
5243 for (Expr *Init : InitList->inits()) {
5244 // Resolving a core issue: a braced-init-list containing any designators
5245 // is a non-deduced context.
5246 if (isa<DesignatedInitExpr>(Init))
5249 *this, TemplateParamsSt.get(), 0, TemplArg, Init->getType(),
5250 Init->Classify(getASTContext()), Init, Info, Deduced,
5251 OriginalCallArgs,
5252 /*Decomposed=*/true,
5253 /*ArgIdx=*/0, /*TDF=*/0);
5256 Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction)
5257 << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
5258 << Init->getSourceRange();
5259 return DeductionFailed(TemplateDeductionResult::AlreadyDiagnosed);
5260 }
5261 return DeductionFailed(TDK);
5262 }
5263
5264 if (DeducedFromInitRange.isInvalid() &&
5265 Deduced[0].getKind() != TemplateArgument::Null)
5266 DeducedFromInitRange = Init->getSourceRange();
5267 }
5268 } else {
5269 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
5270 Diag(Loc, diag::err_auto_bitfield);
5272 }
5273 QualType FuncParam =
5274 SubstituteDeducedTypeTransform(*this, TemplArg).Apply(Type);
5275 assert(!FuncParam.isNull() &&
5276 "substituting template parameter for 'auto' failed");
5278 *this, TemplateParamsSt.get(), 0, FuncParam, Init->getType(),
5279 Init->Classify(getASTContext()), Init, Info, Deduced,
5280 OriginalCallArgs,
5281 /*Decomposed=*/false, /*ArgIdx=*/0, /*TDF=*/0, FailedTSC);
5283 return DeductionFailed(TDK);
5284 }
5285
5286 // Could be null if somehow 'auto' appears in a non-deduced context.
5287 if (Deduced[0].getKind() != TemplateArgument::Type)
5288 return DeductionFailed(TemplateDeductionResult::Incomplete);
5289 DeducedType = Deduced[0].getAsType();
5290
5291 if (InitList) {
5293 if (DeducedType.isNull())
5295 }
5296 }
5297
5298 if (!Result.isNull()) {
5300 Info.FirstArg = Result;
5301 Info.SecondArg = DeducedType;
5302 return DeductionFailed(TemplateDeductionResult::Inconsistent);
5303 }
5305 }
5306
5307 if (AT->isConstrained() && !IgnoreConstraints &&
5309 *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType))
5311
5312 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
5313 if (Result.isNull())
5315
5316 // Check that the deduced argument type is compatible with the original
5317 // argument type per C++ [temp.deduct.call]p4.
5318 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
5319 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
5320 assert((bool)InitList == OriginalArg.DecomposedParam &&
5321 "decomposed non-init-list in auto deduction?");
5322 if (auto TDK =
5323 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
5325 Result = QualType();
5326 return DeductionFailed(TDK);
5327 }
5328 }
5329
5331}
5332
5334 QualType TypeToReplaceAuto) {
5335 assert(TypeToReplaceAuto != Context.DependentTy);
5336 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5337 .TransformType(TypeWithAuto);
5338}
5339
5341 QualType TypeToReplaceAuto) {
5342 assert(TypeToReplaceAuto != Context.DependentTy);
5343 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5344 .TransformType(TypeWithAuto);
5345}
5346
5348 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5349 .TransformType(TypeWithAuto);
5350}
5351
5354 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5355 .TransformType(TypeWithAuto);
5356}
5357
5359 QualType TypeToReplaceAuto) {
5360 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5361 /*UseTypeSugar*/ false)
5362 .TransformType(TypeWithAuto);
5363}
5364
5366 QualType TypeToReplaceAuto) {
5367 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5368 /*UseTypeSugar*/ false)
5369 .TransformType(TypeWithAuto);
5370}
5371
5373 const Expr *Init) {
5374 if (isa<InitListExpr>(Init))
5375 Diag(VDecl->getLocation(),
5376 VDecl->isInitCapture()
5377 ? diag::err_init_capture_deduction_failure_from_init_list
5378 : diag::err_auto_var_deduction_failure_from_init_list)
5379 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
5380 else
5381 Diag(VDecl->getLocation(),
5382 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
5383 : diag::err_auto_var_deduction_failure)
5384 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5385 << Init->getSourceRange();
5386}
5387
5389 bool Diagnose) {
5390 assert(FD->getReturnType()->isUndeducedType());
5391
5392 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
5393 // within the return type from the call operator's type.
5395 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5396 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5397
5398 // For a generic lambda, instantiate the call operator if needed.
5399 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5401 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5402 if (!CallOp || CallOp->isInvalidDecl())
5403 return true;
5404
5405 // We might need to deduce the return type by instantiating the definition
5406 // of the operator() function.
5407 if (CallOp->getReturnType()->isUndeducedType()) {
5410 });
5411 }
5412 }
5413
5414 if (CallOp->isInvalidDecl())
5415 return true;
5416 assert(!CallOp->getReturnType()->isUndeducedType() &&
5417 "failed to deduce lambda return type");
5418
5419 // Build the new return type from scratch.
5420 CallingConv RetTyCC = FD->getReturnType()
5421 ->getPointeeType()
5422 ->castAs<FunctionType>()
5423 ->getCallConv();
5425 CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
5426 if (FD->getReturnType()->getAs<PointerType>())
5427 RetType = Context.getPointerType(RetType);
5428 else {
5429 assert(FD->getReturnType()->getAs<BlockPointerType>());
5430 RetType = Context.getBlockPointerType(RetType);
5431 }
5433 return false;
5434 }
5435
5439 });
5440 }
5441
5442 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
5443 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
5444 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
5445 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
5446 }
5447
5448 return StillUndeduced;
5449}
5450
5453 assert(FD->isImmediateEscalating());
5454
5456 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5457 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5458
5459 // For a generic lambda, instantiate the call operator if needed.
5460 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5462 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5463 if (!CallOp || CallOp->isInvalidDecl())
5464 return true;
5466 Loc, [&] { InstantiateFunctionDefinition(Loc, CallOp); });
5467 }
5468 return CallOp->isInvalidDecl();
5469 }
5470
5473 Loc, [&] { InstantiateFunctionDefinition(Loc, FD); });
5474 }
5475 return false;
5476}
5477
5479 const CXXMethodDecl *Method,
5480 QualType RawType,
5481 bool IsOtherRvr) {
5482 // C++20 [temp.func.order]p3.1, p3.2:
5483 // - The type X(M) is "rvalue reference to cv A" if the optional
5484 // ref-qualifier of M is && or if M has no ref-qualifier and the
5485 // positionally-corresponding parameter of the other transformed template
5486 // has rvalue reference type; if this determination depends recursively
5487 // upon whether X(M) is an rvalue reference type, it is not considered to
5488 // have rvalue reference type.
5489 //
5490 // - Otherwise, X(M) is "lvalue reference to cv A".
5491 assert(Method && !Method->isExplicitObjectMemberFunction() &&
5492 "expected a member function with no explicit object parameter");
5493
5494 RawType = Context.getQualifiedType(RawType, Method->getMethodQualifiers());
5495 if (Method->getRefQualifier() == RQ_RValue ||
5496 (IsOtherRvr && Method->getRefQualifier() == RQ_None))
5497 return Context.getRValueReferenceType(RawType);
5498 return Context.getLValueReferenceType(RawType);
5499}
5500
5502 Sema &S, FunctionTemplateDecl *FTD, int ArgIdx, QualType P, QualType A,
5503 ArrayRef<TemplateArgument> DeducedArgs, bool CheckConsistency) {
5504 MultiLevelTemplateArgumentList MLTAL(FTD, DeducedArgs,
5505 /*Final=*/true);
5507 S, ArgIdx != -1 ? ::getPackIndexForParam(S, FTD, MLTAL, ArgIdx) : -1);
5508 bool IsIncompleteSubstitution = false;
5509 // FIXME: A substitution can be incomplete on a non-structural part of the
5510 // type. Use the canonical type for now, until the TemplateInstantiator can
5511 // deal with that.
5512 QualType InstP = S.SubstType(P.getCanonicalType(), MLTAL, FTD->getLocation(),
5513 FTD->getDeclName(), &IsIncompleteSubstitution);
5514 if (InstP.isNull() && !IsIncompleteSubstitution)
5516 if (!CheckConsistency)
5518 if (IsIncompleteSubstitution)
5520
5521 // [temp.deduct.call]/4 - Check we produced a consistent deduction.
5522 // This handles just the cases that can appear when partial ordering.
5523 if (auto *PA = dyn_cast<PackExpansionType>(A);
5524 PA && !isa<PackExpansionType>(InstP))
5525 A = PA->getPattern();
5526 if (!S.Context.hasSameType(
5531}
5532
5533template <class T>
5535 Sema &S, FunctionTemplateDecl *FTD,
5540 Sema::SFINAETrap Trap(S);
5541
5542 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(FTD));
5543
5544 // C++26 [temp.deduct.type]p2:
5545 // [...] or if any template argument remains neither deduced nor
5546 // explicitly specified, template argument deduction fails.
5547 bool IsIncomplete = false;
5548 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
5550 S, FTD, /*IsDeduced=*/true, Deduced, Info, SugaredBuilder,
5551 CanonicalBuilder, /*CurrentInstantiationScope=*/nullptr,
5552 /*NumAlreadyConverted=*/0, &IsIncomplete);
5554 return Result;
5555
5556 // Form the template argument list from the deduced template arguments.
5557 TemplateArgumentList *SugaredDeducedArgumentList =
5558 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
5559 TemplateArgumentList *CanonicalDeducedArgumentList =
5560 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
5561
5562 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
5563
5564 // Substitute the deduced template arguments into the argument
5565 // and verify that the instantiated argument is both valid
5566 // and equivalent to the parameter.
5567 LocalInstantiationScope InstScope(S);
5568
5569 if (auto TDR = CheckDeductionConsistency(S, FTD, SugaredBuilder);
5571 return TDR;
5572
5575}
5576
5577/// Determine whether the function template \p FT1 is at least as
5578/// specialized as \p FT2.
5582 ArrayRef<QualType> Args1, ArrayRef<QualType> Args2, bool Args1Offset) {
5583 FunctionDecl *FD1 = FT1->getTemplatedDecl();
5584 FunctionDecl *FD2 = FT2->getTemplatedDecl();
5585 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
5586 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
5587 assert(Proto1 && Proto2 && "Function templates must have prototypes");
5588
5589 // C++26 [temp.deduct.partial]p3:
5590 // The types used to determine the ordering depend on the context in which
5591 // the partial ordering is done:
5592 // - In the context of a function call, the types used are those function
5593 // parameter types for which the function call has arguments.
5594 // - In the context of a call to a conversion operator, the return types
5595 // of the conversion function templates are used.
5596 // - In other contexts (14.6.6.2) the function template's function type
5597 // is used.
5598
5599 if (TPOC == TPOC_Other) {
5600 // We wouldn't be partial ordering these candidates if these didn't match.
5601 assert(Proto1->getMethodQuals() == Proto2->getMethodQuals() &&
5602 Proto1->getRefQualifier() == Proto2->getRefQualifier() &&
5603 Proto1->isVariadic() == Proto2->isVariadic() &&
5604 "shouldn't partial order functions with different qualifiers in a "
5605 "context where the function type is used");
5606
5607 assert(Args1.empty() && Args2.empty() &&
5608 "Only call context should have arguments");
5609 Args1 = Proto1->getParamTypes();
5610 Args2 = Proto2->getParamTypes();
5611 }
5612
5613 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
5614 SmallVector<DeducedTemplateArgument, 4> Deduced(TemplateParams->size());
5616
5617 bool HasDeducedAnyParamFromReturnType = false;
5618 if (TPOC != TPOC_Call) {
5620 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
5621 Info, Deduced, TDF_None, PartialOrderingKind::Call,
5622 /*DeducedFromArrayBound=*/false,
5623 &HasDeducedAnyParamFromReturnType) !=
5625 return false;
5626 }
5627
5628 llvm::SmallBitVector HasDeducedParam;
5629 if (TPOC != TPOC_Conversion) {
5630 HasDeducedParam.resize(Args2.size());
5631 if (DeduceTemplateArguments(S, TemplateParams, Args2, Args1, Info, Deduced,
5632 TDF_None, PartialOrderingKind::Call,
5633 /*HasDeducedAnyParam=*/nullptr,
5634 &HasDeducedParam) !=
5636 return false;
5637 }
5638
5639 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
5641 S, Info.getLocation(), FT2, DeducedArgs,
5643 if (Inst.isInvalid())
5644 return false;
5645
5646 bool AtLeastAsSpecialized;
5648 AtLeastAsSpecialized =
5649 ::FinishTemplateArgumentDeduction(
5650 S, FT2, Deduced, Info,
5651 [&](Sema &S, FunctionTemplateDecl *FTD,
5652 ArrayRef<TemplateArgument> DeducedArgs) {
5653 // As a provisional fix for a core issue that does not
5654 // exist yet, which may be related to CWG2160, only check the
5655 // consistency of parameters and return types which participated
5656 // in deduction. We will still try to substitute them though.
5657 if (TPOC != TPOC_Call) {
5658 if (auto TDR = ::CheckDeductionConsistency(
5659 S, FTD, /*ArgIdx=*/-1, Proto2->getReturnType(),
5660 Proto1->getReturnType(), DeducedArgs,
5661 /*CheckConsistency=*/HasDeducedAnyParamFromReturnType);
5662 TDR != TemplateDeductionResult::Success)
5663 return TDR;
5664 }
5665
5666 if (TPOC == TPOC_Conversion)
5667 return TemplateDeductionResult::Success;
5668
5669 return ::DeduceForEachType(
5670 S, TemplateParams, Args2, Args1, Info, Deduced,
5671 PartialOrderingKind::Call, /*FinishingDeduction=*/true,
5672 [&](Sema &S, TemplateParameterList *, int ParamIdx,
5673 int ArgIdx, QualType P, QualType A,
5674 TemplateDeductionInfo &Info,
5675 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5676 PartialOrderingKind) {
5677 if (ArgIdx != -1)
5678 ArgIdx -= Args1Offset;
5679 return ::CheckDeductionConsistency(
5680 S, FTD, ArgIdx, P, A, DeducedArgs,
5681 /*CheckConsistency=*/HasDeducedParam[ParamIdx]);
5682 });
5684 });
5685 if (!AtLeastAsSpecialized)
5686 return false;
5687
5688 // C++0x [temp.deduct.partial]p11:
5689 // In most cases, all template parameters must have values in order for
5690 // deduction to succeed, but for partial ordering purposes a template
5691 // parameter may remain without a value provided it is not used in the
5692 // types being used for partial ordering. [ Note: a template parameter used
5693 // in a non-deduced context is considered used. -end note]
5694 unsigned ArgIdx = 0, NumArgs = Deduced.size();
5695 for (; ArgIdx != NumArgs; ++ArgIdx)
5696 if (Deduced[ArgIdx].isNull())
5697 break;
5698
5699 if (ArgIdx == NumArgs) {
5700 // All template arguments were deduced. FT1 is at least as specialized
5701 // as FT2.
5702 return true;
5703 }
5704
5705 // Figure out which template parameters were used.
5706 llvm::SmallBitVector UsedParameters(TemplateParams->size());
5707 switch (TPOC) {
5708 case TPOC_Call:
5709 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
5710 ::MarkUsedTemplateParameters(S.Context, Args2[I], /*OnlyDeduced=*/false,
5711 TemplateParams->getDepth(), UsedParameters);
5712 break;
5713
5714 case TPOC_Conversion:
5715 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(),
5716 /*OnlyDeduced=*/false,
5717 TemplateParams->getDepth(), UsedParameters);
5718 break;
5719
5720 case TPOC_Other:
5721 // We do not deduce template arguments from the exception specification
5722 // when determining the primary template of a function template
5723 // specialization or when taking the address of a function template.
5724 // Therefore, we do not mark template parameters in the exception
5725 // specification as used during partial ordering to prevent the following
5726 // from being ambiguous:
5727 //
5728 // template<typename T, typename U>
5729 // void f(U) noexcept(noexcept(T())); // #1
5730 //
5731 // template<typename T>
5732 // void f(T*) noexcept; // #2
5733 //
5734 // template<>
5735 // void f<int>(int*) noexcept; // explicit specialization of #2
5736 //
5737 // Although there is no corresponding wording in the standard, this seems
5738 // to be the intended behavior given the definition of
5739 // 'deduction substitution loci' in [temp.deduct].
5741 S.Context,
5743 /*OnlyDeduced=*/false, TemplateParams->getDepth(), UsedParameters);
5744 break;
5745 }
5746
5747 for (; ArgIdx != NumArgs; ++ArgIdx)
5748 // If this argument had no value deduced but was used in one of the types
5749 // used for partial ordering, then deduction fails.
5750 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
5751 return false;
5752
5753 return true;
5754}
5755
5758 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
5759 QualType RawObj1Ty, QualType RawObj2Ty, bool Reversed) {
5762 const FunctionDecl *FD1 = FT1->getTemplatedDecl();
5763 const FunctionDecl *FD2 = FT2->getTemplatedDecl();
5764 bool ShouldConvert1 = false;
5765 bool ShouldConvert2 = false;
5766 bool Args1Offset = false;
5767 bool Args2Offset = false;
5768 QualType Obj1Ty;
5769 QualType Obj2Ty;
5770 if (TPOC == TPOC_Call) {
5771 const FunctionProtoType *Proto1 =
5772 FD1->getType()->castAs<FunctionProtoType>();
5773 const FunctionProtoType *Proto2 =
5774 FD2->getType()->castAs<FunctionProtoType>();
5775
5776 // - In the context of a function call, the function parameter types are
5777 // used.
5778 const CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
5779 const CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
5780 // C++20 [temp.func.order]p3
5781 // [...] Each function template M that is a member function is
5782 // considered to have a new first parameter of type
5783 // X(M), described below, inserted in its function parameter list.
5784 //
5785 // Note that we interpret "that is a member function" as
5786 // "that is a member function with no expicit object argument".
5787 // Otherwise the ordering rules for methods with expicit objet arguments
5788 // against anything else make no sense.
5789
5790 bool NonStaticMethod1 = Method1 && !Method1->isStatic(),
5791 NonStaticMethod2 = Method2 && !Method2->isStatic();
5792
5793 auto Params1Begin = Proto1->param_type_begin(),
5794 Params2Begin = Proto2->param_type_begin();
5795
5796 size_t NumComparedArguments = NumCallArguments1;
5797
5798 if (auto OO = FD1->getOverloadedOperator();
5799 (NonStaticMethod1 && NonStaticMethod2) ||
5800 (OO != OO_None && OO != OO_Call && OO != OO_Subscript)) {
5801 ShouldConvert1 =
5802 NonStaticMethod1 && !Method1->hasCXXExplicitFunctionObjectParameter();
5803 ShouldConvert2 =
5804 NonStaticMethod2 && !Method2->hasCXXExplicitFunctionObjectParameter();
5805 NumComparedArguments += 1;
5806
5807 if (ShouldConvert1) {
5808 bool IsRValRef2 =
5809 ShouldConvert2
5810 ? Method2->getRefQualifier() == RQ_RValue
5811 : Proto2->param_type_begin()[0]->isRValueReferenceType();
5812 // Compare 'this' from Method1 against first parameter from Method2.
5813 Obj1Ty = GetImplicitObjectParameterType(this->Context, Method1,
5814 RawObj1Ty, IsRValRef2);
5815 Args1.push_back(Obj1Ty);
5816 Args1Offset = true;
5817 }
5818 if (ShouldConvert2) {
5819 bool IsRValRef1 =
5820 ShouldConvert1
5821 ? Method1->getRefQualifier() == RQ_RValue
5822 : Proto1->param_type_begin()[0]->isRValueReferenceType();
5823 // Compare 'this' from Method2 against first parameter from Method1.
5824 Obj2Ty = GetImplicitObjectParameterType(this->Context, Method2,
5825 RawObj2Ty, IsRValRef1);
5826 Args2.push_back(Obj2Ty);
5827 Args2Offset = true;
5828 }
5829 } else {
5830 if (NonStaticMethod1 && Method1->hasCXXExplicitFunctionObjectParameter())
5831 Params1Begin += 1;
5832 if (NonStaticMethod2 && Method2->hasCXXExplicitFunctionObjectParameter())
5833 Params2Begin += 1;
5834 }
5835 Args1.insert(Args1.end(), Params1Begin, Proto1->param_type_end());
5836 Args2.insert(Args2.end(), Params2Begin, Proto2->param_type_end());
5837
5838 // C++ [temp.func.order]p5:
5839 // The presence of unused ellipsis and default arguments has no effect on
5840 // the partial ordering of function templates.
5841 Args1.resize(std::min(Args1.size(), NumComparedArguments));
5842 Args2.resize(std::min(Args2.size(), NumComparedArguments));
5843
5844 if (Reversed)
5845 std::reverse(Args2.begin(), Args2.end());
5846 } else {
5847 assert(!Reversed && "Only call context could have reversed arguments");
5848 }
5849 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, Args1,
5850 Args2, Args2Offset);
5851 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, Args2,
5852 Args1, Args1Offset);
5853 // C++ [temp.deduct.partial]p10:
5854 // F is more specialized than G if F is at least as specialized as G and G
5855 // is not at least as specialized as F.
5856 if (Better1 != Better2) // We have a clear winner
5857 return Better1 ? FT1 : FT2;
5858
5859 if (!Better1 && !Better2) // Neither is better than the other
5860 return nullptr;
5861
5862 // C++ [temp.deduct.partial]p11:
5863 // ... and if G has a trailing function parameter pack for which F does not
5864 // have a corresponding parameter, and if F does not have a trailing
5865 // function parameter pack, then F is more specialized than G.
5866
5867 SmallVector<QualType> Param1;
5868 Param1.reserve(FD1->param_size() + ShouldConvert1);
5869 if (ShouldConvert1)
5870 Param1.push_back(Obj1Ty);
5871 for (const auto &P : FD1->parameters())
5872 Param1.push_back(P->getType());
5873
5874 SmallVector<QualType> Param2;
5875 Param2.reserve(FD2->param_size() + ShouldConvert2);
5876 if (ShouldConvert2)
5877 Param2.push_back(Obj2Ty);
5878 for (const auto &P : FD2->parameters())
5879 Param2.push_back(P->getType());
5880
5881 unsigned NumParams1 = Param1.size();
5882 unsigned NumParams2 = Param2.size();
5883
5884 bool Variadic1 =
5885 FD1->param_size() && FD1->parameters().back()->isParameterPack();
5886 bool Variadic2 =
5887 FD2->param_size() && FD2->parameters().back()->isParameterPack();
5888 if (Variadic1 != Variadic2) {
5889 if (Variadic1 && NumParams1 > NumParams2)
5890 return FT2;
5891 if (Variadic2 && NumParams2 > NumParams1)
5892 return FT1;
5893 }
5894
5895 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
5896 // there is no wording or even resolution for this issue.
5897 for (int i = 0, e = std::min(NumParams1, NumParams2); i < e; ++i) {
5898 QualType T1 = Param1[i].getCanonicalType();
5899 QualType T2 = Param2[i].getCanonicalType();
5900 auto *TST1 = dyn_cast<TemplateSpecializationType>(T1);
5901 auto *TST2 = dyn_cast<TemplateSpecializationType>(T2);
5902 if (!TST1 || !TST2)
5903 continue;
5904 const TemplateArgument &TA1 = TST1->template_arguments().back();
5905 if (TA1.getKind() == TemplateArgument::Pack) {
5906 assert(TST1->template_arguments().size() ==
5907 TST2->template_arguments().size());
5908 const TemplateArgument &TA2 = TST2->template_arguments().back();
5909 assert(TA2.getKind() == TemplateArgument::Pack);
5910 unsigned PackSize1 = TA1.pack_size();
5911 unsigned PackSize2 = TA2.pack_size();
5912 bool IsPackExpansion1 =
5913 PackSize1 && TA1.pack_elements().back().isPackExpansion();
5914 bool IsPackExpansion2 =
5915 PackSize2 && TA2.pack_elements().back().isPackExpansion();
5916 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
5917 if (PackSize1 > PackSize2 && IsPackExpansion1)
5918 return FT2;
5919 if (PackSize1 < PackSize2 && IsPackExpansion2)
5920 return FT1;
5921 }
5922 }
5923 }
5924
5925 if (!Context.getLangOpts().CPlusPlus20)
5926 return nullptr;
5927
5928 // Match GCC on not implementing [temp.func.order]p6.2.1.
5929
5930 // C++20 [temp.func.order]p6:
5931 // If deduction against the other template succeeds for both transformed
5932 // templates, constraints can be considered as follows:
5933
5934 // C++20 [temp.func.order]p6.1:
5935 // If their template-parameter-lists (possibly including template-parameters
5936 // invented for an abbreviated function template ([dcl.fct])) or function
5937 // parameter lists differ in length, neither template is more specialized
5938 // than the other.
5941 if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
5942 return nullptr;
5943
5944 // C++20 [temp.func.order]p6.2.2:
5945 // Otherwise, if the corresponding template-parameters of the
5946 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
5947 // function parameters that positionally correspond between the two
5948 // templates are not of the same type, neither template is more specialized
5949 // than the other.
5950 if (!TemplateParameterListsAreEqual(TPL1, TPL2, false,
5952 return nullptr;
5953
5954 // [dcl.fct]p5:
5955 // Any top-level cv-qualifiers modifying a parameter type are deleted when
5956 // forming the function type.
5957 for (unsigned i = 0; i < NumParams1; ++i)
5958 if (!Context.hasSameUnqualifiedType(Param1[i], Param2[i]))
5959 return nullptr;
5960
5961 // C++20 [temp.func.order]p6.3:
5962 // Otherwise, if the context in which the partial ordering is done is
5963 // that of a call to a conversion function and the return types of the
5964 // templates are not the same, then neither template is more specialized
5965 // than the other.
5966 if (TPOC == TPOC_Conversion &&
5968 return nullptr;
5969
5971 FT1->getAssociatedConstraints(AC1);
5972 FT2->getAssociatedConstraints(AC2);
5973 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
5974 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
5975 return nullptr;
5976 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
5977 return nullptr;
5978 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
5979 return nullptr;
5980 return AtLeastAsConstrained1 ? FT1 : FT2;
5981}
5982
5985 TemplateSpecCandidateSet &FailedCandidates,
5986 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
5987 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
5988 bool Complain, QualType TargetType) {
5989 if (SpecBegin == SpecEnd) {
5990 if (Complain) {
5991 Diag(Loc, NoneDiag);
5992 FailedCandidates.NoteCandidates(*this, Loc);
5993 }
5994 return SpecEnd;
5995 }
5996
5997 if (SpecBegin + 1 == SpecEnd)
5998 return SpecBegin;
5999
6000 // Find the function template that is better than all of the templates it
6001 // has been compared to.
6002 UnresolvedSetIterator Best = SpecBegin;
6003 FunctionTemplateDecl *BestTemplate
6004 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
6005 assert(BestTemplate && "Not a function template specialization?");
6006 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
6007 FunctionTemplateDecl *Challenger
6008 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6009 assert(Challenger && "Not a function template specialization?");
6010 if (declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6011 Loc, TPOC_Other, 0),
6012 Challenger)) {
6013 Best = I;
6014 BestTemplate = Challenger;
6015 }
6016 }
6017
6018 // Make sure that the "best" function template is more specialized than all
6019 // of the others.
6020 bool Ambiguous = false;
6021 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6022 FunctionTemplateDecl *Challenger
6023 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6024 if (I != Best &&
6025 !declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6026 Loc, TPOC_Other, 0),
6027 BestTemplate)) {
6028 Ambiguous = true;
6029 break;
6030 }
6031 }
6032
6033 if (!Ambiguous) {
6034 // We found an answer. Return it.
6035 return Best;
6036 }
6037
6038 // Diagnose the ambiguity.
6039 if (Complain) {
6040 Diag(Loc, AmbigDiag);
6041
6042 // FIXME: Can we order the candidates in some sane way?
6043 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6044 PartialDiagnostic PD = CandidateDiag;
6045 const auto *FD = cast<FunctionDecl>(*I);
6047 FD->getPrimaryTemplate()->getTemplateParameters(),
6048 *FD->getTemplateSpecializationArgs());
6049 if (!TargetType.isNull())
6050 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
6051 Diag((*I)->getLocation(), PD);
6052 }
6053 }
6054
6055 return SpecEnd;
6056}
6057
6059 FunctionDecl *FD2) {
6060 assert(!FD1->getDescribedTemplate() && !FD2->getDescribedTemplate() &&
6061 "not for function templates");
6062 assert(!FD1->isFunctionTemplateSpecialization() ||
6063 isa<CXXConversionDecl>(FD1));
6064 assert(!FD2->isFunctionTemplateSpecialization() ||
6065 isa<CXXConversionDecl>(FD2));
6066
6067 FunctionDecl *F1 = FD1;
6069 F1 = P;
6070
6071 FunctionDecl *F2 = FD2;
6073 F2 = P;
6074
6076 F1->getAssociatedConstraints(AC1);
6077 F2->getAssociatedConstraints(AC2);
6078 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6079 if (IsAtLeastAsConstrained(F1, AC1, F2, AC2, AtLeastAsConstrained1))
6080 return nullptr;
6081 if (IsAtLeastAsConstrained(F2, AC2, F1, AC1, AtLeastAsConstrained2))
6082 return nullptr;
6083 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6084 return nullptr;
6085 return AtLeastAsConstrained1 ? FD1 : FD2;
6086}
6087
6088/// Determine whether one partial specialization, P1, is at least as
6089/// specialized than another, P2.
6090///
6091/// \tparam TemplateLikeDecl The kind of P2, which must be a
6092/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
6093/// \param T1 The injected-class-name of P1 (faked for a variable template).
6094/// \param T2 The injected-class-name of P2 (faked for a variable template).
6095template<typename TemplateLikeDecl>
6097 TemplateLikeDecl *P2,
6098 TemplateDeductionInfo &Info) {
6099 // C++ [temp.class.order]p1:
6100 // For two class template partial specializations, the first is at least as
6101 // specialized as the second if, given the following rewrite to two
6102 // function templates, the first function template is at least as
6103 // specialized as the second according to the ordering rules for function
6104 // templates (14.6.6.2):
6105 // - the first function template has the same template parameters as the
6106 // first partial specialization and has a single function parameter
6107 // whose type is a class template specialization with the template
6108 // arguments of the first partial specialization, and
6109 // - the second function template has the same template parameters as the
6110 // second partial specialization and has a single function parameter
6111 // whose type is a class template specialization with the template
6112 // arguments of the second partial specialization.
6113 //
6114 // Rather than synthesize function templates, we merely perform the
6115 // equivalent partial ordering by performing deduction directly on
6116 // the template arguments of the class template partial
6117 // specializations. This computation is slightly simpler than the
6118 // general problem of function template partial ordering, because
6119 // class template partial specializations are more constrained. We
6120 // know that every template parameter is deducible from the class
6121 // template partial specialization's template arguments, for
6122 // example.
6124
6125 // Determine whether P1 is at least as specialized as P2.
6126 Deduced.resize(P2->getTemplateParameters()->size());
6128 S, P2->getTemplateParameters(), T2, T1, Info, Deduced, TDF_None,
6129 PartialOrderingKind::Call, /*DeducedFromArrayBound=*/false,
6130 /*HasDeducedAnyParam=*/nullptr) != TemplateDeductionResult::Success)
6131 return false;
6132
6133 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
6134 Deduced.end());
6135 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
6136 Info);
6137 if (Inst.isInvalid())
6138 return false;
6139
6140 const auto *TST1 = cast<TemplateSpecializationType>(T1);
6141 bool AtLeastAsSpecialized;
6143 AtLeastAsSpecialized =
6144 FinishTemplateArgumentDeduction(
6145 S, P2, /*IsPartialOrdering=*/true, TST1->template_arguments(),
6146 Deduced, Info) == TemplateDeductionResult::Success;
6147 });
6148 return AtLeastAsSpecialized;
6149}
6150
6151namespace {
6152// A dummy class to return nullptr instead of P2 when performing "more
6153// specialized than primary" check.
6154struct GetP2 {
6155 template <typename T1, typename T2,
6156 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6157 T2 *operator()(T1 *, T2 *P2) {
6158 return P2;
6159 }
6160 template <typename T1, typename T2,
6161 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6162 T1 *operator()(T1 *, T2 *) {
6163 return nullptr;
6164 }
6165};
6166
6167// The assumption is that two template argument lists have the same size.
6168struct TemplateArgumentListAreEqual {
6169 ASTContext &Ctx;
6170 TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
6171
6172 template <typename T1, typename T2,
6173 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6174 bool operator()(T1 *PS1, T2 *PS2) {
6175 ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
6176 Args2 = PS2->getTemplateArgs().asArray();
6177
6178 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6179 // We use profile, instead of structural comparison of the arguments,
6180 // because canonicalization can't do the right thing for dependent
6181 // expressions.
6182 llvm::FoldingSetNodeID IDA, IDB;
6183 Args1[I].Profile(IDA, Ctx);
6184 Args2[I].Profile(IDB, Ctx);
6185 if (IDA != IDB)
6186 return false;
6187 }
6188 return true;
6189 }
6190
6191 template <typename T1, typename T2,
6192 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6193 bool operator()(T1 *Spec, T2 *Primary) {
6194 ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
6195 Args2 = Primary->getInjectedTemplateArgs(Ctx);
6196
6197 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6198 // We use profile, instead of structural comparison of the arguments,
6199 // because canonicalization can't do the right thing for dependent
6200 // expressions.
6201 llvm::FoldingSetNodeID IDA, IDB;
6202 Args1[I].Profile(IDA, Ctx);
6203 // Unlike the specialization arguments, the injected arguments are not
6204 // always canonical.
6205 Ctx.getCanonicalTemplateArgument(Args2[I]).Profile(IDB, Ctx);
6206 if (IDA != IDB)
6207 return false;
6208 }
6209 return true;
6210 }
6211};
6212} // namespace
6213
6214/// Returns the more specialized template specialization between T1/P1 and
6215/// T2/P2.
6216/// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
6217/// specialization and T2/P2 is the primary template.
6218/// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
6219///
6220/// \param T1 the type of the first template partial specialization
6221///
6222/// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
6223/// template partial specialization; otherwise, the type of the
6224/// primary template.
6225///
6226/// \param P1 the first template partial specialization
6227///
6228/// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
6229/// partial specialization; otherwise, the primary template.
6230///
6231/// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
6232/// more specialized, returns nullptr if P1 is not more specialized.
6233/// - otherwise, returns the more specialized template partial
6234/// specialization. If neither partial specialization is more
6235/// specialized, returns NULL.
6236template <typename TemplateLikeDecl, typename PrimaryDel>
6237static TemplateLikeDecl *
6238getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
6239 PrimaryDel *P2, TemplateDeductionInfo &Info) {
6240 constexpr bool IsMoreSpecialThanPrimaryCheck =
6241 !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
6242
6243 bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, Info);
6244 if (IsMoreSpecialThanPrimaryCheck && !Better1)
6245 return nullptr;
6246
6247 bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1, Info);
6248 if (IsMoreSpecialThanPrimaryCheck && !Better2)
6249 return P1;
6250
6251 // C++ [temp.deduct.partial]p10:
6252 // F is more specialized than G if F is at least as specialized as G and G
6253 // is not at least as specialized as F.
6254 if (Better1 != Better2) // We have a clear winner
6255 return Better1 ? P1 : GetP2()(P1, P2);
6256
6257 if (!Better1 && !Better2)
6258 return nullptr;
6259
6260 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
6261 // there is no wording or even resolution for this issue.
6262 auto *TST1 = cast<TemplateSpecializationType>(T1);
6263 auto *TST2 = cast<TemplateSpecializationType>(T2);
6264 const TemplateArgument &TA1 = TST1->template_arguments().back();
6265 if (TA1.getKind() == TemplateArgument::Pack) {
6266 assert(TST1->template_arguments().size() ==
6267 TST2->template_arguments().size());
6268 const TemplateArgument &TA2 = TST2->template_arguments().back();
6269 assert(TA2.getKind() == TemplateArgument::Pack);
6270 unsigned PackSize1 = TA1.pack_size();
6271 unsigned PackSize2 = TA2.pack_size();
6272 bool IsPackExpansion1 =
6273 PackSize1 && TA1.pack_elements().back().isPackExpansion();
6274 bool IsPackExpansion2 =
6275 PackSize2 && TA2.pack_elements().back().isPackExpansion();
6276 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
6277 if (PackSize1 > PackSize2 && IsPackExpansion1)
6278 return GetP2()(P1, P2);
6279 if (PackSize1 < PackSize2 && IsPackExpansion2)
6280 return P1;
6281 }
6282 }
6283
6284 if (!S.Context.getLangOpts().CPlusPlus20)
6285 return nullptr;
6286
6287 // Match GCC on not implementing [temp.func.order]p6.2.1.
6288
6289 // C++20 [temp.func.order]p6:
6290 // If deduction against the other template succeeds for both transformed
6291 // templates, constraints can be considered as follows:
6292
6293 TemplateParameterList *TPL1 = P1->getTemplateParameters();
6294 TemplateParameterList *TPL2 = P2->getTemplateParameters();
6295 if (TPL1->size() != TPL2->size())
6296 return nullptr;
6297
6298 // C++20 [temp.func.order]p6.2.2:
6299 // Otherwise, if the corresponding template-parameters of the
6300 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6301 // function parameters that positionally correspond between the two
6302 // templates are not of the same type, neither template is more specialized
6303 // than the other.
6304 if (!S.TemplateParameterListsAreEqual(TPL1, TPL2, false,
6306 return nullptr;
6307
6308 if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
6309 return nullptr;
6310
6312 P1->getAssociatedConstraints(AC1);
6313 P2->getAssociatedConstraints(AC2);
6314 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6315 if (S.IsAtLeastAsConstrained(P1, AC1, P2, AC2, AtLeastAsConstrained1) ||
6316 (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
6317 return nullptr;
6318 if (S.IsAtLeastAsConstrained(P2, AC2, P1, AC1, AtLeastAsConstrained2))
6319 return nullptr;
6320 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6321 return nullptr;
6322 return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
6323}
6324
6332
6334 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6335}
6336
6339 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
6340 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
6341 QualType PartialT = Spec->getInjectedSpecializationType();
6342
6344 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6345 if (MaybeSpec)
6346 Info.clearSFINAEDiagnostic();
6347 return MaybeSpec;
6348}
6349
6354 // Pretend the variable template specializations are class template
6355 // specializations and form a fake injected class name type for comparison.
6356 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
6357 "the partial specializations being compared should specialize"
6358 " the same template.");
6361 Name, PS1->getTemplateArgs().asArray());
6363 Name, PS2->getTemplateArgs().asArray());
6364
6366 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6367}
6368
6371 VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
6372 TemplateName Name(Primary);
6374 Name, Primary->getInjectedTemplateArgs(Context));
6376 Name, Spec->getTemplateArgs().asArray());
6377
6379 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6380 if (MaybeSpec)
6381 Info.clearSFINAEDiagnostic();
6382 return MaybeSpec;
6383}
6384
6387 const DefaultArguments &DefaultArgs, SourceLocation Loc, bool IsDeduced) {
6388 // C++1z [temp.arg.template]p4: (DR 150)
6389 // A template template-parameter P is at least as specialized as a
6390 // template template-argument A if, given the following rewrite to two
6391 // function templates...
6392
6393 // Rather than synthesize function templates, we merely perform the
6394 // equivalent partial ordering by performing deduction directly on
6395 // the template parameter lists of the template template parameters.
6396 //
6398
6399 // Given an invented class template X with the template parameter list of
6400 // A (including default arguments):
6401 // - Each function template has a single function parameter whose type is
6402 // a specialization of X with template arguments corresponding to the
6403 // template parameters from the respective function template
6405
6406 // Check P's arguments against A's parameter list. This will fill in default
6407 // template arguments as needed. AArgs are already correct by construction.
6408 // We can't just use CheckTemplateIdType because that will expand alias
6409 // templates.
6410 SmallVector<TemplateArgument, 4> PArgs(P->getInjectedTemplateArgs(Context));
6411 {
6412 TemplateArgumentListInfo PArgList(P->getLAngleLoc(),
6413 P->getRAngleLoc());
6414 for (unsigned I = 0, N = P->size(); I != N; ++I) {
6415 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
6416 // expansions, to form an "as written" argument list.
6417 TemplateArgument Arg = PArgs[I];
6418 if (Arg.getKind() == TemplateArgument::Pack) {
6419 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
6420 Arg = *Arg.pack_begin();
6421 }
6423 Arg, QualType(), P->getParam(I)->getLocation()));
6424 }
6425 PArgs.clear();
6426
6427 SFINAETrap Trap(*this);
6428 // C++1z [temp.arg.template]p3:
6429 // If the rewrite produces an invalid type, then P is not at least as
6430 // specialized as A.
6432 if (CheckTemplateArgumentList(AArg, Loc, PArgList, DefaultArgs, false,
6433 SugaredPArgs, PArgs,
6434 /*UpdateArgsWithConversions=*/true,
6435 /*ConstraintsNotSatisfied=*/nullptr,
6436 /*PartialOrderTTP=*/true) ||
6437 Trap.hasErrorOccurred())
6438 return false;
6439 }
6440
6441 // Determine whether P1 is at least as specialized as P2.
6444 Deduced.resize(A->size());
6445
6446 // ... the function template corresponding to P is at least as specialized
6447 // as the function template corresponding to A according to the partial
6448 // ordering rules for function templates.
6449
6450 // Provisional resolution for CWG2398: Regarding temp.arg.template]p4, when
6451 // applying the partial ordering rules for function templates on
6452 // the rewritten template template parameters:
6453 // - In a deduced context, the matching of packs versus fixed-size needs to
6454 // be inverted between Ps and As. On non-deduced context, matching needs to
6455 // happen both ways, according to [temp.arg.template]p3, but this is
6456 // currently implemented as a special case elsewhere.
6457 if (::DeduceTemplateArguments(*this, A, AArgs, PArgs, Info, Deduced,
6458 /*NumberOfArgumentsMustMatch=*/false,
6459 /*PartialOrdering=*/true,
6460 IsDeduced ? PackFold::ArgumentToParameter
6461 : PackFold::ParameterToArgument,
6462 /*HasDeducedAnyParam=*/nullptr) !=
6464 return false;
6465
6466 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
6467 Sema::InstantiatingTemplate Inst(*this, Info.getLocation(), AArg, DeducedArgs,
6468 Info);
6469 if (Inst.isInvalid())
6470 return false;
6471
6472 bool AtLeastAsSpecialized;
6474 AtLeastAsSpecialized =
6475 ::FinishTemplateArgumentDeduction(
6476 *this, AArg, /*IsPartialOrdering=*/true, PArgs, Deduced, Info) ==
6477 TemplateDeductionResult::Success;
6478 });
6479 return AtLeastAsSpecialized;
6480}
6481
6482namespace {
6483struct MarkUsedTemplateParameterVisitor : DynamicRecursiveASTVisitor {
6484 llvm::SmallBitVector &Used;
6485 unsigned Depth;
6486
6487 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used,
6488 unsigned Depth)
6489 : Used(Used), Depth(Depth) { }
6490
6491 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
6492 if (T->getDepth() == Depth)
6493 Used[T->getIndex()] = true;
6494 return true;
6495 }
6496
6497 bool TraverseTemplateName(TemplateName Template) override {
6498 if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
6499 Template.getAsTemplateDecl()))
6500 if (TTP->getDepth() == Depth)
6501 Used[TTP->getIndex()] = true;
6503 return true;
6504 }
6505
6506 bool VisitDeclRefExpr(DeclRefExpr *E) override {
6507 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
6508 if (NTTP->getDepth() == Depth)
6509 Used[NTTP->getIndex()] = true;
6510 return true;
6511 }
6512};
6513}
6514
6515/// Mark the template parameters that are used by the given
6516/// expression.
6517static void
6519 const Expr *E,
6520 bool OnlyDeduced,
6521 unsigned Depth,
6522 llvm::SmallBitVector &Used) {
6523 if (!OnlyDeduced) {
6524 MarkUsedTemplateParameterVisitor(Used, Depth)
6525 .TraverseStmt(const_cast<Expr *>(E));
6526 return;
6527 }
6528
6529 // We can deduce from a pack expansion.
6530 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
6531 E = Expansion->getPattern();
6532
6534 if (!NTTP)
6535 return;
6536
6537 if (NTTP->getDepth() == Depth)
6538 Used[NTTP->getIndex()] = true;
6539
6540 // In C++17 mode, additional arguments may be deduced from the type of a
6541 // non-type argument.
6542 if (Ctx.getLangOpts().CPlusPlus17)
6543 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
6544}
6545
6546/// Mark the template parameters that are used by the given
6547/// nested name specifier.
6548static void
6551 bool OnlyDeduced,
6552 unsigned Depth,
6553 llvm::SmallBitVector &Used) {
6554 if (!NNS)
6555 return;
6556
6557 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
6558 Used);
6560 OnlyDeduced, Depth, Used);
6561}
6562
6563/// Mark the template parameters that are used by the given
6564/// template name.
6565static void
6567 TemplateName Name,
6568 bool OnlyDeduced,
6569 unsigned Depth,
6570 llvm::SmallBitVector &Used) {
6571 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
6573 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
6574 if (TTP->getDepth() == Depth)
6575 Used[TTP->getIndex()] = true;
6576 }
6577 return;
6578 }
6579
6580 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
6581 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
6582 Depth, Used);
6583 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
6584 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
6585 Depth, Used);
6586}
6587
6588/// Mark the template parameters that are used by the given
6589/// type.
6590static void
6592 bool OnlyDeduced,
6593 unsigned Depth,
6594 llvm::SmallBitVector &Used) {
6595 if (T.isNull())
6596 return;
6597
6598 // Non-dependent types have nothing deducible
6599 if (!T->isDependentType())
6600 return;
6601
6602 T = Ctx.getCanonicalType(T);
6603 switch (T->getTypeClass()) {
6604 case Type::Pointer:
6606 cast<PointerType>(T)->getPointeeType(),
6607 OnlyDeduced,
6608 Depth,
6609 Used);
6610 break;
6611
6612 case Type::BlockPointer:
6614 cast<BlockPointerType>(T)->getPointeeType(),
6615 OnlyDeduced,
6616 Depth,
6617 Used);
6618 break;
6619
6620 case Type::LValueReference:
6621 case Type::RValueReference:
6623 cast<ReferenceType>(T)->getPointeeType(),
6624 OnlyDeduced,
6625 Depth,
6626 Used);
6627 break;
6628
6629 case Type::MemberPointer: {
6630 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
6631 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
6632 Depth, Used);
6633 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
6634 OnlyDeduced, Depth, Used);
6635 break;
6636 }
6637
6638 case Type::DependentSizedArray:
6640 cast<DependentSizedArrayType>(T)->getSizeExpr(),
6641 OnlyDeduced, Depth, Used);
6642 // Fall through to check the element type
6643 [[fallthrough]];
6644
6645 case Type::ConstantArray:
6646 case Type::IncompleteArray:
6647 case Type::ArrayParameter:
6649 cast<ArrayType>(T)->getElementType(),
6650 OnlyDeduced, Depth, Used);
6651 break;
6652 case Type::Vector:
6653 case Type::ExtVector:
6655 cast<VectorType>(T)->getElementType(),
6656 OnlyDeduced, Depth, Used);
6657 break;
6658
6659 case Type::DependentVector: {
6660 const auto *VecType = cast<DependentVectorType>(T);
6661 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6662 Depth, Used);
6663 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
6664 Used);
6665 break;
6666 }
6667 case Type::DependentSizedExtVector: {
6668 const DependentSizedExtVectorType *VecType
6669 = cast<DependentSizedExtVectorType>(T);
6670 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6671 Depth, Used);
6672 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
6673 Depth, Used);
6674 break;
6675 }
6676
6677 case Type::DependentAddressSpace: {
6678 const DependentAddressSpaceType *DependentASType =
6679 cast<DependentAddressSpaceType>(T);
6680 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
6681 OnlyDeduced, Depth, Used);
6683 DependentASType->getAddrSpaceExpr(),
6684 OnlyDeduced, Depth, Used);
6685 break;
6686 }
6687
6688 case Type::ConstantMatrix: {
6689 const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T);
6690 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6691 Depth, Used);
6692 break;
6693 }
6694
6695 case Type::DependentSizedMatrix: {
6696 const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(T);
6697 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6698 Depth, Used);
6699 MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
6700 Used);
6701 MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
6702 Depth, Used);
6703 break;
6704 }
6705
6706 case Type::FunctionProto: {
6707 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
6708 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
6709 Used);
6710 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
6711 // C++17 [temp.deduct.type]p5:
6712 // The non-deduced contexts are: [...]
6713 // -- A function parameter pack that does not occur at the end of the
6714 // parameter-declaration-list.
6715 if (!OnlyDeduced || I + 1 == N ||
6716 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
6717 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
6718 Depth, Used);
6719 } else {
6720 // FIXME: C++17 [temp.deduct.call]p1:
6721 // When a function parameter pack appears in a non-deduced context,
6722 // the type of that pack is never deduced.
6723 //
6724 // We should also track a set of "never deduced" parameters, and
6725 // subtract that from the list of deduced parameters after marking.
6726 }
6727 }
6728 if (auto *E = Proto->getNoexceptExpr())
6729 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
6730 break;
6731 }
6732
6733 case Type::TemplateTypeParm: {
6734 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
6735 if (TTP->getDepth() == Depth)
6736 Used[TTP->getIndex()] = true;
6737 break;
6738 }
6739
6740 case Type::SubstTemplateTypeParmPack: {
6742 = cast<SubstTemplateTypeParmPackType>(T);
6743 if (Subst->getReplacedParameter()->getDepth() == Depth)
6744 Used[Subst->getIndex()] = true;
6746 OnlyDeduced, Depth, Used);
6747 break;
6748 }
6749
6750 case Type::InjectedClassName:
6751 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
6752 [[fallthrough]];
6753
6754 case Type::TemplateSpecialization: {
6755 const TemplateSpecializationType *Spec
6756 = cast<TemplateSpecializationType>(T);
6757 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
6758 Depth, Used);
6759
6760 // C++0x [temp.deduct.type]p9:
6761 // If the template argument list of P contains a pack expansion that is
6762 // not the last template argument, the entire template argument list is a
6763 // non-deduced context.
6764 if (OnlyDeduced &&
6766 break;
6767
6768 for (const auto &Arg : Spec->template_arguments())
6769 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6770 break;
6771 }
6772
6773 case Type::Complex:
6774 if (!OnlyDeduced)
6776 cast<ComplexType>(T)->getElementType(),
6777 OnlyDeduced, Depth, Used);
6778 break;
6779
6780 case Type::Atomic:
6781 if (!OnlyDeduced)
6783 cast<AtomicType>(T)->getValueType(),
6784 OnlyDeduced, Depth, Used);
6785 break;
6786
6787 case Type::DependentName:
6788 if (!OnlyDeduced)
6790 cast<DependentNameType>(T)->getQualifier(),
6791 OnlyDeduced, Depth, Used);
6792 break;
6793
6794 case Type::DependentTemplateSpecialization: {
6795 // C++14 [temp.deduct.type]p5:
6796 // The non-deduced contexts are:
6797 // -- The nested-name-specifier of a type that was specified using a
6798 // qualified-id
6799 //
6800 // C++14 [temp.deduct.type]p6:
6801 // When a type name is specified in a way that includes a non-deduced
6802 // context, all of the types that comprise that type name are also
6803 // non-deduced.
6804 if (OnlyDeduced)
6805 break;
6806
6808 = cast<DependentTemplateSpecializationType>(T);
6809
6811 OnlyDeduced, Depth, Used);
6812
6813 for (const auto &Arg : Spec->template_arguments())
6814 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6815 break;
6816 }
6817
6818 case Type::TypeOf:
6819 if (!OnlyDeduced)
6820 MarkUsedTemplateParameters(Ctx, cast<TypeOfType>(T)->getUnmodifiedType(),
6821 OnlyDeduced, Depth, Used);
6822 break;
6823
6824 case Type::TypeOfExpr:
6825 if (!OnlyDeduced)
6827 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
6828 OnlyDeduced, Depth, Used);
6829 break;
6830
6831 case Type::Decltype:
6832 if (!OnlyDeduced)
6834 cast<DecltypeType>(T)->getUnderlyingExpr(),
6835 OnlyDeduced, Depth, Used);
6836 break;
6837
6838 case Type::PackIndexing:
6839 if (!OnlyDeduced) {
6840 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getPattern(),
6841 OnlyDeduced, Depth, Used);
6842 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getIndexExpr(),
6843 OnlyDeduced, Depth, Used);
6844 }
6845 break;
6846
6847 case Type::UnaryTransform:
6848 if (!OnlyDeduced)
6850 cast<UnaryTransformType>(T)->getUnderlyingType(),
6851 OnlyDeduced, Depth, Used);
6852 break;
6853
6854 case Type::PackExpansion:
6856 cast<PackExpansionType>(T)->getPattern(),
6857 OnlyDeduced, Depth, Used);
6858 break;
6859
6860 case Type::Auto:
6861 case Type::DeducedTemplateSpecialization:
6863 cast<DeducedType>(T)->getDeducedType(),
6864 OnlyDeduced, Depth, Used);
6865 break;
6866 case Type::DependentBitInt:
6868 cast<DependentBitIntType>(T)->getNumBitsExpr(),
6869 OnlyDeduced, Depth, Used);
6870 break;
6871
6872 case Type::HLSLAttributedResource:
6874 Ctx, cast<HLSLAttributedResourceType>(T)->getWrappedType(), OnlyDeduced,
6875 Depth, Used);
6876 if (cast<HLSLAttributedResourceType>(T)->hasContainedType())
6878 Ctx, cast<HLSLAttributedResourceType>(T)->getContainedType(),
6879 OnlyDeduced, Depth, Used);
6880 break;
6881
6882 // None of these types have any template parameters in them.
6883 case Type::Builtin:
6884 case Type::VariableArray:
6885 case Type::FunctionNoProto:
6886 case Type::Record:
6887 case Type::Enum:
6888 case Type::ObjCInterface:
6889 case Type::ObjCObject:
6890 case Type::ObjCObjectPointer:
6891 case Type::UnresolvedUsing:
6892 case Type::Pipe:
6893 case Type::BitInt:
6894#define TYPE(Class, Base)
6895#define ABSTRACT_TYPE(Class, Base)
6896#define DEPENDENT_TYPE(Class, Base)
6897#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6898#include "clang/AST/TypeNodes.inc"
6899 break;
6900 }
6901}
6902
6903/// Mark the template parameters that are used by this
6904/// template argument.
6905static void
6908 bool OnlyDeduced,
6909 unsigned Depth,
6910 llvm::SmallBitVector &Used) {
6911 switch (TemplateArg.getKind()) {
6917 break;
6918
6920 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
6921 Depth, Used);
6922 break;
6923
6927 TemplateArg.getAsTemplateOrTemplatePattern(),
6928 OnlyDeduced, Depth, Used);
6929 break;
6930
6932 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
6933 Depth, Used);
6934 break;
6935
6937 for (const auto &P : TemplateArg.pack_elements())
6938 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
6939 break;
6940 }
6941}
6942
6943void
6944Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
6945 unsigned Depth,
6946 llvm::SmallBitVector &Used) {
6947 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
6948}
6949
6950void
6952 bool OnlyDeduced, unsigned Depth,
6953 llvm::SmallBitVector &Used) {
6954 // C++0x [temp.deduct.type]p9:
6955 // If the template argument list of P contains a pack expansion that is not
6956 // the last template argument, the entire template argument list is a
6957 // non-deduced context.
6958 if (OnlyDeduced &&
6959 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
6960 return;
6961
6962 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6963 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
6964 Depth, Used);
6965}
6966
6968 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
6969 llvm::SmallBitVector &Deduced) {
6970 TemplateParameterList *TemplateParams
6971 = FunctionTemplate->getTemplateParameters();
6972 Deduced.clear();
6973 Deduced.resize(TemplateParams->size());
6974
6975 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
6976 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
6977 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
6978 true, TemplateParams->getDepth(), Deduced);
6979}
6980
6982 FunctionTemplateDecl *FunctionTemplate,
6983 QualType T) {
6984 if (!T->isDependentType())
6985 return false;
6986
6987 TemplateParameterList *TemplateParams
6988 = FunctionTemplate->getTemplateParameters();
6989 llvm::SmallBitVector Deduced(TemplateParams->size());
6990 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
6991 Deduced);
6992
6993 return Deduced.any();
6994}
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 ...
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:13193
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8041
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3003
A helper class for building up ExtParameterInfos.
Definition: Sema.h:12607
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:12626
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12079
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12109
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:463
bool CheckInstantiatedFunctionTemplateConstraints(SourceLocation PointOfInstantiation, FunctionDecl *Decl, ArrayRef< TemplateArgument > TemplateArgs, ConstraintSatisfaction &Satisfaction)
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12636
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:1070
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:6452
@ CTAK_DeducedFromArrayBound
The template argument was deduced from an array bound via template argument deduction.
Definition: Sema.h:11639
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:11631
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition: Sema.h:11635
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition: Sema.h:908
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:531
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:690
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:816
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:11813
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:524
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:14368
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:1043
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:12142
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:20955
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:14938
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)
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:562
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:12480
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
@ 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:364
@ 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:12674
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:12681
A stack object to be created when performing template instantiation.
Definition: Sema.h:12838
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:12992
brief A function argument from which we performed template argument
Definition: Sema.h:12242
Location information for a TemplateArgument.
Definition: TemplateBase.h:472