clang 21.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 "llvm/Support/SaveAndRestore.h"
57#include <algorithm>
58#include <cassert>
59#include <optional>
60#include <tuple>
61#include <type_traits>
62#include <utility>
63
64namespace clang {
65
66 /// Various flags that control template argument deduction.
67 ///
68 /// These flags can be bitwise-OR'd together.
70 /// No template argument deduction flags, which indicates the
71 /// strictest results for template argument deduction (as used for, e.g.,
72 /// matching class template partial specializations).
74
75 /// Within template argument deduction from a function call, we are
76 /// matching with a parameter type for which the original parameter was
77 /// a reference.
79
80 /// Within template argument deduction from a function call, we
81 /// are matching in a case where we ignore cv-qualifiers.
83
84 /// Within template argument deduction from a function call,
85 /// we are matching in a case where we can perform template argument
86 /// deduction from a template-id of a derived class of the argument type.
88
89 /// Allow non-dependent types to differ, e.g., when performing
90 /// template argument deduction from a function call where conversions
91 /// may apply.
93
94 /// Whether we are performing template argument deduction for
95 /// parameters and arguments in a top-level template argument
97
98 /// Within template argument deduction from overload resolution per
99 /// C++ [over.over] allow matching function types that are compatible in
100 /// terms of noreturn and default calling convention adjustments, or
101 /// similarly matching a declared template specialization against a
102 /// possible template, per C++ [temp.deduct.decl]. In either case, permit
103 /// deduction where the parameter is a function type that can be converted
104 /// to the argument type.
106
107 /// Within template argument deduction for a conversion function, we are
108 /// matching with an argument type for which the original argument was
109 /// a reference.
111 };
112}
113
114using namespace clang;
115using namespace sema;
116
117/// Compare two APSInts, extending and switching the sign as
118/// necessary to compare their values regardless of underlying type.
119static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
120 if (Y.getBitWidth() > X.getBitWidth())
121 X = X.extend(Y.getBitWidth());
122 else if (Y.getBitWidth() < X.getBitWidth())
123 Y = Y.extend(X.getBitWidth());
124
125 // If there is a signedness mismatch, correct it.
126 if (X.isSigned() != Y.isSigned()) {
127 // If the signed value is negative, then the values cannot be the same.
128 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
129 return false;
130
131 Y.setIsSigned(true);
132 X.setIsSigned(true);
133 }
134
135 return X == Y;
136}
137
138/// The kind of PartialOrdering we're performing template argument deduction
139/// for (C++11 [temp.deduct.partial]).
141
143 Sema &S, TemplateParameterList *TemplateParams, QualType Param,
145 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
146 PartialOrderingKind POK, bool DeducedFromArrayBound,
147 bool *HasDeducedAnyParam);
148
149/// What directions packs are allowed to match non-packs.
151
158 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
159 PackFold PackFold, bool *HasDeducedAnyParam);
160
163 bool OnlyDeduced, unsigned Depth,
164 llvm::SmallBitVector &Used);
165
167 bool OnlyDeduced, unsigned Level,
168 llvm::SmallBitVector &Deduced);
169
170/// If the given expression is of a form that permits the deduction
171/// of a non-type template parameter, return the declaration of that
172/// non-type template parameter.
173static const NonTypeTemplateParmDecl *
174getDeducedParameterFromExpr(const Expr *E, unsigned Depth) {
175 // If we are within an alias template, the expression may have undergone
176 // any number of parameter substitutions already.
177 while (true) {
178 if (const auto *IC = dyn_cast<ImplicitCastExpr>(E))
179 E = IC->getSubExpr();
180 else if (const auto *CE = dyn_cast<ConstantExpr>(E))
181 E = CE->getSubExpr();
182 else if (const auto *Subst = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
183 E = Subst->getReplacement();
184 else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) {
185 // Look through implicit copy construction from an lvalue of the same type.
186 if (CCE->getParenOrBraceRange().isValid())
187 break;
188 // Note, there could be default arguments.
189 assert(CCE->getNumArgs() >= 1 && "implicit construct expr should have 1 arg");
190 E = CCE->getArg(0);
191 } else
192 break;
193 }
194
195 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
196 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
197 if (NTTP->getDepth() == Depth)
198 return NTTP;
199
200 return nullptr;
201}
202
203static const NonTypeTemplateParmDecl *
206}
207
208/// Determine whether two declaration pointers refer to the same
209/// declaration.
210static bool isSameDeclaration(Decl *X, Decl *Y) {
211 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
212 X = NX->getUnderlyingDecl();
213 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
214 Y = NY->getUnderlyingDecl();
215
216 return X->getCanonicalDecl() == Y->getCanonicalDecl();
217}
218
219/// Verify that the given, deduced template arguments are compatible.
220///
221/// \returns The deduced template argument, or a NULL template argument if
222/// the deduced template arguments were incompatible.
227 bool AggregateCandidateDeduction = false) {
228 // We have no deduction for one or both of the arguments; they're compatible.
229 if (X.isNull())
230 return Y;
231 if (Y.isNull())
232 return X;
233
234 // If we have two non-type template argument values deduced for the same
235 // parameter, they must both match the type of the parameter, and thus must
236 // match each other's type. As we're only keeping one of them, we must check
237 // for that now. The exception is that if either was deduced from an array
238 // bound, the type is permitted to differ.
239 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
240 QualType XType = X.getNonTypeTemplateArgumentType();
241 if (!XType.isNull()) {
243 if (YType.isNull() || !Context.hasSameType(XType, YType))
245 }
246 }
247
248 switch (X.getKind()) {
250 llvm_unreachable("Non-deduced template arguments handled above");
251
253 // If two template type arguments have the same type, they're compatible.
254 QualType TX = X.getAsType(), TY = Y.getAsType();
255 if (Y.getKind() == TemplateArgument::Type && Context.hasSameType(TX, TY))
256 return DeducedTemplateArgument(Context.getCommonSugaredType(TX, TY),
257 X.wasDeducedFromArrayBound() ||
259
260 // If one of the two arguments was deduced from an array bound, the other
261 // supersedes it.
262 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
263 return X.wasDeducedFromArrayBound() ? Y : X;
264
265 // The arguments are not compatible.
267 }
268
270 // If we deduced a constant in one case and either a dependent expression or
271 // declaration in another case, keep the integral constant.
272 // If both are integral constants with the same value, keep that value.
276 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
277 return X.wasDeducedFromArrayBound() ? Y : X;
278
279 // All other combinations are incompatible.
281
283 // If we deduced a value and a dependent expression, keep the value.
286 X.structurallyEquals(Y)))
287 return X;
288
289 // All other combinations are incompatible.
291
294 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
295 return X;
296
297 // All other combinations are incompatible.
299
302 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
304 return X;
305
306 // All other combinations are incompatible.
308
311 return checkDeducedTemplateArguments(Context, Y, X);
312
313 // Compare the expressions for equality
314 llvm::FoldingSetNodeID ID1, ID2;
315 X.getAsExpr()->Profile(ID1, Context, true);
316 Y.getAsExpr()->Profile(ID2, Context, true);
317 if (ID1 == ID2)
318 return X.wasDeducedFromArrayBound() ? Y : X;
319
320 // Differing dependent expressions are incompatible.
322 }
323
325 assert(!X.wasDeducedFromArrayBound());
326
327 // If we deduced a declaration and a dependent expression, keep the
328 // declaration.
330 return X;
331
332 // If we deduced a declaration and an integral constant, keep the
333 // integral constant and whichever type did not come from an array
334 // bound.
337 return TemplateArgument(Context, Y.getAsIntegral(),
338 X.getParamTypeForDecl());
339 return Y;
340 }
341
342 // If we deduced two declarations, make sure that they refer to the
343 // same declaration.
345 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
346 return X;
347
348 // All other combinations are incompatible.
350
352 // If we deduced a null pointer and a dependent expression, keep the
353 // null pointer.
356 X.getNullPtrType(), Y.getAsExpr()->getType()),
357 true);
358
359 // If we deduced a null pointer and an integral constant, keep the
360 // integral constant.
362 return Y;
363
364 // If we deduced two null pointers, they are the same.
366 return TemplateArgument(
367 Context.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
368 true);
369
370 // All other combinations are incompatible.
372
374 if (Y.getKind() != TemplateArgument::Pack ||
375 (!AggregateCandidateDeduction && X.pack_size() != Y.pack_size()))
377
380 XA = X.pack_begin(),
381 XAEnd = X.pack_end(), YA = Y.pack_begin(), YAEnd = Y.pack_end();
382 XA != XAEnd; ++XA) {
383 if (YA != YAEnd) {
385 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
387 if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
389 NewPack.push_back(Merged);
390 ++YA;
391 } else {
392 NewPack.push_back(*XA);
393 }
394 }
395
397 TemplateArgument::CreatePackCopy(Context, NewPack),
398 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
399 }
400 }
401
402 llvm_unreachable("Invalid TemplateArgument Kind!");
403}
404
405/// Deduce the value of the given non-type template parameter
406/// as the given deduced template argument. All non-type template parameter
407/// deduction is funneled through here.
410 const NonTypeTemplateParmDecl *NTTP,
411 const DeducedTemplateArgument &NewDeduced,
412 QualType ValueType, TemplateDeductionInfo &Info,
413 bool PartialOrdering,
415 bool *HasDeducedAnyParam) {
416 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
417 "deducing non-type template argument with wrong depth");
418
420 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
421 if (Result.isNull()) {
422 Info.Param = const_cast<NonTypeTemplateParmDecl*>(NTTP);
423 Info.FirstArg = Deduced[NTTP->getIndex()];
424 Info.SecondArg = NewDeduced;
425 return TemplateDeductionResult::Inconsistent;
426 }
427
428 Deduced[NTTP->getIndex()] = Result;
429 if (!S.getLangOpts().CPlusPlus17)
430 return TemplateDeductionResult::Success;
431
432 if (NTTP->isExpandedParameterPack())
433 // FIXME: We may still need to deduce parts of the type here! But we
434 // don't have any way to find which slice of the type to use, and the
435 // type stored on the NTTP itself is nonsense. Perhaps the type of an
436 // expanded NTTP should be a pack expansion type?
437 return TemplateDeductionResult::Success;
438
439 // Get the type of the parameter for deduction. If it's a (dependent) array
440 // or function type, we will not have decayed it yet, so do that now.
441 QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
442 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
443 ParamType = Expansion->getPattern();
444
445 // FIXME: It's not clear how deduction of a parameter of reference
446 // type from an argument (of non-reference type) should be performed.
447 // For now, we just make the argument have same reference type as the
448 // parameter.
449 if (ParamType->isReferenceType() && !ValueType->isReferenceType()) {
450 if (ParamType->isRValueReferenceType())
451 ValueType = S.Context.getRValueReferenceType(ValueType);
452 else
453 ValueType = S.Context.getLValueReferenceType(ValueType);
454 }
455
457 S, TemplateParams, ParamType, ValueType, Info, Deduced,
461 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound(), HasDeducedAnyParam);
462}
463
464/// Deduce the value of the given non-type template parameter
465/// from the given integral constant.
467 Sema &S, TemplateParameterList *TemplateParams,
468 const NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
469 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
471 bool *HasDeducedAnyParam) {
473 S, TemplateParams, NTTP,
475 DeducedFromArrayBound),
476 ValueType, Info, PartialOrdering, Deduced, HasDeducedAnyParam);
477}
478
479/// Deduce the value of the given non-type template parameter
480/// from the given null pointer template argument type.
483 const NonTypeTemplateParmDecl *NTTP,
484 QualType NullPtrType, TemplateDeductionInfo &Info,
485 bool PartialOrdering,
487 bool *HasDeducedAnyParam) {
490 NTTP->getLocation()),
491 NullPtrType,
492 NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer
493 : CK_NullToPointer)
494 .get();
496 S, TemplateParams, NTTP, DeducedTemplateArgument(Value), Value->getType(),
497 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
498}
499
500/// Deduce the value of the given non-type template parameter
501/// from the given type- or value-dependent expression.
502///
503/// \returns true if deduction succeeded, false otherwise.
506 const NonTypeTemplateParmDecl *NTTP, Expr *Value,
509 bool *HasDeducedAnyParam) {
511 S, TemplateParams, NTTP, DeducedTemplateArgument(Value), Value->getType(),
512 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
513}
514
515/// Deduce the value of the given non-type template parameter
516/// from the given declaration.
517///
518/// \returns true if deduction succeeded, false otherwise.
521 const NonTypeTemplateParmDecl *NTTP, ValueDecl *D,
523 bool PartialOrdering,
525 bool *HasDeducedAnyParam) {
526 TemplateArgument New(D, T);
528 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info,
529 PartialOrdering, Deduced, HasDeducedAnyParam);
530}
531
533 Sema &S, TemplateParameterList *TemplateParams, TemplateName Param,
537 bool *HasDeducedAnyParam) {
538 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
539 if (!ParamDecl) {
540 // The parameter type is dependent and is not a template template parameter,
541 // so there is nothing that we can deduce.
542 return TemplateDeductionResult::Success;
543 }
544
545 if (auto *TempParam = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
546 // If we're not deducing at this depth, there's nothing to deduce.
547 if (TempParam->getDepth() != Info.getDeducedDepth())
548 return TemplateDeductionResult::Success;
549
550 ArrayRef<NamedDecl *> Params =
551 ParamDecl->getTemplateParameters()->asArray();
552 unsigned StartPos = 0;
553 for (unsigned I = 0, E = std::min(Params.size(), DefaultArguments.size());
554 I < E; ++I) {
555 if (Params[I]->isParameterPack()) {
556 StartPos = DefaultArguments.size();
557 break;
558 }
559 StartPos = I + 1;
560 }
561
562 // Provisional resolution for CWG2398: If Arg names a template
563 // specialization, then we deduce a synthesized template name
564 // based on A, but using the TS's extra arguments, relative to P, as
565 // defaults.
566 DeducedTemplateArgument NewDeduced =
569 Arg, {StartPos, DefaultArguments.drop_front(StartPos)}))
570 : Arg;
571
573 S.Context, Deduced[TempParam->getIndex()], NewDeduced);
574 if (Result.isNull()) {
575 Info.Param = TempParam;
576 Info.FirstArg = Deduced[TempParam->getIndex()];
577 Info.SecondArg = NewDeduced;
578 return TemplateDeductionResult::Inconsistent;
579 }
580
581 Deduced[TempParam->getIndex()] = Result;
582 if (HasDeducedAnyParam)
583 *HasDeducedAnyParam = true;
584 return TemplateDeductionResult::Success;
585 }
586
587 // Verify that the two template names are equivalent.
589 Param, Arg, /*IgnoreDeduced=*/DefaultArguments.size() != 0))
590 return TemplateDeductionResult::Success;
591
592 // Mismatch of non-dependent template parameter to argument.
593 Info.FirstArg = TemplateArgument(Param);
594 Info.SecondArg = TemplateArgument(Arg);
595 return TemplateDeductionResult::NonDeducedMismatch;
596}
597
598/// Deduce the template arguments by comparing the template parameter
599/// type (which is a template-id) with the template argument type.
600///
601/// \param S the Sema
602///
603/// \param TemplateParams the template parameters that we are deducing
604///
605/// \param P the parameter type
606///
607/// \param A the argument type
608///
609/// \param Info information about the template argument deduction itself
610///
611/// \param Deduced the deduced template arguments
612///
613/// \returns the result of template argument deduction so far. Note that a
614/// "success" result means that template argument deduction has not yet failed,
615/// but it may still fail, later, for other reasons.
616
618 for (const Type *T = QT.getTypePtr(); /**/; /**/) {
619 const TemplateSpecializationType *TST =
621 assert(TST && "Expected a TemplateSpecializationType");
622 if (!TST->isSugared())
623 return TST;
624 T = TST->desugar().getTypePtr();
625 }
626}
627
630 const QualType P, QualType A,
633 bool *HasDeducedAnyParam) {
634 QualType UP = P;
635 if (const auto *IP = P->getAs<InjectedClassNameType>())
636 UP = IP->getInjectedSpecializationType();
637
638 assert(isa<TemplateSpecializationType>(UP.getCanonicalType()));
640 TemplateName TNP = TP->getTemplateName();
641
642 // If the parameter is an alias template, there is nothing to deduce.
643 if (const auto *TD = TNP.getAsTemplateDecl(); TD && TD->isTypeAlias())
644 return TemplateDeductionResult::Success;
645
646 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
647 // arguments.
651 ->template_arguments();
652
653 QualType UA = A;
654 std::optional<NestedNameSpecifier *> NNS;
655 // Treat an injected-class-name as its underlying template-id.
656 if (const auto *Elaborated = A->getAs<ElaboratedType>()) {
657 NNS = Elaborated->getQualifier();
658 } else if (const auto *Injected = A->getAs<InjectedClassNameType>()) {
659 UA = Injected->getInjectedSpecializationType();
660 NNS = nullptr;
661 }
662
663 // Check whether the template argument is a dependent template-id.
664 if (isa<TemplateSpecializationType>(UA.getCanonicalType())) {
666 TemplateName TNA = SA->getTemplateName();
667
668 // If the argument is an alias template, there is nothing to deduce.
669 if (const auto *TD = TNA.getAsTemplateDecl(); TD && TD->isTypeAlias())
670 return TemplateDeductionResult::Success;
671
672 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
673 // arguments.
677 ->template_arguments();
678
679 // Perform template argument deduction for the template name.
680 if (auto Result = DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
681 /*DefaultArguments=*/AResolved,
682 PartialOrdering, Deduced,
683 HasDeducedAnyParam);
684 Result != TemplateDeductionResult::Success)
685 return Result;
686
687 // Perform template argument deduction on each template
688 // argument. Ignore any missing/extra arguments, since they could be
689 // filled in by default arguments.
691 S, TemplateParams, PResolved, AResolved, Info, Deduced,
692 /*NumberOfArgumentsMustMatch=*/false, PartialOrdering,
693 PackFold::ParameterToArgument, HasDeducedAnyParam);
694 }
695
696 // If the argument type is a class template specialization, we
697 // perform template argument deduction using its template
698 // arguments.
699 const auto *RA = UA->getAs<RecordType>();
700 const auto *SA =
701 RA ? dyn_cast<ClassTemplateSpecializationDecl>(RA->getDecl()) : nullptr;
702 if (!SA) {
704 Info.SecondArg = TemplateArgument(A);
705 return TemplateDeductionResult::NonDeducedMismatch;
706 }
707
708 TemplateName TNA = TemplateName(SA->getSpecializedTemplate());
709 if (NNS)
711 *NNS, false, TemplateName(SA->getSpecializedTemplate()));
712
713 // Perform template argument deduction for the template name.
714 if (auto Result = DeduceTemplateArguments(
715 S, TemplateParams, TNP, TNA, Info,
716 /*DefaultArguments=*/SA->getTemplateArgs().asArray(), PartialOrdering,
717 Deduced, HasDeducedAnyParam);
718 Result != TemplateDeductionResult::Success)
719 return Result;
720
721 // Perform template argument deduction for the template arguments.
722 return DeduceTemplateArguments(S, TemplateParams, PResolved,
723 SA->getTemplateArgs().asArray(), Info, Deduced,
724 /*NumberOfArgumentsMustMatch=*/true,
726 HasDeducedAnyParam);
727}
728
730 assert(T->isCanonicalUnqualified());
731
732 switch (T->getTypeClass()) {
733 case Type::TypeOfExpr:
734 case Type::TypeOf:
735 case Type::DependentName:
736 case Type::Decltype:
737 case Type::PackIndexing:
738 case Type::UnresolvedUsing:
739 case Type::TemplateTypeParm:
740 case Type::Auto:
741 return true;
742
743 case Type::ConstantArray:
744 case Type::IncompleteArray:
745 case Type::VariableArray:
746 case Type::DependentSizedArray:
748 cast<ArrayType>(T)->getElementType().getTypePtr());
749
750 default:
751 return false;
752 }
753}
754
755/// Determines whether the given type is an opaque type that
756/// might be more qualified when instantiated.
760}
761
762/// Helper function to build a TemplateParameter when we don't
763/// know its type statically.
765 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
766 return TemplateParameter(TTP);
767 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
768 return TemplateParameter(NTTP);
769
770 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
771}
772
773/// A pack that we're currently deducing.
775 // The index of the pack.
776 unsigned Index;
777
778 // The old value of the pack before we started deducing it.
780
781 // A deferred value of this pack from an inner deduction, that couldn't be
782 // deduced because this deduction hadn't happened yet.
784
785 // The new value of the pack.
787
788 // The outer deduction for this pack, if any.
789 DeducedPack *Outer = nullptr;
790
791 DeducedPack(unsigned Index) : Index(Index) {}
792};
793
794namespace {
795
796/// A scope in which we're performing pack deduction.
797class PackDeductionScope {
798public:
799 /// Prepare to deduce the packs named within Pattern.
800 /// \param FinishingDeduction Don't attempt to deduce the pack. Useful when
801 /// just checking a previous deduction of the pack.
802 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
805 bool DeducePackIfNotAlreadyDeduced = false,
806 bool FinishingDeduction = false)
807 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info),
808 DeducePackIfNotAlreadyDeduced(DeducePackIfNotAlreadyDeduced),
809 FinishingDeduction(FinishingDeduction) {
810 unsigned NumNamedPacks = addPacks(Pattern);
811 finishConstruction(NumNamedPacks);
812 }
813
814 /// Prepare to directly deduce arguments of the parameter with index \p Index.
815 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
817 TemplateDeductionInfo &Info, unsigned Index)
818 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
819 addPack(Index);
820 finishConstruction(1);
821 }
822
823private:
824 void addPack(unsigned Index) {
825 // Save the deduced template argument for the parameter pack expanded
826 // by this pack expansion, then clear out the deduction.
827 DeducedFromEarlierParameter = !Deduced[Index].isNull();
828 DeducedPack Pack(Index);
829 if (!FinishingDeduction) {
830 Pack.Saved = Deduced[Index];
831 Deduced[Index] = TemplateArgument();
832 }
833
834 // FIXME: What if we encounter multiple packs with different numbers of
835 // pre-expanded expansions? (This should already have been diagnosed
836 // during substitution.)
837 if (std::optional<unsigned> ExpandedPackExpansions =
838 getExpandedPackSize(TemplateParams->getParam(Index)))
839 FixedNumExpansions = ExpandedPackExpansions;
840
841 Packs.push_back(Pack);
842 }
843
844 unsigned addPacks(TemplateArgument Pattern) {
845 // Compute the set of template parameter indices that correspond to
846 // parameter packs expanded by the pack expansion.
847 llvm::SmallBitVector SawIndices(TemplateParams->size());
849
850 auto AddPack = [&](unsigned Index) {
851 if (SawIndices[Index])
852 return;
853 SawIndices[Index] = true;
854 addPack(Index);
855
856 // Deducing a parameter pack that is a pack expansion also constrains the
857 // packs appearing in that parameter to have the same deduced arity. Also,
858 // in C++17 onwards, deducing a non-type template parameter deduces its
859 // type, so we need to collect the pending deduced values for those packs.
860 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
861 TemplateParams->getParam(Index))) {
862 if (!NTTP->isExpandedParameterPack())
863 // FIXME: CWG2982 suggests a type-constraint forms a non-deduced
864 // context, however it is not yet resolved.
865 if (auto *Expansion = dyn_cast<PackExpansionType>(
866 S.Context.getUnconstrainedType(NTTP->getType())))
867 ExtraDeductions.push_back(Expansion->getPattern());
868 }
869 // FIXME: Also collect the unexpanded packs in any type and template
870 // parameter packs that are pack expansions.
871 };
872
873 auto Collect = [&](TemplateArgument Pattern) {
875 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
876 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
877 unsigned Depth, Index;
878 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
879 if (Depth == Info.getDeducedDepth())
880 AddPack(Index);
881 }
882 };
883
884 // Look for unexpanded packs in the pattern.
885 Collect(Pattern);
886 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
887
888 unsigned NumNamedPacks = Packs.size();
889
890 // Also look for unexpanded packs that are indirectly deduced by deducing
891 // the sizes of the packs in this pattern.
892 while (!ExtraDeductions.empty())
893 Collect(ExtraDeductions.pop_back_val());
894
895 return NumNamedPacks;
896 }
897
898 void finishConstruction(unsigned NumNamedPacks) {
899 // Dig out the partially-substituted pack, if there is one.
900 const TemplateArgument *PartialPackArgs = nullptr;
901 unsigned NumPartialPackArgs = 0;
902 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
903 if (auto *Scope = S.CurrentInstantiationScope)
904 if (auto *Partial = Scope->getPartiallySubstitutedPack(
905 &PartialPackArgs, &NumPartialPackArgs))
906 PartialPackDepthIndex = getDepthAndIndex(Partial);
907
908 // This pack expansion will have been partially or fully expanded if
909 // it only names explicitly-specified parameter packs (including the
910 // partially-substituted one, if any).
911 bool IsExpanded = true;
912 for (unsigned I = 0; I != NumNamedPacks; ++I) {
913 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
914 IsExpanded = false;
915 IsPartiallyExpanded = false;
916 break;
917 }
918 if (PartialPackDepthIndex ==
919 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
920 IsPartiallyExpanded = true;
921 }
922 }
923
924 // Skip over the pack elements that were expanded into separate arguments.
925 // If we partially expanded, this is the number of partial arguments.
926 // FIXME: `&& FixedNumExpansions` is a workaround for UB described in
927 // https://github.com/llvm/llvm-project/issues/100095
928 if (IsPartiallyExpanded)
929 PackElements += NumPartialPackArgs;
930 else if (IsExpanded && FixedNumExpansions)
931 PackElements += *FixedNumExpansions;
932
933 for (auto &Pack : Packs) {
934 if (Info.PendingDeducedPacks.size() > Pack.Index)
935 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
936 else
937 Info.PendingDeducedPacks.resize(Pack.Index + 1);
938 Info.PendingDeducedPacks[Pack.Index] = &Pack;
939
940 if (PartialPackDepthIndex ==
941 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
942 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
943 // We pre-populate the deduced value of the partially-substituted
944 // pack with the specified value. This is not entirely correct: the
945 // value is supposed to have been substituted, not deduced, but the
946 // cases where this is observable require an exact type match anyway.
947 //
948 // FIXME: If we could represent a "depth i, index j, pack elem k"
949 // parameter, we could substitute the partially-substituted pack
950 // everywhere and avoid this.
951 if (!FinishingDeduction && !IsPartiallyExpanded)
952 Deduced[Pack.Index] = Pack.New[PackElements];
953 }
954 }
955 }
956
957public:
958 ~PackDeductionScope() {
959 for (auto &Pack : Packs)
960 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
961 }
962
963 // Return the size of the saved packs if all of them has the same size.
964 std::optional<unsigned> getSavedPackSizeIfAllEqual() const {
965 unsigned PackSize = Packs[0].Saved.pack_size();
966
967 if (std::all_of(Packs.begin() + 1, Packs.end(), [&PackSize](const auto &P) {
968 return P.Saved.pack_size() == PackSize;
969 }))
970 return PackSize;
971 return {};
972 }
973
974 /// Determine whether this pack has already been deduced from a previous
975 /// argument.
976 bool isDeducedFromEarlierParameter() const {
977 return DeducedFromEarlierParameter;
978 }
979
980 /// Determine whether this pack has already been partially expanded into a
981 /// sequence of (prior) function parameters / template arguments.
982 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
983
984 /// Determine whether this pack expansion scope has a known, fixed arity.
985 /// This happens if it involves a pack from an outer template that has
986 /// (notionally) already been expanded.
987 bool hasFixedArity() { return FixedNumExpansions.has_value(); }
988
989 /// Determine whether the next element of the argument is still part of this
990 /// pack. This is the case unless the pack is already expanded to a fixed
991 /// length.
992 bool hasNextElement() {
993 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
994 }
995
996 /// Move to deducing the next element in each pack that is being deduced.
997 void nextPackElement() {
998 // Capture the deduced template arguments for each parameter pack expanded
999 // by this pack expansion, add them to the list of arguments we've deduced
1000 // for that pack, then clear out the deduced argument.
1001 if (!FinishingDeduction) {
1002 for (auto &Pack : Packs) {
1003 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
1004 if (!Pack.New.empty() || !DeducedArg.isNull()) {
1005 while (Pack.New.size() < PackElements)
1006 Pack.New.push_back(DeducedTemplateArgument());
1007 if (Pack.New.size() == PackElements)
1008 Pack.New.push_back(DeducedArg);
1009 else
1010 Pack.New[PackElements] = DeducedArg;
1011 DeducedArg = Pack.New.size() > PackElements + 1
1012 ? Pack.New[PackElements + 1]
1014 }
1015 }
1016 }
1017 ++PackElements;
1018 }
1019
1020 /// Finish template argument deduction for a set of argument packs,
1021 /// producing the argument packs and checking for consistency with prior
1022 /// deductions.
1023 TemplateDeductionResult finish() {
1024 if (FinishingDeduction)
1025 return TemplateDeductionResult::Success;
1026 // Build argument packs for each of the parameter packs expanded by this
1027 // pack expansion.
1028 for (auto &Pack : Packs) {
1029 // Put back the old value for this pack.
1030 if (!FinishingDeduction)
1031 Deduced[Pack.Index] = Pack.Saved;
1032
1033 // Always make sure the size of this pack is correct, even if we didn't
1034 // deduce any values for it.
1035 //
1036 // FIXME: This isn't required by the normative wording, but substitution
1037 // and post-substitution checking will always fail if the arity of any
1038 // pack is not equal to the number of elements we processed. (Either that
1039 // or something else has gone *very* wrong.) We're permitted to skip any
1040 // hard errors from those follow-on steps by the intent (but not the
1041 // wording) of C++ [temp.inst]p8:
1042 //
1043 // If the function selected by overload resolution can be determined
1044 // without instantiating a class template definition, it is unspecified
1045 // whether that instantiation actually takes place
1046 Pack.New.resize(PackElements);
1047
1048 // Build or find a new value for this pack.
1050 if (Pack.New.empty()) {
1051 // If we deduced an empty argument pack, create it now.
1053 } else {
1054 TemplateArgument *ArgumentPack =
1055 new (S.Context) TemplateArgument[Pack.New.size()];
1056 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
1057 NewPack = DeducedTemplateArgument(
1058 TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())),
1059 // FIXME: This is wrong, it's possible that some pack elements are
1060 // deduced from an array bound and others are not:
1061 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
1062 // g({1, 2, 3}, {{}, {}});
1063 // ... should deduce T = {int, size_t (from array bound)}.
1064 Pack.New[0].wasDeducedFromArrayBound());
1065 }
1066
1067 // Pick where we're going to put the merged pack.
1069 if (Pack.Outer) {
1070 if (Pack.Outer->DeferredDeduction.isNull()) {
1071 // Defer checking this pack until we have a complete pack to compare
1072 // it against.
1073 Pack.Outer->DeferredDeduction = NewPack;
1074 continue;
1075 }
1076 Loc = &Pack.Outer->DeferredDeduction;
1077 } else {
1078 Loc = &Deduced[Pack.Index];
1079 }
1080
1081 // Check the new pack matches any previous value.
1082 DeducedTemplateArgument OldPack = *Loc;
1084 S.Context, OldPack, NewPack, DeducePackIfNotAlreadyDeduced);
1085
1086 Info.AggregateDeductionCandidateHasMismatchedArity =
1087 OldPack.getKind() == TemplateArgument::Pack &&
1088 NewPack.getKind() == TemplateArgument::Pack &&
1089 OldPack.pack_size() != NewPack.pack_size() && !Result.isNull();
1090
1091 // If we deferred a deduction of this pack, check that one now too.
1092 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
1093 OldPack = Result;
1094 NewPack = Pack.DeferredDeduction;
1095 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
1096 }
1097
1098 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
1099 if (Result.isNull()) {
1100 Info.Param = makeTemplateParameter(Param);
1101 Info.FirstArg = OldPack;
1102 Info.SecondArg = NewPack;
1103 return TemplateDeductionResult::Inconsistent;
1104 }
1105
1106 // If we have a pre-expanded pack and we didn't deduce enough elements
1107 // for it, fail deduction.
1108 if (std::optional<unsigned> Expansions = getExpandedPackSize(Param)) {
1109 if (*Expansions != PackElements) {
1110 Info.Param = makeTemplateParameter(Param);
1111 Info.FirstArg = Result;
1112 return TemplateDeductionResult::IncompletePack;
1113 }
1114 }
1115
1116 *Loc = Result;
1117 }
1118
1119 return TemplateDeductionResult::Success;
1120 }
1121
1122private:
1123 Sema &S;
1124 TemplateParameterList *TemplateParams;
1127 unsigned PackElements = 0;
1128 bool IsPartiallyExpanded = false;
1129 bool DeducePackIfNotAlreadyDeduced = false;
1130 bool DeducedFromEarlierParameter = false;
1131 bool FinishingDeduction = false;
1132 /// The number of expansions, if we have a fully-expanded pack in this scope.
1133 std::optional<unsigned> FixedNumExpansions;
1134
1136};
1137
1138} // namespace
1139
1140template <class T>
1142 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1145 bool FinishingDeduction, T &&DeductFunc) {
1146 // C++0x [temp.deduct.type]p10:
1147 // Similarly, if P has a form that contains (T), then each parameter type
1148 // Pi of the respective parameter-type- list of P is compared with the
1149 // corresponding parameter type Ai of the corresponding parameter-type-list
1150 // of A. [...]
1151 unsigned ArgIdx = 0, ParamIdx = 0;
1152 for (; ParamIdx != Params.size(); ++ParamIdx) {
1153 // Check argument types.
1154 const PackExpansionType *Expansion
1155 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1156 if (!Expansion) {
1157 // Simple case: compare the parameter and argument types at this point.
1158
1159 // Make sure we have an argument.
1160 if (ArgIdx >= Args.size())
1161 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1162
1163 if (isa<PackExpansionType>(Args[ArgIdx])) {
1164 // C++0x [temp.deduct.type]p22:
1165 // If the original function parameter associated with A is a function
1166 // parameter pack and the function parameter associated with P is not
1167 // a function parameter pack, then template argument deduction fails.
1168 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1169 }
1170
1171 if (TemplateDeductionResult Result =
1172 DeductFunc(S, TemplateParams, ParamIdx, ArgIdx,
1173 Params[ParamIdx].getUnqualifiedType(),
1174 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, POK);
1175 Result != TemplateDeductionResult::Success)
1176 return Result;
1177
1178 ++ArgIdx;
1179 continue;
1180 }
1181
1182 // C++0x [temp.deduct.type]p10:
1183 // If the parameter-declaration corresponding to Pi is a function
1184 // parameter pack, then the type of its declarator- id is compared with
1185 // each remaining parameter type in the parameter-type-list of A. Each
1186 // comparison deduces template arguments for subsequent positions in the
1187 // template parameter packs expanded by the function parameter pack.
1188
1189 QualType Pattern = Expansion->getPattern();
1190 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern,
1191 /*DeducePackIfNotAlreadyDeduced=*/false,
1192 FinishingDeduction);
1193
1194 // A pack scope with fixed arity is not really a pack any more, so is not
1195 // a non-deduced context.
1196 if (ParamIdx + 1 == Params.size() || PackScope.hasFixedArity()) {
1197 for (; ArgIdx < Args.size() && PackScope.hasNextElement(); ++ArgIdx) {
1198 // Deduce template arguments from the pattern.
1199 if (TemplateDeductionResult Result = DeductFunc(
1200 S, TemplateParams, ParamIdx, ArgIdx,
1201 Pattern.getUnqualifiedType(), Args[ArgIdx].getUnqualifiedType(),
1202 Info, Deduced, POK);
1203 Result != TemplateDeductionResult::Success)
1204 return Result;
1205 PackScope.nextPackElement();
1206 }
1207 } else {
1208 // C++0x [temp.deduct.type]p5:
1209 // The non-deduced contexts are:
1210 // - A function parameter pack that does not occur at the end of the
1211 // parameter-declaration-clause.
1212 //
1213 // FIXME: There is no wording to say what we should do in this case. We
1214 // choose to resolve this by applying the same rule that is applied for a
1215 // function call: that is, deduce all contained packs to their
1216 // explicitly-specified values (or to <> if there is no such value).
1217 //
1218 // This is seemingly-arbitrarily different from the case of a template-id
1219 // with a non-trailing pack-expansion in its arguments, which renders the
1220 // entire template-argument-list a non-deduced context.
1221
1222 // If the parameter type contains an explicitly-specified pack that we
1223 // could not expand, skip the number of parameters notionally created
1224 // by the expansion.
1225 std::optional<unsigned> NumExpansions = Expansion->getNumExpansions();
1226 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1227 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
1228 ++I, ++ArgIdx)
1229 PackScope.nextPackElement();
1230 }
1231 }
1232
1233 // Build argument packs for each of the parameter packs expanded by this
1234 // pack expansion.
1235 if (auto Result = PackScope.finish();
1236 Result != TemplateDeductionResult::Success)
1237 return Result;
1238 }
1239
1240 // DR692, DR1395
1241 // C++0x [temp.deduct.type]p10:
1242 // If the parameter-declaration corresponding to P_i ...
1243 // During partial ordering, if Ai was originally a function parameter pack:
1244 // - if P does not contain a function parameter type corresponding to Ai then
1245 // Ai is ignored;
1246 if (POK == PartialOrderingKind::Call && ArgIdx + 1 == Args.size() &&
1247 isa<PackExpansionType>(Args[ArgIdx]))
1248 return TemplateDeductionResult::Success;
1249
1250 // Make sure we don't have any extra arguments.
1251 if (ArgIdx < Args.size())
1252 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1253
1254 return TemplateDeductionResult::Success;
1255}
1256
1257/// Deduce the template arguments by comparing the list of parameter
1258/// types to the list of argument types, as in the parameter-type-lists of
1259/// function types (C++ [temp.deduct.type]p10).
1260///
1261/// \param S The semantic analysis object within which we are deducing
1262///
1263/// \param TemplateParams The template parameters that we are deducing
1264///
1265/// \param Params The list of parameter types
1266///
1267/// \param Args The list of argument types
1268///
1269/// \param Info information about the template argument deduction itself
1270///
1271/// \param Deduced the deduced template arguments
1272///
1273/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1274/// how template argument deduction is performed.
1275///
1276/// \param PartialOrdering If true, we are performing template argument
1277/// deduction for during partial ordering for a call
1278/// (C++0x [temp.deduct.partial]).
1279///
1280/// \param HasDeducedAnyParam If set, the object pointed at will indicate
1281/// whether any template parameter was deduced.
1282///
1283/// \param HasDeducedParam If set, the bit vector will be used to represent
1284/// which template parameters were deduced, in order.
1285///
1286/// \returns the result of template argument deduction so far. Note that a
1287/// "success" result means that template argument deduction has not yet failed,
1288/// but it may still fail, later, for other reasons.
1290 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1292 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1293 PartialOrderingKind POK, bool *HasDeducedAnyParam,
1294 llvm::SmallBitVector *HasDeducedParam) {
1295 return ::DeduceForEachType(
1296 S, TemplateParams, Params, Args, Info, Deduced, POK,
1297 /*FinishingDeduction=*/false,
1298 [&](Sema &S, TemplateParameterList *TemplateParams, int ParamIdx,
1299 int ArgIdx, QualType P, QualType A, TemplateDeductionInfo &Info,
1301 PartialOrderingKind POK) {
1302 bool HasDeducedAnyParamCopy = false;
1304 S, TemplateParams, P, A, Info, Deduced, TDF, POK,
1305 /*DeducedFromArrayBound=*/false, &HasDeducedAnyParamCopy);
1306 if (HasDeducedAnyParam && HasDeducedAnyParamCopy)
1307 *HasDeducedAnyParam = true;
1308 if (HasDeducedParam && HasDeducedAnyParamCopy)
1309 (*HasDeducedParam)[ParamIdx] = true;
1310 return TDR;
1311 });
1312}
1313
1314/// Determine whether the parameter has qualifiers that the argument
1315/// lacks. Put another way, determine whether there is no way to add
1316/// a deduced set of qualifiers to the ParamType that would result in
1317/// its qualifiers matching those of the ArgType.
1319 QualType ArgType) {
1320 Qualifiers ParamQs = ParamType.getQualifiers();
1321 Qualifiers ArgQs = ArgType.getQualifiers();
1322
1323 if (ParamQs == ArgQs)
1324 return false;
1325
1326 // Mismatched (but not missing) Objective-C GC attributes.
1327 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1328 ParamQs.hasObjCGCAttr())
1329 return true;
1330
1331 // Mismatched (but not missing) address spaces.
1332 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1333 ParamQs.hasAddressSpace())
1334 return true;
1335
1336 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1337 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1338 ParamQs.hasObjCLifetime())
1339 return true;
1340
1341 // CVR qualifiers inconsistent or a superset.
1342 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1343}
1344
1346 const FunctionType *PF = P->getAs<FunctionType>(),
1347 *AF = A->getAs<FunctionType>();
1348
1349 // Just compare if not functions.
1350 if (!PF || !AF)
1351 return Context.hasSameType(P, A);
1352
1353 // Noreturn and noexcept adjustment.
1354 if (QualType AdjustedParam; IsFunctionConversion(P, A, AdjustedParam))
1355 P = AdjustedParam;
1356
1357 // FIXME: Compatible calling conventions.
1359}
1360
1361/// Get the index of the first template parameter that was originally from the
1362/// innermost template-parameter-list. This is 0 except when we concatenate
1363/// the template parameter lists of a class template and a constructor template
1364/// when forming an implicit deduction guide.
1366 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1367 if (!Guide || !Guide->isImplicit())
1368 return 0;
1369 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1370}
1371
1372/// Determine whether a type denotes a forwarding reference.
1373static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1374 // C++1z [temp.deduct.call]p3:
1375 // A forwarding reference is an rvalue reference to a cv-unqualified
1376 // template parameter that does not represent a template parameter of a
1377 // class template.
1378 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1379 if (ParamRef->getPointeeType().getQualifiers())
1380 return false;
1381 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1382 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1383 }
1384 return false;
1385}
1386
1387/// Attempt to deduce the template arguments by checking the base types
1388/// according to (C++20 [temp.deduct.call] p4b3.
1389///
1390/// \param S the semantic analysis object within which we are deducing.
1391///
1392/// \param RD the top level record object we are deducing against.
1393///
1394/// \param TemplateParams the template parameters that we are deducing.
1395///
1396/// \param P the template specialization parameter type.
1397///
1398/// \param Info information about the template argument deduction itself.
1399///
1400/// \param Deduced the deduced template arguments.
1401///
1402/// \returns the result of template argument deduction with the bases. "invalid"
1403/// means no matches, "success" found a single item, and the
1404/// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
1407 TemplateParameterList *TemplateParams, QualType P,
1410 bool *HasDeducedAnyParam) {
1411 // C++14 [temp.deduct.call] p4b3:
1412 // If P is a class and P has the form simple-template-id, then the
1413 // transformed A can be a derived class of the deduced A. Likewise if
1414 // P is a pointer to a class of the form simple-template-id, the
1415 // transformed A can be a pointer to a derived class pointed to by the
1416 // deduced A. However, if there is a class C that is a (direct or
1417 // indirect) base class of D and derived (directly or indirectly) from a
1418 // class B and that would be a valid deduced A, the deduced A cannot be
1419 // B or pointer to B, respectively.
1420 //
1421 // These alternatives are considered only if type deduction would
1422 // otherwise fail. If they yield more than one possible deduced A, the
1423 // type deduction fails.
1424
1425 // Use a breadth-first search through the bases to collect the set of
1426 // successful matches. Visited contains the set of nodes we have already
1427 // visited, while ToVisit is our stack of records that we still need to
1428 // visit. Matches contains a list of matches that have yet to be
1429 // disqualified.
1432 // We iterate over this later, so we have to use MapVector to ensure
1433 // determinism.
1434 struct MatchValue {
1436 bool HasDeducedAnyParam;
1437 };
1438 llvm::MapVector<const CXXRecordDecl *, MatchValue> Matches;
1439
1440 auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
1441 for (const auto &Base : RD->bases()) {
1442 QualType T = Base.getType();
1443 assert(T->isRecordType() && "Base class that isn't a record?");
1444 if (Visited.insert(T->getAsCXXRecordDecl()).second)
1445 ToVisit.push_back(T);
1446 }
1447 };
1448
1449 // Set up the loop by adding all the bases.
1450 AddBases(RD);
1451
1452 // Search each path of bases until we either run into a successful match
1453 // (where all bases of it are invalid), or we run out of bases.
1454 while (!ToVisit.empty()) {
1455 QualType NextT = ToVisit.pop_back_val();
1456
1457 SmallVector<DeducedTemplateArgument, 8> DeducedCopy(Deduced.begin(),
1458 Deduced.end());
1460 bool HasDeducedAnyParamCopy = false;
1462 S, TemplateParams, P, NextT, BaseInfo, PartialOrdering, DeducedCopy,
1463 &HasDeducedAnyParamCopy);
1464
1465 // If this was a successful deduction, add it to the list of matches,
1466 // otherwise we need to continue searching its bases.
1467 const CXXRecordDecl *RD = NextT->getAsCXXRecordDecl();
1469 Matches.insert({RD, {DeducedCopy, HasDeducedAnyParamCopy}});
1470 else
1471 AddBases(RD);
1472 }
1473
1474 // At this point, 'Matches' contains a list of seemingly valid bases, however
1475 // in the event that we have more than 1 match, it is possible that the base
1476 // of one of the matches might be disqualified for being a base of another
1477 // valid match. We can count on cyclical instantiations being invalid to
1478 // simplify the disqualifications. That is, if A & B are both matches, and B
1479 // inherits from A (disqualifying A), we know that A cannot inherit from B.
1480 if (Matches.size() > 1) {
1481 Visited.clear();
1482 for (const auto &Match : Matches)
1483 AddBases(Match.first);
1484
1485 // We can give up once we have a single item (or have run out of things to
1486 // search) since cyclical inheritance isn't valid.
1487 while (Matches.size() > 1 && !ToVisit.empty()) {
1488 const CXXRecordDecl *RD = ToVisit.pop_back_val()->getAsCXXRecordDecl();
1489 Matches.erase(RD);
1490
1491 // Always add all bases, since the inheritance tree can contain
1492 // disqualifications for multiple matches.
1493 AddBases(RD);
1494 }
1495 }
1496
1497 if (Matches.empty())
1499 if (Matches.size() > 1)
1501
1502 std::swap(Matches.front().second.Deduced, Deduced);
1503 if (bool HasDeducedAnyParamCopy = Matches.front().second.HasDeducedAnyParam;
1504 HasDeducedAnyParamCopy && HasDeducedAnyParam)
1505 *HasDeducedAnyParam = HasDeducedAnyParamCopy;
1507}
1508
1509/// When propagating a partial ordering kind into a NonCall context,
1510/// this is used to downgrade a 'Call' into a 'NonCall', so that
1511/// the kind still reflects whether we are in a partial ordering context.
1514 return std::min(POK, PartialOrderingKind::NonCall);
1515}
1516
1517/// Deduce the template arguments by comparing the parameter type and
1518/// the argument type (C++ [temp.deduct.type]).
1519///
1520/// \param S the semantic analysis object within which we are deducing
1521///
1522/// \param TemplateParams the template parameters that we are deducing
1523///
1524/// \param P the parameter type
1525///
1526/// \param A the argument type
1527///
1528/// \param Info information about the template argument deduction itself
1529///
1530/// \param Deduced the deduced template arguments
1531///
1532/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1533/// how template argument deduction is performed.
1534///
1535/// \param PartialOrdering Whether we're performing template argument deduction
1536/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1537///
1538/// \returns the result of template argument deduction so far. Note that a
1539/// "success" result means that template argument deduction has not yet failed,
1540/// but it may still fail, later, for other reasons.
1542 Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
1544 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1545 PartialOrderingKind POK, bool DeducedFromArrayBound,
1546 bool *HasDeducedAnyParam) {
1547
1548 // If the argument type is a pack expansion, look at its pattern.
1549 // This isn't explicitly called out
1550 if (const auto *AExp = dyn_cast<PackExpansionType>(A))
1551 A = AExp->getPattern();
1552 assert(!isa<PackExpansionType>(A.getCanonicalType()));
1553
1554 if (POK == PartialOrderingKind::Call) {
1555 // C++11 [temp.deduct.partial]p5:
1556 // Before the partial ordering is done, certain transformations are
1557 // performed on the types used for partial ordering:
1558 // - If P is a reference type, P is replaced by the type referred to.
1559 const ReferenceType *PRef = P->getAs<ReferenceType>();
1560 if (PRef)
1561 P = PRef->getPointeeType();
1562
1563 // - If A is a reference type, A is replaced by the type referred to.
1564 const ReferenceType *ARef = A->getAs<ReferenceType>();
1565 if (ARef)
1566 A = A->getPointeeType();
1567
1568 if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
1569 // C++11 [temp.deduct.partial]p9:
1570 // If, for a given type, deduction succeeds in both directions (i.e.,
1571 // the types are identical after the transformations above) and both
1572 // P and A were reference types [...]:
1573 // - if [one type] was an lvalue reference and [the other type] was
1574 // not, [the other type] is not considered to be at least as
1575 // specialized as [the first type]
1576 // - if [one type] is more cv-qualified than [the other type],
1577 // [the other type] is not considered to be at least as specialized
1578 // as [the first type]
1579 // Objective-C ARC adds:
1580 // - [one type] has non-trivial lifetime, [the other type] has
1581 // __unsafe_unretained lifetime, and the types are otherwise
1582 // identical
1583 //
1584 // A is "considered to be at least as specialized" as P iff deduction
1585 // succeeds, so we model this as a deduction failure. Note that
1586 // [the first type] is P and [the other type] is A here; the standard
1587 // gets this backwards.
1588 Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
1589 if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
1590 PQuals.isStrictSupersetOf(AQuals) ||
1591 (PQuals.hasNonTrivialObjCLifetime() &&
1592 AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1593 PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
1594 Info.FirstArg = TemplateArgument(P);
1595 Info.SecondArg = TemplateArgument(A);
1597 }
1598 }
1599 Qualifiers DiscardedQuals;
1600 // C++11 [temp.deduct.partial]p7:
1601 // Remove any top-level cv-qualifiers:
1602 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1603 // version of P.
1604 P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
1605 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1606 // version of A.
1607 A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
1608 } else {
1609 // C++0x [temp.deduct.call]p4 bullet 1:
1610 // - If the original P is a reference type, the deduced A (i.e., the type
1611 // referred to by the reference) can be more cv-qualified than the
1612 // transformed A.
1613 if (TDF & TDF_ParamWithReferenceType) {
1614 Qualifiers Quals;
1615 QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
1617 P = S.Context.getQualifiedType(UnqualP, Quals);
1618 }
1619
1620 if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
1621 // C++0x [temp.deduct.type]p10:
1622 // If P and A are function types that originated from deduction when
1623 // taking the address of a function template (14.8.2.2) or when deducing
1624 // template arguments from a function declaration (14.8.2.6) and Pi and
1625 // Ai are parameters of the top-level parameter-type-list of P and A,
1626 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1627 // is an lvalue reference, in
1628 // which case the type of Pi is changed to be the template parameter
1629 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1630 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1631 // deduced as X&. - end note ]
1632 TDF &= ~TDF_TopLevelParameterTypeList;
1633 if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
1635 P = P->getPointeeType();
1636 }
1637 }
1638
1639 // C++ [temp.deduct.type]p9:
1640 // A template type argument T, a template template argument TT or a
1641 // template non-type argument i can be deduced if P and A have one of
1642 // the following forms:
1643 //
1644 // T
1645 // cv-list T
1646 if (const auto *TTP = P->getAs<TemplateTypeParmType>()) {
1647 // Just skip any attempts to deduce from a placeholder type or a parameter
1648 // at a different depth.
1649 if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
1651
1652 unsigned Index = TTP->getIndex();
1653
1654 // If the argument type is an array type, move the qualifiers up to the
1655 // top level, so they can be matched with the qualifiers on the parameter.
1656 if (A->isArrayType()) {
1657 Qualifiers Quals;
1658 A = S.Context.getUnqualifiedArrayType(A, Quals);
1659 if (Quals)
1660 A = S.Context.getQualifiedType(A, Quals);
1661 }
1662
1663 // The argument type can not be less qualified than the parameter
1664 // type.
1665 if (!(TDF & TDF_IgnoreQualifiers) &&
1667 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1668 Info.FirstArg = TemplateArgument(P);
1669 Info.SecondArg = TemplateArgument(A);
1671 }
1672
1673 // Do not match a function type with a cv-qualified type.
1674 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1675 if (A->isFunctionType() && P.hasQualifiers())
1677
1678 assert(TTP->getDepth() == Info.getDeducedDepth() &&
1679 "saw template type parameter with wrong depth");
1680 assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&
1681 "Unresolved overloaded function");
1683
1684 // Remove any qualifiers on the parameter from the deduced type.
1685 // We checked the qualifiers for consistency above.
1686 Qualifiers DeducedQs = DeducedType.getQualifiers();
1687 Qualifiers ParamQs = P.getQualifiers();
1688 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1689 if (ParamQs.hasObjCGCAttr())
1690 DeducedQs.removeObjCGCAttr();
1691 if (ParamQs.hasAddressSpace())
1692 DeducedQs.removeAddressSpace();
1693 if (ParamQs.hasObjCLifetime())
1694 DeducedQs.removeObjCLifetime();
1695
1696 // Objective-C ARC:
1697 // If template deduction would produce a lifetime qualifier on a type
1698 // that is not a lifetime type, template argument deduction fails.
1699 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1701 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1702 Info.FirstArg = TemplateArgument(P);
1703 Info.SecondArg = TemplateArgument(A);
1705 }
1706
1707 // Objective-C ARC:
1708 // If template deduction would produce an argument type with lifetime type
1709 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1710 if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
1711 !DeducedQs.hasObjCLifetime())
1713
1714 DeducedType =
1715 S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
1716
1717 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1719 checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
1720 if (Result.isNull()) {
1721 // We can also get inconsistencies when matching NTTP type.
1722 switch (NamedDecl *Param = TemplateParams->getParam(Index);
1723 Param->getKind()) {
1724 case Decl::TemplateTypeParm:
1725 Info.Param = cast<TemplateTypeParmDecl>(Param);
1726 break;
1727 case Decl::NonTypeTemplateParm:
1728 Info.Param = cast<NonTypeTemplateParmDecl>(Param);
1729 break;
1730 case Decl::TemplateTemplateParm:
1731 Info.Param = cast<TemplateTemplateParmDecl>(Param);
1732 break;
1733 default:
1734 llvm_unreachable("unexpected kind");
1735 }
1736 Info.FirstArg = Deduced[Index];
1737 Info.SecondArg = NewDeduced;
1739 }
1740
1741 Deduced[Index] = Result;
1742 if (HasDeducedAnyParam)
1743 *HasDeducedAnyParam = true;
1745 }
1746
1747 // Set up the template argument deduction information for a failure.
1748 Info.FirstArg = TemplateArgument(P);
1749 Info.SecondArg = TemplateArgument(A);
1750
1751 // If the parameter is an already-substituted template parameter
1752 // pack, do nothing: we don't know which of its arguments to look
1753 // at, so we have to wait until all of the parameter packs in this
1754 // expansion have arguments.
1755 if (P->getAs<SubstTemplateTypeParmPackType>())
1757
1758 // Check the cv-qualifiers on the parameter and argument types.
1759 if (!(TDF & TDF_IgnoreQualifiers)) {
1760 if (TDF & TDF_ParamWithReferenceType) {
1763 } else if (TDF & TDF_ArgWithReferenceType) {
1764 // C++ [temp.deduct.conv]p4:
1765 // If the original A is a reference type, A can be more cv-qualified
1766 // than the deduced A
1767 if (!A.getQualifiers().compatiblyIncludes(P.getQualifiers(),
1768 S.getASTContext()))
1770
1771 // Strip out all extra qualifiers from the argument to figure out the
1772 // type we're converting to, prior to the qualification conversion.
1773 Qualifiers Quals;
1774 A = S.Context.getUnqualifiedArrayType(A, Quals);
1775 A = S.Context.getQualifiedType(A, P.getQualifiers());
1776 } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
1777 if (P.getCVRQualifiers() != A.getCVRQualifiers())
1779 }
1780 }
1781
1782 // If the parameter type is not dependent, there is nothing to deduce.
1783 if (!P->isDependentType()) {
1784 if (TDF & TDF_SkipNonDependent)
1787 : S.Context.hasSameType(P, A))
1792 if (!(TDF & TDF_IgnoreQualifiers))
1794 // Otherwise, when ignoring qualifiers, the types not having the same
1795 // unqualified type does not mean they do not match, so in this case we
1796 // must keep going and analyze with a non-dependent parameter type.
1797 }
1798
1799 switch (P.getCanonicalType()->getTypeClass()) {
1800 // Non-canonical types cannot appear here.
1801#define NON_CANONICAL_TYPE(Class, Base) \
1802 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1803#define TYPE(Class, Base)
1804#include "clang/AST/TypeNodes.inc"
1805
1806 case Type::TemplateTypeParm:
1807 case Type::SubstTemplateTypeParmPack:
1808 llvm_unreachable("Type nodes handled above");
1809
1810 case Type::Auto:
1811 // C++23 [temp.deduct.funcaddr]/3:
1812 // A placeholder type in the return type of a function template is a
1813 // non-deduced context.
1814 // There's no corresponding wording for [temp.deduct.decl], but we treat
1815 // it the same to match other compilers.
1816 if (P->isDependentType())
1818 [[fallthrough]];
1819 case Type::Builtin:
1820 case Type::VariableArray:
1821 case Type::Vector:
1822 case Type::FunctionNoProto:
1823 case Type::Record:
1824 case Type::Enum:
1825 case Type::ObjCObject:
1826 case Type::ObjCInterface:
1827 case Type::ObjCObjectPointer:
1828 case Type::BitInt:
1829 return (TDF & TDF_SkipNonDependent) ||
1830 ((TDF & TDF_IgnoreQualifiers)
1832 : S.Context.hasSameType(P, A))
1835
1836 // _Complex T [placeholder extension]
1837 case Type::Complex: {
1838 const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
1839 if (!CA)
1842 S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
1843 Deduced, TDF, degradeCallPartialOrderingKind(POK),
1844 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1845 }
1846
1847 // _Atomic T [extension]
1848 case Type::Atomic: {
1849 const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
1850 if (!AA)
1853 S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
1854 Deduced, TDF, degradeCallPartialOrderingKind(POK),
1855 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1856 }
1857
1858 // T *
1859 case Type::Pointer: {
1860 QualType PointeeType;
1861 if (const auto *PA = A->getAs<PointerType>()) {
1862 PointeeType = PA->getPointeeType();
1863 } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
1864 PointeeType = PA->getPointeeType();
1865 } else {
1867 }
1869 S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
1870 PointeeType, Info, Deduced,
1873 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1874 }
1875
1876 // T &
1877 case Type::LValueReference: {
1878 const auto *RP = P->castAs<LValueReferenceType>(),
1879 *RA = A->getAs<LValueReferenceType>();
1880 if (!RA)
1882
1884 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1885 Deduced, 0, degradeCallPartialOrderingKind(POK),
1886 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1887 }
1888
1889 // T && [C++0x]
1890 case Type::RValueReference: {
1891 const auto *RP = P->castAs<RValueReferenceType>(),
1892 *RA = A->getAs<RValueReferenceType>();
1893 if (!RA)
1895
1897 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1898 Deduced, 0, degradeCallPartialOrderingKind(POK),
1899 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1900 }
1901
1902 // T [] (implied, but not stated explicitly)
1903 case Type::IncompleteArray: {
1904 const auto *IAA = S.Context.getAsIncompleteArrayType(A);
1905 if (!IAA)
1907
1908 const auto *IAP = S.Context.getAsIncompleteArrayType(P);
1909 assert(IAP && "Template parameter not of incomplete array type");
1910
1912 S, TemplateParams, IAP->getElementType(), IAA->getElementType(), Info,
1913 Deduced, TDF & TDF_IgnoreQualifiers,
1915 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1916 }
1917
1918 // T [integer-constant]
1919 case Type::ConstantArray: {
1920 const auto *CAA = S.Context.getAsConstantArrayType(A),
1922 assert(CAP);
1923 if (!CAA || CAA->getSize() != CAP->getSize())
1925
1927 S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
1928 Deduced, TDF & TDF_IgnoreQualifiers,
1930 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1931 }
1932
1933 // type [i]
1934 case Type::DependentSizedArray: {
1935 const auto *AA = S.Context.getAsArrayType(A);
1936 if (!AA)
1938
1939 // Check the element type of the arrays
1940 const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
1941 assert(DAP);
1943 S, TemplateParams, DAP->getElementType(), AA->getElementType(),
1944 Info, Deduced, TDF & TDF_IgnoreQualifiers,
1946 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1948 return Result;
1949
1950 // Determine the array bound is something we can deduce.
1951 const NonTypeTemplateParmDecl *NTTP =
1952 getDeducedParameterFromExpr(Info, DAP->getSizeExpr());
1953 if (!NTTP)
1955
1956 // We can perform template argument deduction for the given non-type
1957 // template parameter.
1958 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1959 "saw non-type template parameter with wrong depth");
1960 if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
1961 llvm::APSInt Size(CAA->getSize());
1963 S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
1964 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
1965 Deduced, HasDeducedAnyParam);
1966 }
1967 if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
1968 if (DAA->getSizeExpr())
1970 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info,
1971 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
1972
1973 // Incomplete type does not match a dependently-sized array type
1975 }
1976
1977 // type(*)(T)
1978 // T(*)()
1979 // T(*)(T)
1980 case Type::FunctionProto: {
1981 const auto *FPP = P->castAs<FunctionProtoType>(),
1982 *FPA = A->getAs<FunctionProtoType>();
1983 if (!FPA)
1985
1986 if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
1987 FPP->getRefQualifier() != FPA->getRefQualifier() ||
1988 FPP->isVariadic() != FPA->isVariadic())
1990
1991 // Check return types.
1993 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
1994 Info, Deduced, 0, degradeCallPartialOrderingKind(POK),
1995 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1997 return Result;
1998
1999 // Check parameter types.
2001 S, TemplateParams, FPP->param_types(), FPA->param_types(), Info,
2002 Deduced, TDF & TDF_TopLevelParameterTypeList, POK,
2003 HasDeducedAnyParam,
2004 /*HasDeducedParam=*/nullptr);
2006 return Result;
2007
2010
2011 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
2012 // deducing through the noexcept-specifier if it's part of the canonical
2013 // type. libstdc++ relies on this.
2014 Expr *NoexceptExpr = FPP->getNoexceptExpr();
2015 if (const NonTypeTemplateParmDecl *NTTP =
2016 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
2017 : nullptr) {
2018 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
2019 "saw non-type template parameter with wrong depth");
2020
2021 llvm::APSInt Noexcept(1);
2022 switch (FPA->canThrow()) {
2023 case CT_Cannot:
2024 Noexcept = 1;
2025 [[fallthrough]];
2026
2027 case CT_Can:
2028 // We give E in noexcept(E) the "deduced from array bound" treatment.
2029 // FIXME: Should we?
2031 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
2032 /*DeducedFromArrayBound=*/true, Info,
2033 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2034
2035 case CT_Dependent:
2036 if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
2038 S, TemplateParams, NTTP, ArgNoexceptExpr, Info,
2039 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2040 // Can't deduce anything from throw(T...).
2041 break;
2042 }
2043 }
2044 // FIXME: Detect non-deduced exception specification mismatches?
2045 //
2046 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
2047 // top-level differences in noexcept-specifications.
2048
2050 }
2051
2052 case Type::InjectedClassName:
2053 // Treat a template's injected-class-name as if the template
2054 // specialization type had been used.
2055
2056 // template-name<T> (where template-name refers to a class template)
2057 // template-name<i>
2058 // TT<T>
2059 // TT<i>
2060 // TT<>
2061 case Type::TemplateSpecialization: {
2062 // When Arg cannot be a derived class, we can just try to deduce template
2063 // arguments from the template-id.
2064 if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
2065 return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
2066 POK != PartialOrderingKind::None,
2067 Deduced, HasDeducedAnyParam);
2068
2069 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
2070 Deduced.end());
2071
2073 S, TemplateParams, P, A, Info, POK != PartialOrderingKind::None,
2074 Deduced, HasDeducedAnyParam);
2076 return Result;
2077
2078 // We cannot inspect base classes as part of deduction when the type
2079 // is incomplete, so either instantiate any templates necessary to
2080 // complete the type, or skip over it if it cannot be completed.
2081 if (!S.isCompleteType(Info.getLocation(), A))
2082 return Result;
2083
2084 const CXXRecordDecl *RD = A->getAsCXXRecordDecl();
2085 if (RD->isInvalidDecl())
2086 return Result;
2087
2088 // Reset the incorrectly deduced argument from above.
2089 Deduced = DeducedOrig;
2090
2091 // Check bases according to C++14 [temp.deduct.call] p4b3:
2092 auto BaseResult = DeduceTemplateBases(S, RD, TemplateParams, P, Info,
2093 POK != PartialOrderingKind::None,
2094 Deduced, HasDeducedAnyParam);
2096 : Result;
2097 }
2098
2099 // T type::*
2100 // T T::*
2101 // T (type::*)()
2102 // type (T::*)()
2103 // type (type::*)(T)
2104 // type (T::*)(T)
2105 // T (type::*)(T)
2106 // T (T::*)()
2107 // T (T::*)(T)
2108 case Type::MemberPointer: {
2109 const auto *MPP = P->castAs<MemberPointerType>(),
2110 *MPA = A->getAs<MemberPointerType>();
2111 if (!MPA)
2113
2114 QualType PPT = MPP->getPointeeType();
2115 if (PPT->isFunctionType())
2116 S.adjustMemberFunctionCC(PPT, /*HasThisPointer=*/false,
2117 /*IsCtorOrDtor=*/false, Info.getLocation());
2118 QualType APT = MPA->getPointeeType();
2119 if (APT->isFunctionType())
2120 S.adjustMemberFunctionCC(APT, /*HasThisPointer=*/false,
2121 /*IsCtorOrDtor=*/false, Info.getLocation());
2122
2123 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
2125 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF,
2127 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2129 return Result;
2131 S, TemplateParams, QualType(MPP->getClass(), 0),
2132 QualType(MPA->getClass(), 0), Info, Deduced, SubTDF,
2134 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2135 }
2136
2137 // (clang extension)
2138 //
2139 // type(^)(T)
2140 // T(^)()
2141 // T(^)(T)
2142 case Type::BlockPointer: {
2143 const auto *BPP = P->castAs<BlockPointerType>(),
2144 *BPA = A->getAs<BlockPointerType>();
2145 if (!BPA)
2148 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
2149 Deduced, 0, degradeCallPartialOrderingKind(POK),
2150 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2151 }
2152
2153 // (clang extension)
2154 //
2155 // T __attribute__(((ext_vector_type(<integral constant>))))
2156 case Type::ExtVector: {
2157 const auto *VP = P->castAs<ExtVectorType>();
2158 QualType ElementType;
2159 if (const auto *VA = A->getAs<ExtVectorType>()) {
2160 // Make sure that the vectors have the same number of elements.
2161 if (VP->getNumElements() != VA->getNumElements())
2163 ElementType = VA->getElementType();
2164 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2165 // We can't check the number of elements, since the argument has a
2166 // dependent number of elements. This can only occur during partial
2167 // ordering.
2168 ElementType = VA->getElementType();
2169 } else {
2171 }
2172 // Perform deduction on the element types.
2174 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
2176 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2177 }
2178
2179 case Type::DependentVector: {
2180 const auto *VP = P->castAs<DependentVectorType>();
2181
2182 if (const auto *VA = A->getAs<VectorType>()) {
2183 // Perform deduction on the element types.
2185 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2186 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2187 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2189 return Result;
2190
2191 // Perform deduction on the vector size, if we can.
2192 const NonTypeTemplateParmDecl *NTTP =
2193 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2194 if (!NTTP)
2196
2197 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2198 ArgSize = VA->getNumElements();
2199 // Note that we use the "array bound" rules here; just like in that
2200 // case, we don't have any particular type for the vector size, but
2201 // we can provide one if necessary.
2203 S, TemplateParams, NTTP, ArgSize, S.Context.UnsignedIntTy, true,
2204 Info, POK != PartialOrderingKind::None, Deduced,
2205 HasDeducedAnyParam);
2206 }
2207
2208 if (const auto *VA = A->getAs<DependentVectorType>()) {
2209 // Perform deduction on the element types.
2211 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2212 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2213 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2215 return Result;
2216
2217 // Perform deduction on the vector size, if we can.
2218 const NonTypeTemplateParmDecl *NTTP =
2219 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2220 if (!NTTP)
2222
2224 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2225 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2226 }
2227
2229 }
2230
2231 // (clang extension)
2232 //
2233 // T __attribute__(((ext_vector_type(N))))
2234 case Type::DependentSizedExtVector: {
2235 const auto *VP = P->castAs<DependentSizedExtVectorType>();
2236
2237 if (const auto *VA = A->getAs<ExtVectorType>()) {
2238 // Perform deduction on the element types.
2240 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2241 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2242 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2244 return Result;
2245
2246 // Perform deduction on the vector size, if we can.
2247 const NonTypeTemplateParmDecl *NTTP =
2248 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2249 if (!NTTP)
2251
2252 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2253 ArgSize = VA->getNumElements();
2254 // Note that we use the "array bound" rules here; just like in that
2255 // case, we don't have any particular type for the vector size, but
2256 // we can provide one if necessary.
2258 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2259 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2260 }
2261
2262 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2263 // Perform deduction on the element types.
2265 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2266 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2267 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2269 return Result;
2270
2271 // Perform deduction on the vector size, if we can.
2272 const NonTypeTemplateParmDecl *NTTP =
2273 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2274 if (!NTTP)
2276
2278 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2279 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2280 }
2281
2283 }
2284
2285 // (clang extension)
2286 //
2287 // T __attribute__((matrix_type(<integral constant>,
2288 // <integral constant>)))
2289 case Type::ConstantMatrix: {
2290 const auto *MP = P->castAs<ConstantMatrixType>(),
2291 *MA = A->getAs<ConstantMatrixType>();
2292 if (!MA)
2294
2295 // Check that the dimensions are the same
2296 if (MP->getNumRows() != MA->getNumRows() ||
2297 MP->getNumColumns() != MA->getNumColumns()) {
2299 }
2300 // Perform deduction on element types.
2302 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2303 Deduced, TDF, degradeCallPartialOrderingKind(POK),
2304 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2305 }
2306
2307 case Type::DependentSizedMatrix: {
2308 const auto *MP = P->castAs<DependentSizedMatrixType>();
2309 const auto *MA = A->getAs<MatrixType>();
2310 if (!MA)
2312
2313 // Check the element type of the matrixes.
2315 S, TemplateParams, MP->getElementType(), MA->getElementType(),
2316 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2317 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2319 return Result;
2320
2321 // Try to deduce a matrix dimension.
2322 auto DeduceMatrixArg =
2323 [&S, &Info, &Deduced, &TemplateParams, &HasDeducedAnyParam, POK](
2324 Expr *ParamExpr, const MatrixType *A,
2325 unsigned (ConstantMatrixType::*GetArgDimension)() const,
2326 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2327 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2328 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
2329 if (!ParamExpr->isValueDependent()) {
2330 std::optional<llvm::APSInt> ParamConst =
2331 ParamExpr->getIntegerConstantExpr(S.Context);
2332 if (!ParamConst)
2334
2335 if (ACM) {
2336 if ((ACM->*GetArgDimension)() == *ParamConst)
2339 }
2340
2341 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2342 if (std::optional<llvm::APSInt> ArgConst =
2343 ArgExpr->getIntegerConstantExpr(S.Context))
2344 if (*ArgConst == *ParamConst)
2347 }
2348
2349 const NonTypeTemplateParmDecl *NTTP =
2350 getDeducedParameterFromExpr(Info, ParamExpr);
2351 if (!NTTP)
2353
2354 if (ACM) {
2355 llvm::APSInt ArgConst(
2357 ArgConst = (ACM->*GetArgDimension)();
2359 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
2360 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
2361 Deduced, HasDeducedAnyParam);
2362 }
2363
2365 S, TemplateParams, NTTP, (ADM->*GetArgDimensionExpr)(), Info,
2366 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2367 };
2368
2369 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
2373 return Result;
2374
2375 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2378 }
2379
2380 // (clang extension)
2381 //
2382 // T __attribute__(((address_space(N))))
2383 case Type::DependentAddressSpace: {
2384 const auto *ASP = P->castAs<DependentAddressSpaceType>();
2385
2386 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
2387 // Perform deduction on the pointer type.
2389 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2390 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2391 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2393 return Result;
2394
2395 // Perform deduction on the address space, if we can.
2396 const NonTypeTemplateParmDecl *NTTP =
2397 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2398 if (!NTTP)
2400
2402 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info,
2403 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2404 }
2405
2407 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2408 false);
2409 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
2410
2411 // Perform deduction on the pointer types.
2413 S, TemplateParams, ASP->getPointeeType(),
2414 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF,
2416 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2418 return Result;
2419
2420 // Perform deduction on the address space, if we can.
2421 const NonTypeTemplateParmDecl *NTTP =
2422 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2423 if (!NTTP)
2425
2427 S, TemplateParams, NTTP, ArgAddressSpace, S.Context.IntTy, true,
2428 Info, POK != PartialOrderingKind::None, Deduced,
2429 HasDeducedAnyParam);
2430 }
2431
2433 }
2434 case Type::DependentBitInt: {
2435 const auto *IP = P->castAs<DependentBitIntType>();
2436
2437 if (const auto *IA = A->getAs<BitIntType>()) {
2438 if (IP->isUnsigned() != IA->isUnsigned())
2440
2441 const NonTypeTemplateParmDecl *NTTP =
2442 getDeducedParameterFromExpr(Info, IP->getNumBitsExpr());
2443 if (!NTTP)
2445
2446 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2447 ArgSize = IA->getNumBits();
2448
2450 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2451 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2452 }
2453
2454 if (const auto *IA = A->getAs<DependentBitIntType>()) {
2455 if (IP->isUnsigned() != IA->isUnsigned())
2458 }
2459
2461 }
2462
2463 case Type::TypeOfExpr:
2464 case Type::TypeOf:
2465 case Type::DependentName:
2466 case Type::UnresolvedUsing:
2467 case Type::Decltype:
2468 case Type::UnaryTransform:
2469 case Type::DeducedTemplateSpecialization:
2470 case Type::DependentTemplateSpecialization:
2471 case Type::PackExpansion:
2472 case Type::Pipe:
2473 case Type::ArrayParameter:
2474 case Type::HLSLAttributedResource:
2475 // No template argument deduction for these types
2477
2478 case Type::PackIndexing: {
2479 const PackIndexingType *PIT = P->getAs<PackIndexingType>();
2480 if (PIT->hasSelectedType()) {
2482 S, TemplateParams, PIT->getSelectedType(), A, Info, Deduced, TDF,
2484 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2485 }
2487 }
2488 }
2489
2490 llvm_unreachable("Invalid Type Class!");
2491}
2492
2498 bool *HasDeducedAnyParam) {
2499 // If the template argument is a pack expansion, perform template argument
2500 // deduction against the pattern of that expansion. This only occurs during
2501 // partial ordering.
2502 if (A.isPackExpansion())
2504
2505 switch (P.getKind()) {
2507 llvm_unreachable("Null template argument in parameter list");
2508
2512 S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0,
2513 PartialOrdering ? PartialOrderingKind::NonCall
2514 : PartialOrderingKind::None,
2515 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2516 Info.FirstArg = P;
2517 Info.SecondArg = A;
2519
2521 // PartialOrdering does not matter here, since template specializations are
2522 // not being deduced.
2525 S, TemplateParams, P.getAsTemplate(), A.getAsTemplate(), Info,
2526 /*DefaultArguments=*/{}, /*PartialOrdering=*/false, Deduced,
2527 HasDeducedAnyParam);
2528 Info.FirstArg = P;
2529 Info.SecondArg = A;
2531
2533 llvm_unreachable("caller should handle pack expansions");
2534
2537 isSameDeclaration(P.getAsDecl(), A.getAsDecl()))
2539
2540 Info.FirstArg = P;
2541 Info.SecondArg = A;
2543
2545 // 'nullptr' has only one possible value, so it always matches.
2548 Info.FirstArg = P;
2549 Info.SecondArg = A;
2551
2554 if (hasSameExtendedValue(P.getAsIntegral(), A.getAsIntegral()))
2556 }
2557 Info.FirstArg = P;
2558 Info.SecondArg = A;
2560
2562 // FIXME: structural equality will also compare types,
2563 // but they should match iff they have the same value.
2567
2568 Info.FirstArg = P;
2569 Info.SecondArg = A;
2571
2573 if (const NonTypeTemplateParmDecl *NTTP =
2574 getDeducedParameterFromExpr(Info, P.getAsExpr())) {
2575 switch (A.getKind()) {
2577 const Expr *E = A.getAsExpr();
2578 // When checking NTTP, if either the parameter or the argument is
2579 // dependent, as there would be otherwise nothing to deduce, we force
2580 // the argument to the parameter type using this dependent implicit
2581 // cast, in order to maintain invariants. Now we can deduce the
2582 // resulting type from the original type, and deduce the original type
2583 // against the parameter we are checking.
2584 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
2585 ICE && ICE->getCastKind() == clang::CK_Dependent) {
2586 E = ICE->getSubExpr();
2588 S, TemplateParams, ICE->getType(), E->getType(), Info,
2589 Deduced, TDF_SkipNonDependent,
2590 PartialOrdering ? PartialOrderingKind::NonCall
2591 : PartialOrderingKind::None,
2592 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2594 return Result;
2595 }
2597 S, TemplateParams, NTTP, DeducedTemplateArgument(A), E->getType(),
2598 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
2599 }
2603 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2605 HasDeducedAnyParam);
2606
2609 S, TemplateParams, NTTP, A.getNullPtrType(), Info, PartialOrdering,
2610 Deduced, HasDeducedAnyParam);
2611
2614 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
2615 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
2616
2622 Info.FirstArg = P;
2623 Info.SecondArg = A;
2625 }
2626 llvm_unreachable("Unknown template argument kind");
2627 }
2628
2629 // Can't deduce anything, but that's okay.
2632 llvm_unreachable("Argument packs should be expanded by the caller!");
2633 }
2634
2635 llvm_unreachable("Invalid TemplateArgument Kind!");
2636}
2637
2638/// Determine whether there is a template argument to be used for
2639/// deduction.
2640///
2641/// This routine "expands" argument packs in-place, overriding its input
2642/// parameters so that \c Args[ArgIdx] will be the available template argument.
2643///
2644/// \returns true if there is another template argument (which will be at
2645/// \c Args[ArgIdx]), false otherwise.
2647 unsigned &ArgIdx) {
2648 if (ArgIdx == Args.size())
2649 return false;
2650
2651 const TemplateArgument &Arg = Args[ArgIdx];
2652 if (Arg.getKind() != TemplateArgument::Pack)
2653 return true;
2654
2655 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2656 Args = Arg.pack_elements();
2657 ArgIdx = 0;
2658 return ArgIdx < Args.size();
2659}
2660
2661/// Determine whether the given set of template arguments has a pack
2662/// expansion that is not the last template argument.
2664 bool FoundPackExpansion = false;
2665 for (const auto &A : Args) {
2666 if (FoundPackExpansion)
2667 return true;
2668
2669 if (A.getKind() == TemplateArgument::Pack)
2670 return hasPackExpansionBeforeEnd(A.pack_elements());
2671
2672 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2673 // templates, it should not be treated as a pack expansion.
2674 if (A.isPackExpansion())
2675 FoundPackExpansion = true;
2676 }
2677
2678 return false;
2679}
2680
2687 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
2688 PackFold PackFold, bool *HasDeducedAnyParam) {
2689 bool FoldPackParameter = PackFold == PackFold::ParameterToArgument ||
2690 PackFold == PackFold::Both,
2691 FoldPackArgument = PackFold == PackFold::ArgumentToParameter ||
2692 PackFold == PackFold::Both;
2693
2694 // C++0x [temp.deduct.type]p9:
2695 // If the template argument list of P contains a pack expansion that is not
2696 // the last template argument, the entire template argument list is a
2697 // non-deduced context.
2698 if (FoldPackParameter && hasPackExpansionBeforeEnd(Ps))
2700
2701 // C++0x [temp.deduct.type]p9:
2702 // If P has a form that contains <T> or <i>, then each argument Pi of the
2703 // respective template argument list P is compared with the corresponding
2704 // argument Ai of the corresponding template argument list of A.
2705 for (unsigned ArgIdx = 0, ParamIdx = 0; /**/; /**/) {
2707 return !FoldPackParameter && hasTemplateArgumentForDeduction(As, ArgIdx)
2710
2711 if (!Ps[ParamIdx].isPackExpansion()) {
2712 // The simple case: deduce template arguments by matching Pi and Ai.
2713
2714 // Check whether we have enough arguments.
2715 if (!hasTemplateArgumentForDeduction(As, ArgIdx))
2716 return !FoldPackArgument && NumberOfArgumentsMustMatch
2719
2720 if (As[ArgIdx].isPackExpansion()) {
2721 // C++1z [temp.deduct.type]p9:
2722 // During partial ordering, if Ai was originally a pack expansion
2723 // [and] Pi is not a pack expansion, template argument deduction
2724 // fails.
2725 if (!FoldPackArgument)
2727
2728 TemplateArgument Pattern = As[ArgIdx].getPackExpansionPattern();
2729 for (;;) {
2730 // Deduce template parameters from the pattern.
2732 S, TemplateParams, Ps[ParamIdx], Pattern, Info,
2733 PartialOrdering, Deduced, HasDeducedAnyParam);
2735 return Result;
2736
2737 ++ParamIdx;
2740 if (Ps[ParamIdx].isPackExpansion())
2741 break;
2742 }
2743 } else {
2744 // Perform deduction for this Pi/Ai pair.
2746 S, TemplateParams, Ps[ParamIdx], As[ArgIdx], Info,
2747 PartialOrdering, Deduced, HasDeducedAnyParam);
2749 return Result;
2750
2751 ++ArgIdx;
2752 ++ParamIdx;
2753 continue;
2754 }
2755 }
2756
2757 // The parameter is a pack expansion.
2758
2759 // C++0x [temp.deduct.type]p9:
2760 // If Pi is a pack expansion, then the pattern of Pi is compared with
2761 // each remaining argument in the template argument list of A. Each
2762 // comparison deduces template arguments for subsequent positions in the
2763 // template parameter packs expanded by Pi.
2764 TemplateArgument Pattern = Ps[ParamIdx].getPackExpansionPattern();
2765
2766 // Prepare to deduce the packs within the pattern.
2767 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2768
2769 // Keep track of the deduced template arguments for each parameter pack
2770 // expanded by this pack expansion (the outer index) and for each
2771 // template argument (the inner SmallVectors).
2772 for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
2773 PackScope.hasNextElement();
2774 ++ArgIdx) {
2775 if (!As[ArgIdx].isPackExpansion()) {
2776 if (!FoldPackParameter)
2778 if (FoldPackArgument)
2780 }
2781 // Deduce template arguments from the pattern.
2783 S, TemplateParams, Pattern, As[ArgIdx], Info, PartialOrdering,
2784 Deduced, HasDeducedAnyParam);
2786 return Result;
2787
2788 PackScope.nextPackElement();
2789 }
2790
2791 // Build argument packs for each of the parameter packs expanded by this
2792 // pack expansion.
2793 return PackScope.finish();
2794 }
2795}
2796
2801 bool NumberOfArgumentsMustMatch) {
2802 return ::DeduceTemplateArguments(
2803 *this, TemplateParams, Ps, As, Info, Deduced, NumberOfArgumentsMustMatch,
2804 /*PartialOrdering=*/false, PackFold::ParameterToArgument,
2805 /*HasDeducedAnyParam=*/nullptr);
2806}
2807
2808/// Determine whether two template arguments are the same.
2809static bool isSameTemplateArg(ASTContext &Context,
2811 const TemplateArgument &Y,
2812 bool PartialOrdering,
2813 bool PackExpansionMatchesPack = false) {
2814 // If we're checking deduced arguments (X) against original arguments (Y),
2815 // we will have flattened packs to non-expansions in X.
2816 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2817 X = X.getPackExpansionPattern();
2818
2819 if (X.getKind() != Y.getKind())
2820 return false;
2821
2822 switch (X.getKind()) {
2824 llvm_unreachable("Comparing NULL template argument");
2825
2827 return Context.getCanonicalType(X.getAsType()) ==
2828 Context.getCanonicalType(Y.getAsType());
2829
2831 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
2832
2834 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2835
2838 return Context.getCanonicalTemplateName(
2839 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2842
2844 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2845
2847 return X.structurallyEquals(Y);
2848
2850 llvm::FoldingSetNodeID XID, YID;
2851 X.getAsExpr()->Profile(XID, Context, true);
2852 Y.getAsExpr()->Profile(YID, Context, true);
2853 return XID == YID;
2854 }
2855
2857 unsigned PackIterationSize = X.pack_size();
2858 if (X.pack_size() != Y.pack_size()) {
2859 if (!PartialOrdering)
2860 return false;
2861
2862 // C++0x [temp.deduct.type]p9:
2863 // During partial ordering, if Ai was originally a pack expansion:
2864 // - if P does not contain a template argument corresponding to Ai
2865 // then Ai is ignored;
2866 bool XHasMoreArg = X.pack_size() > Y.pack_size();
2867 if (!(XHasMoreArg && X.pack_elements().back().isPackExpansion()) &&
2868 !(!XHasMoreArg && Y.pack_elements().back().isPackExpansion()))
2869 return false;
2870
2871 if (XHasMoreArg)
2872 PackIterationSize = Y.pack_size();
2873 }
2874
2875 ArrayRef<TemplateArgument> XP = X.pack_elements();
2877 for (unsigned i = 0; i < PackIterationSize; ++i)
2878 if (!isSameTemplateArg(Context, XP[i], YP[i], PartialOrdering,
2879 PackExpansionMatchesPack))
2880 return false;
2881 return true;
2882 }
2883 }
2884
2885 llvm_unreachable("Invalid TemplateArgument Kind!");
2886}
2887
2890 QualType NTTPType, SourceLocation Loc,
2892 switch (Arg.getKind()) {
2894 llvm_unreachable("Can't get a NULL template argument here");
2895
2897 return TemplateArgumentLoc(
2899
2901 if (NTTPType.isNull())
2902 NTTPType = Arg.getParamTypeForDecl();
2905 .getAs<Expr>();
2907 }
2908
2910 if (NTTPType.isNull())
2911 NTTPType = Arg.getNullPtrType();
2913 .getAs<Expr>();
2914 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2915 E);
2916 }
2917
2922 }
2923
2929 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2930 else if (QualifiedTemplateName *QTN =
2931 Template.getAsQualifiedTemplateName())
2932 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2933
2935 return TemplateArgumentLoc(Context, Arg,
2936 Builder.getWithLocInContext(Context), Loc);
2937
2938 return TemplateArgumentLoc(
2939 Context, Arg, Builder.getWithLocInContext(Context), Loc, Loc);
2940 }
2941
2943 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2944
2947 }
2948
2949 llvm_unreachable("Invalid TemplateArgument Kind!");
2950}
2951
2954 SourceLocation Location) {
2956 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2957}
2958
2959/// Convert the given deduced template argument and add it to the set of
2960/// fully-converted template arguments.
2961static bool
2963 DeducedTemplateArgument Arg, NamedDecl *Template,
2964 TemplateDeductionInfo &Info, bool IsDeduced,
2966 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2967 unsigned ArgumentPackIndex) {
2968 // Convert the deduced template argument into a template
2969 // argument that we can check, almost as if the user had written
2970 // the template argument explicitly.
2972 Arg, QualType(), Info.getLocation(), Param);
2973
2974 SaveAndRestore _1(CTAI.MatchingTTP, false);
2976 // Check the template argument, converting it as necessary.
2977 auto Res = S.CheckTemplateArgument(
2978 Param, ArgLoc, Template, Template->getLocation(),
2979 Template->getSourceRange().getEnd(), ArgumentPackIndex, CTAI,
2980 IsDeduced
2986 return Res;
2987 };
2988
2989 if (Arg.getKind() == TemplateArgument::Pack) {
2990 // This is a template argument pack, so check each of its arguments against
2991 // the template parameter.
2992 SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
2993 CanonicalPackedArgsBuilder;
2994 for (const auto &P : Arg.pack_elements()) {
2995 // When converting the deduced template argument, append it to the
2996 // general output list. We need to do this so that the template argument
2997 // checking logic has all of the prior template arguments available.
2998 DeducedTemplateArgument InnerArg(P);
3000 assert(InnerArg.getKind() != TemplateArgument::Pack &&
3001 "deduced nested pack");
3002 if (P.isNull()) {
3003 // We deduced arguments for some elements of this pack, but not for
3004 // all of them. This happens if we get a conditionally-non-deduced
3005 // context in a pack expansion (such as an overload set in one of the
3006 // arguments).
3007 S.Diag(Param->getLocation(),
3008 diag::err_template_arg_deduced_incomplete_pack)
3009 << Arg << Param;
3010 return true;
3011 }
3012 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
3013 return true;
3014
3015 // Move the converted template argument into our argument pack.
3016 SugaredPackedArgsBuilder.push_back(CTAI.SugaredConverted.pop_back_val());
3017 CanonicalPackedArgsBuilder.push_back(
3018 CTAI.CanonicalConverted.pop_back_val());
3019 }
3020
3021 // If the pack is empty, we still need to substitute into the parameter
3022 // itself, in case that substitution fails.
3023 if (SugaredPackedArgsBuilder.empty()) {
3026 /*Final=*/true);
3027
3028 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3029 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
3030 NTTP, CTAI.SugaredConverted,
3031 Template->getSourceRange());
3032 if (Inst.isInvalid() ||
3033 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
3034 NTTP->getDeclName()).isNull())
3035 return true;
3036 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3037 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
3038 TTP, CTAI.SugaredConverted,
3039 Template->getSourceRange());
3040 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
3041 return true;
3042 }
3043 // For type parameters, no substitution is ever required.
3044 }
3045
3046 // Create the resulting argument pack.
3047 CTAI.SugaredConverted.push_back(
3048 TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
3050 S.Context, CanonicalPackedArgsBuilder));
3051 return false;
3052 }
3053
3054 return ConvertArg(Arg, 0);
3055}
3056
3057// FIXME: This should not be a template, but
3058// ClassTemplatePartialSpecializationDecl sadly does not derive from
3059// TemplateDecl.
3060/// \param IsIncomplete When used, we only consider template parameters that
3061/// were deduced, disregarding any default arguments. After the function
3062/// finishes, the object pointed at will contain a value indicating if the
3063/// conversion was actually incomplete.
3064template <typename TemplateDeclT>
3066 Sema &S, TemplateDeclT *Template, bool IsDeduced,
3069 LocalInstantiationScope *CurrentInstantiationScope,
3070 unsigned NumAlreadyConverted, bool *IsIncomplete) {
3071 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3072
3073 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3074 NamedDecl *Param = TemplateParams->getParam(I);
3075
3076 // C++0x [temp.arg.explicit]p3:
3077 // A trailing template parameter pack (14.5.3) not otherwise deduced will
3078 // be deduced to an empty sequence of template arguments.
3079 // FIXME: Where did the word "trailing" come from?
3080 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
3081 if (auto Result =
3082 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish();
3084 return Result;
3085 }
3086
3087 if (!Deduced[I].isNull()) {
3088 if (I < NumAlreadyConverted) {
3089 // We may have had explicitly-specified template arguments for a
3090 // template parameter pack (that may or may not have been extended
3091 // via additional deduced arguments).
3092 if (Param->isParameterPack() && CurrentInstantiationScope &&
3093 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
3094 // Forget the partially-substituted pack; its substitution is now
3095 // complete.
3096 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
3097 // We still need to check the argument in case it was extended by
3098 // deduction.
3099 } else {
3100 // We have already fully type-checked and converted this
3101 // argument, because it was explicitly-specified. Just record the
3102 // presence of this argument.
3103 CTAI.SugaredConverted.push_back(Deduced[I]);
3104 CTAI.CanonicalConverted.push_back(
3106 continue;
3107 }
3108 }
3109
3110 // We may have deduced this argument, so it still needs to be
3111 // checked and converted.
3112 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
3113 IsDeduced, CTAI)) {
3114 Info.Param = makeTemplateParameter(Param);
3115 // FIXME: These template arguments are temporary. Free them!
3116 Info.reset(
3119 CTAI.CanonicalConverted));
3121 }
3122
3123 continue;
3124 }
3125
3126 // [C++26][temp.deduct.partial]p12 - When partial ordering, it's ok for
3127 // template parameters to remain not deduced. As a provisional fix for a
3128 // core issue that does not exist yet, which may be related to CWG2160, only
3129 // consider template parameters that were deduced, disregarding any default
3130 // arguments.
3131 if (IsIncomplete) {
3132 *IsIncomplete = true;
3133 CTAI.SugaredConverted.push_back({});
3134 CTAI.CanonicalConverted.push_back({});
3135 continue;
3136 }
3137
3138 // Substitute into the default template argument, if available.
3139 bool HasDefaultArg = false;
3140 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
3141 if (!TD) {
3142 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
3143 isa<VarTemplatePartialSpecializationDecl>(Template));
3145 }
3146
3147 TemplateArgumentLoc DefArg;
3148 {
3149 Qualifiers ThisTypeQuals;
3150 CXXRecordDecl *ThisContext = nullptr;
3151 if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
3152 if (Rec->isLambda())
3153 if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
3154 ThisContext = Method->getParent();
3155 ThisTypeQuals = Method->getMethodQualifiers();
3156 }
3157
3158 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
3159 S.getLangOpts().CPlusPlus17);
3160
3162 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param,
3163 CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
3164 }
3165
3166 // If there was no default argument, deduction is incomplete.
3167 if (DefArg.getArgument().isNull()) {
3169 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
3170 Info.reset(
3173
3176 }
3177
3178 SaveAndRestore _1(CTAI.PartialOrdering, false);
3179 SaveAndRestore _2(CTAI.MatchingTTP, false);
3181 // Check whether we can actually use the default argument.
3183 Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
3184 /*ArgumentPackIndex=*/0, CTAI, Sema::CTAK_Specified)) {
3186 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
3187 // FIXME: These template arguments are temporary. Free them!
3188 Info.reset(
3192 }
3193
3194 // If we get here, we successfully used the default template argument.
3195 }
3196
3198}
3199
3201 if (auto *DC = dyn_cast<DeclContext>(D))
3202 return DC;
3203 return D->getDeclContext();
3204}
3205
3206template<typename T> struct IsPartialSpecialization {
3207 static constexpr bool value = false;
3208};
3209template<>
3211 static constexpr bool value = true;
3212};
3213template<>
3215 static constexpr bool value = true;
3216};
3217template <typename TemplateDeclT>
3218static bool DeducedArgsNeedReplacement(TemplateDeclT *Template) {
3219 return false;
3220}
3221template <>
3224 return !Spec->isClassScopeExplicitSpecialization();
3225}
3226template <>
3229 return !Spec->isClassScopeExplicitSpecialization();
3230}
3231
3232template <typename TemplateDeclT>
3234CheckDeducedArgumentConstraints(Sema &S, TemplateDeclT *Template,
3235 ArrayRef<TemplateArgument> SugaredDeducedArgs,
3236 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
3237 TemplateDeductionInfo &Info) {
3238 llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
3239 Template->getAssociatedConstraints(AssociatedConstraints);
3240
3241 std::optional<ArrayRef<TemplateArgument>> Innermost;
3242 // If we don't need to replace the deduced template arguments,
3243 // we can add them immediately as the inner-most argument list.
3244 if (!DeducedArgsNeedReplacement(Template))
3245 Innermost = CanonicalDeducedArgs;
3246
3248 Template, Template->getDeclContext(), /*Final=*/false, Innermost,
3249 /*RelativeToPrimary=*/true, /*Pattern=*/
3250 nullptr, /*ForConstraintInstantiation=*/true);
3251
3252 // getTemplateInstantiationArgs picks up the non-deduced version of the
3253 // template args when this is a variable template partial specialization and
3254 // not class-scope explicit specialization, so replace with Deduced Args
3255 // instead of adding to inner-most.
3256 if (!Innermost)
3257 MLTAL.replaceInnermostTemplateArguments(Template, CanonicalDeducedArgs);
3258
3259 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
3260 Info.getLocation(),
3263 Info.reset(
3264 TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
3265 TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
3267 }
3269}
3270
3271/// Complete template argument deduction for a partial specialization.
3272template <typename T>
3273static std::enable_if_t<IsPartialSpecialization<T>::value,
3276 Sema &S, T *Partial, bool IsPartialOrdering,
3277 ArrayRef<TemplateArgument> TemplateArgs,
3279 TemplateDeductionInfo &Info) {
3280 // Unevaluated SFINAE context.
3283 Sema::SFINAETrap Trap(S);
3284
3285 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
3286
3287 // C++ [temp.deduct.type]p2:
3288 // [...] or if any template argument remains neither deduced nor
3289 // explicitly specified, template argument deduction fails.
3290 Sema::CheckTemplateArgumentInfo CTAI(IsPartialOrdering);
3292 S, Partial, IsPartialOrdering, Deduced, Info, CTAI,
3293 /*CurrentInstantiationScope=*/nullptr, /*NumAlreadyConverted=*/0,
3294 /*IsIncomplete=*/nullptr);
3296 return Result;
3297
3298 // Form the template argument list from the deduced template arguments.
3299 TemplateArgumentList *SugaredDeducedArgumentList =
3301 TemplateArgumentList *CanonicalDeducedArgumentList =
3303
3304 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3305
3306 // Substitute the deduced template arguments into the template
3307 // arguments of the class template partial specialization, and
3308 // verify that the instantiated template arguments are both valid
3309 // and are equivalent to the template arguments originally provided
3310 // to the class template.
3311 LocalInstantiationScope InstScope(S);
3312 auto *Template = Partial->getSpecializedTemplate();
3313 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
3314 Partial->getTemplateArgsAsWritten();
3315
3316 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
3317 PartialTemplArgInfo->RAngleLoc);
3318
3320 PartialTemplArgInfo->arguments(),
3322 /*Final=*/true),
3323 InstArgs)) {
3324 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
3325 if (ParamIdx >= Partial->getTemplateParameters()->size())
3326 ParamIdx = Partial->getTemplateParameters()->size() - 1;
3327
3328 Decl *Param = const_cast<NamedDecl *>(
3329 Partial->getTemplateParameters()->getParam(ParamIdx));
3330 Info.Param = makeTemplateParameter(Param);
3331 Info.FirstArg = (*PartialTemplArgInfo)[ArgIdx].getArgument();
3333 }
3334
3337 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
3338 /*DefaultArgs=*/{}, false, InstCTAI,
3339 /*UpdateArgsWithConversions=*/true,
3346
3347 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3348 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3349 TemplateArgument InstArg = InstCTAI.SugaredConverted.data()[I];
3350 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
3351 IsPartialOrdering)) {
3352 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3353 Info.FirstArg = TemplateArgs[I];
3354 Info.SecondArg = InstArg;
3356 }
3357 }
3358
3359 if (Trap.hasErrorOccurred())
3361
3362 if (!IsPartialOrdering) {
3364 S, Partial, CTAI.SugaredConverted, CTAI.CanonicalConverted, Info);
3366 return Result;
3367 }
3368
3370}
3371
3372/// Complete template argument deduction for a class or variable template,
3373/// when partial ordering against a partial specialization.
3374// FIXME: Factor out duplication with partial specialization version above.
3376 Sema &S, TemplateDecl *Template, bool PartialOrdering,
3377 ArrayRef<TemplateArgument> TemplateArgs,
3379 TemplateDeductionInfo &Info) {
3380 // Unevaluated SFINAE context.
3383
3384 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
3385
3386 // C++ [temp.deduct.type]p2:
3387 // [...] or if any template argument remains neither deduced nor
3388 // explicitly specified, template argument deduction fails.
3391 S, Template, /*IsDeduced=*/PartialOrdering, Deduced, Info, CTAI,
3392 /*CurrentInstantiationScope=*/nullptr,
3393 /*NumAlreadyConverted=*/0U, /*IsIncomplete=*/nullptr);
3395 return Result;
3396
3397 // Check that we produced the correct argument list.
3398 SmallVector<ArrayRef<TemplateArgument>, 4> PsStack{TemplateArgs},
3399 AsStack{CTAI.CanonicalConverted};
3400 for (;;) {
3401 auto take = [](SmallVectorImpl<ArrayRef<TemplateArgument>> &Stack)
3403 while (!Stack.empty()) {
3404 auto &Xs = Stack.back();
3405 if (Xs.empty()) {
3406 Stack.pop_back();
3407 continue;
3408 }
3409 auto &X = Xs.front();
3410 if (X.getKind() == TemplateArgument::Pack) {
3411 Stack.emplace_back(X.getPackAsArray());
3412 Xs = Xs.drop_front();
3413 continue;
3414 }
3415 assert(!X.isNull());
3416 return {Xs, X};
3417 }
3418 static constexpr ArrayRef<TemplateArgument> None;
3419 return {const_cast<ArrayRef<TemplateArgument> &>(None),
3421 };
3422 auto [Ps, P] = take(PsStack);
3423 auto [As, A] = take(AsStack);
3424 if (P.isNull() && A.isNull())
3425 break;
3426 TemplateArgument PP = P.isPackExpansion() ? P.getPackExpansionPattern() : P,
3427 PA = A.isPackExpansion() ? A.getPackExpansionPattern() : A;
3428 if (!isSameTemplateArg(S.Context, PP, PA, /*PartialOrdering=*/false)) {
3429 if (!P.isPackExpansion() && !A.isPackExpansion()) {
3430 Info.Param =
3432 (PsStack.empty() ? TemplateArgs.end()
3433 : PsStack.front().begin()) -
3434 TemplateArgs.begin()));
3435 Info.FirstArg = P;
3436 Info.SecondArg = A;
3438 }
3439 if (P.isPackExpansion()) {
3440 Ps = Ps.drop_front();
3441 continue;
3442 }
3443 if (A.isPackExpansion()) {
3444 As = As.drop_front();
3445 continue;
3446 }
3447 }
3448 Ps = Ps.drop_front(P.isPackExpansion() ? 0 : 1);
3449 As = As.drop_front(A.isPackExpansion() && !P.isPackExpansion() ? 0 : 1);
3450 }
3451 assert(PsStack.empty());
3452 assert(AsStack.empty());
3453
3454 if (!PartialOrdering) {
3456 S, Template, CTAI.SugaredConverted, CTAI.CanonicalConverted, Info);
3458 return Result;
3459 }
3460
3462}
3463
3464/// Complete template argument deduction for DeduceTemplateArgumentsFromType.
3465/// FIXME: this is mostly duplicated with the above two versions. Deduplicate
3466/// the three implementations.
3468 Sema &S, TemplateDecl *TD,
3470 TemplateDeductionInfo &Info) {
3471 // Unevaluated SFINAE context.
3474
3476
3477 // C++ [temp.deduct.type]p2:
3478 // [...] or if any template argument remains neither deduced nor
3479 // explicitly specified, template argument deduction fails.
3482 S, TD, /*IsDeduced=*/false, Deduced, Info, CTAI,
3483 /*CurrentInstantiationScope=*/nullptr, /*NumAlreadyConverted=*/0,
3484 /*IsIncomplete=*/nullptr);
3486 return Result;
3487
3488 return ::CheckDeducedArgumentConstraints(S, TD, CTAI.SugaredConverted,
3489 CTAI.CanonicalConverted, Info);
3490}
3491
3492/// Perform template argument deduction to determine whether the given template
3493/// arguments match the given class or variable template partial specialization
3494/// per C++ [temp.class.spec.match].
3495template <typename T>
3496static std::enable_if_t<IsPartialSpecialization<T>::value,
3499 ArrayRef<TemplateArgument> TemplateArgs,
3500 TemplateDeductionInfo &Info) {
3501 if (Partial->isInvalidDecl())
3503
3504 // C++ [temp.class.spec.match]p2:
3505 // A partial specialization matches a given actual template
3506 // argument list if the template arguments of the partial
3507 // specialization can be deduced from the actual template argument
3508 // list (14.8.2).
3509
3510 // Unevaluated SFINAE context.
3513 Sema::SFINAETrap Trap(S);
3514
3515 // This deduction has no relation to any outer instantiation we might be
3516 // performing.
3517 LocalInstantiationScope InstantiationScope(S);
3518
3520 Deduced.resize(Partial->getTemplateParameters()->size());
3522 S, Partial->getTemplateParameters(),
3523 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3524 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/false,
3525 PackFold::ParameterToArgument,
3526 /*HasDeducedAnyParam=*/nullptr);
3528 return Result;
3529
3530 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3531 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs,
3532 Info);
3533 if (Inst.isInvalid())
3535
3538 Result = ::FinishTemplateArgumentDeduction(S, Partial,
3539 /*IsPartialOrdering=*/false,
3540 TemplateArgs, Deduced, Info);
3541 });
3542
3544 return Result;
3545
3546 if (Trap.hasErrorOccurred())
3548
3550}
3551
3554 ArrayRef<TemplateArgument> TemplateArgs,
3555 TemplateDeductionInfo &Info) {
3556 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3557}
3560 ArrayRef<TemplateArgument> TemplateArgs,
3561 TemplateDeductionInfo &Info) {
3562 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3563}
3564
3568 if (TD->isInvalidDecl())
3570
3571 QualType PType;
3572 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
3573 // Use the InjectedClassNameType.
3574 PType = Context.getTypeDeclType(CTD->getTemplatedDecl());
3575 } else if (const auto *AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(TD)) {
3576 PType = AliasTemplate->getTemplatedDecl()->getUnderlyingType();
3577 } else {
3578 assert(false && "Expected a class or alias template");
3579 }
3580
3581 // Unevaluated SFINAE context.
3584 SFINAETrap Trap(*this);
3585
3586 // This deduction has no relation to any outer instantiation we might be
3587 // performing.
3588 LocalInstantiationScope InstantiationScope(*this);
3589
3591 TD->getTemplateParameters()->size());
3594 if (auto DeducedResult = DeduceTemplateArguments(
3595 TD->getTemplateParameters(), PArgs, AArgs, Info, Deduced, false);
3596 DeducedResult != TemplateDeductionResult::Success) {
3597 return DeducedResult;
3598 }
3599
3600 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3601 InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs, Info);
3602 if (Inst.isInvalid())
3604
3607 Result = ::FinishTemplateArgumentDeduction(*this, TD, Deduced, Info);
3608 });
3609
3611 return Result;
3612
3613 if (Trap.hasErrorOccurred())
3615
3617}
3618
3619/// Determine whether the given type T is a simple-template-id type.
3621 if (const TemplateSpecializationType *Spec
3623 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
3624
3625 // C++17 [temp.local]p2:
3626 // the injected-class-name [...] is equivalent to the template-name followed
3627 // by the template-arguments of the class template specialization or partial
3628 // specialization enclosed in <>
3629 // ... which means it's equivalent to a simple-template-id.
3630 //
3631 // This only arises during class template argument deduction for a copy
3632 // deduction candidate, where it permits slicing.
3634 return true;
3635
3636 return false;
3637}
3638
3640 FunctionTemplateDecl *FunctionTemplate,
3641 TemplateArgumentListInfo &ExplicitTemplateArgs,
3644 TemplateDeductionInfo &Info) {
3645 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3646 TemplateParameterList *TemplateParams
3647 = FunctionTemplate->getTemplateParameters();
3648
3649 if (ExplicitTemplateArgs.size() == 0) {
3650 // No arguments to substitute; just copy over the parameter types and
3651 // fill in the function type.
3652 for (auto *P : Function->parameters())
3653 ParamTypes.push_back(P->getType());
3654
3655 if (FunctionType)
3656 *FunctionType = Function->getType();
3658 }
3659
3660 // Unevaluated SFINAE context.
3663 SFINAETrap Trap(*this);
3664
3665 // C++ [temp.arg.explicit]p3:
3666 // Template arguments that are present shall be specified in the
3667 // declaration order of their corresponding template-parameters. The
3668 // template argument list shall not specify more template-arguments than
3669 // there are corresponding template-parameters.
3670
3671 // Enter a new template instantiation context where we check the
3672 // explicitly-specified template arguments against this function template,
3673 // and then substitute them into the function parameter types.
3676 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3678 if (Inst.isInvalid())
3680
3683 ExplicitTemplateArgs, /*DefaultArgs=*/{},
3684 /*PartialTemplateArgs=*/true, CTAI,
3685 /*UpdateArgsWithConversions=*/false) ||
3686 Trap.hasErrorOccurred()) {
3687 unsigned Index = CTAI.SugaredConverted.size();
3688 if (Index >= TemplateParams->size())
3690 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3692 }
3693
3694 // Form the template argument list from the explicitly-specified
3695 // template arguments.
3696 TemplateArgumentList *SugaredExplicitArgumentList =
3698 TemplateArgumentList *CanonicalExplicitArgumentList =
3700 Info.setExplicitArgs(SugaredExplicitArgumentList,
3701 CanonicalExplicitArgumentList);
3702
3703 // Template argument deduction and the final substitution should be
3704 // done in the context of the templated declaration. Explicit
3705 // argument substitution, on the other hand, needs to happen in the
3706 // calling context.
3707 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3708
3709 // If we deduced template arguments for a template parameter pack,
3710 // note that the template argument pack is partially substituted and record
3711 // the explicit template arguments. They'll be used as part of deduction
3712 // for this template parameter pack.
3713 unsigned PartiallySubstitutedPackIndex = -1u;
3714 if (!CTAI.SugaredConverted.empty()) {
3715 const TemplateArgument &Arg = CTAI.SugaredConverted.back();
3716 if (Arg.getKind() == TemplateArgument::Pack) {
3717 auto *Param = TemplateParams->getParam(CTAI.SugaredConverted.size() - 1);
3718 // If this is a fully-saturated fixed-size pack, it should be
3719 // fully-substituted, not partially-substituted.
3720 std::optional<unsigned> Expansions = getExpandedPackSize(Param);
3721 if (!Expansions || Arg.pack_size() < *Expansions) {
3722 PartiallySubstitutedPackIndex = CTAI.SugaredConverted.size() - 1;
3724 Param, Arg.pack_begin(), Arg.pack_size());
3725 }
3726 }
3727 }
3728
3729 const FunctionProtoType *Proto
3730 = Function->getType()->getAs<FunctionProtoType>();
3731 assert(Proto && "Function template does not have a prototype?");
3732
3733 // Isolate our substituted parameters from our caller.
3734 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3735
3736 ExtParameterInfoBuilder ExtParamInfos;
3737
3739 SugaredExplicitArgumentList->asArray(),
3740 /*Final=*/true);
3741
3742 // Instantiate the types of each of the function parameters given the
3743 // explicitly-specified template arguments. If the function has a trailing
3744 // return type, substitute it after the arguments to ensure we substitute
3745 // in lexical order.
3746 if (Proto->hasTrailingReturn()) {
3747 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3748 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3749 /*params=*/nullptr, ExtParamInfos))
3751 }
3752
3753 // Instantiate the return type.
3754 QualType ResultType;
3755 {
3756 // C++11 [expr.prim.general]p3:
3757 // If a declaration declares a member function or member function
3758 // template of a class X, the expression this is a prvalue of type
3759 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3760 // and the end of the function-definition, member-declarator, or
3761 // declarator.
3762 Qualifiers ThisTypeQuals;
3763 CXXRecordDecl *ThisContext = nullptr;
3764 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3765 ThisContext = Method->getParent();
3766 ThisTypeQuals = Method->getMethodQualifiers();
3767 }
3768
3769 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3771
3772 ResultType =
3773 SubstType(Proto->getReturnType(), MLTAL,
3774 Function->getTypeSpecStartLoc(), Function->getDeclName());
3775 if (ResultType.isNull() || Trap.hasErrorOccurred())
3777 // CUDA: Kernel function must have 'void' return type.
3778 if (getLangOpts().CUDA)
3779 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3780 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3781 << Function->getType() << Function->getSourceRange();
3783 }
3784 }
3785
3786 // Instantiate the types of each of the function parameters given the
3787 // explicitly-specified template arguments if we didn't do so earlier.
3788 if (!Proto->hasTrailingReturn() &&
3789 SubstParmTypes(Function->getLocation(), Function->parameters(),
3790 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3791 /*params*/ nullptr, ExtParamInfos))
3793
3794 if (FunctionType) {
3795 auto EPI = Proto->getExtProtoInfo();
3796 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3797 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3798 Function->getLocation(),
3799 Function->getDeclName(),
3800 EPI);
3801 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3803 }
3804
3805 // C++ [temp.arg.explicit]p2:
3806 // Trailing template arguments that can be deduced (14.8.2) may be
3807 // omitted from the list of explicit template-arguments. If all of the
3808 // template arguments can be deduced, they may all be omitted; in this
3809 // case, the empty template argument list <> itself may also be omitted.
3810 //
3811 // Take all of the explicitly-specified arguments and put them into
3812 // the set of deduced template arguments. The partially-substituted
3813 // parameter pack, however, will be set to NULL since the deduction
3814 // mechanism handles the partially-substituted argument pack directly.
3815 Deduced.reserve(TemplateParams->size());
3816 for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3817 const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
3818 if (I == PartiallySubstitutedPackIndex)
3819 Deduced.push_back(DeducedTemplateArgument());
3820 else
3821 Deduced.push_back(Arg);
3822 }
3823
3825}
3826
3827/// Check whether the deduced argument type for a call to a function
3828/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3831 Sema::OriginalCallArg OriginalArg,
3832 QualType DeducedA) {
3833 ASTContext &Context = S.Context;
3834
3835 auto Failed = [&]() -> TemplateDeductionResult {
3836 Info.FirstArg = TemplateArgument(DeducedA);
3837 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3838 Info.CallArgIndex = OriginalArg.ArgIdx;
3839 return OriginalArg.DecomposedParam
3842 };
3843
3844 QualType A = OriginalArg.OriginalArgType;
3845 QualType OriginalParamType = OriginalArg.OriginalParamType;
3846
3847 // Check for type equality (top-level cv-qualifiers are ignored).
3848 if (Context.hasSameUnqualifiedType(A, DeducedA))
3850
3851 // Strip off references on the argument types; they aren't needed for
3852 // the following checks.
3853 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3854 DeducedA = DeducedARef->getPointeeType();
3855 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3856 A = ARef->getPointeeType();
3857
3858 // C++ [temp.deduct.call]p4:
3859 // [...] However, there are three cases that allow a difference:
3860 // - If the original P is a reference type, the deduced A (i.e., the
3861 // type referred to by the reference) can be more cv-qualified than
3862 // the transformed A.
3863 if (const ReferenceType *OriginalParamRef
3864 = OriginalParamType->getAs<ReferenceType>()) {
3865 // We don't want to keep the reference around any more.
3866 OriginalParamType = OriginalParamRef->getPointeeType();
3867
3868 // FIXME: Resolve core issue (no number yet): if the original P is a
3869 // reference type and the transformed A is function type "noexcept F",
3870 // the deduced A can be F.
3871 QualType Tmp;
3872 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
3874
3875 Qualifiers AQuals = A.getQualifiers();
3876 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3877
3878 // Under Objective-C++ ARC, the deduced type may have implicitly
3879 // been given strong or (when dealing with a const reference)
3880 // unsafe_unretained lifetime. If so, update the original
3881 // qualifiers to include this lifetime.
3882 if (S.getLangOpts().ObjCAutoRefCount &&
3883 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3885 (DeducedAQuals.hasConst() &&
3886 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3887 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3888 }
3889
3890 if (AQuals == DeducedAQuals) {
3891 // Qualifiers match; there's nothing to do.
3892 } else if (!DeducedAQuals.compatiblyIncludes(AQuals, S.getASTContext())) {
3893 return Failed();
3894 } else {
3895 // Qualifiers are compatible, so have the argument type adopt the
3896 // deduced argument type's qualifiers as if we had performed the
3897 // qualification conversion.
3898 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3899 }
3900 }
3901
3902 // - The transformed A can be another pointer or pointer to member
3903 // type that can be converted to the deduced A via a function pointer
3904 // conversion and/or a qualification conversion.
3905 //
3906 // Also allow conversions which merely strip __attribute__((noreturn)) from
3907 // function types (recursively).
3908 bool ObjCLifetimeConversion = false;
3909 QualType ResultTy;
3910 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3911 (S.IsQualificationConversion(A, DeducedA, false,
3912 ObjCLifetimeConversion) ||
3913 S.IsFunctionConversion(A, DeducedA, ResultTy)))
3915
3916 // - If P is a class and P has the form simple-template-id, then the
3917 // transformed A can be a derived class of the deduced A. [...]
3918 // [...] Likewise, if P is a pointer to a class of the form
3919 // simple-template-id, the transformed A can be a pointer to a
3920 // derived class pointed to by the deduced A.
3921 if (const PointerType *OriginalParamPtr
3922 = OriginalParamType->getAs<PointerType>()) {
3923 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3924 if (const PointerType *APtr = A->getAs<PointerType>()) {
3925 if (A->getPointeeType()->isRecordType()) {
3926 OriginalParamType = OriginalParamPtr->getPointeeType();
3927 DeducedA = DeducedAPtr->getPointeeType();
3928 A = APtr->getPointeeType();
3929 }
3930 }
3931 }
3932 }
3933
3934 if (Context.hasSameUnqualifiedType(A, DeducedA))
3936
3937 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3938 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3940
3941 return Failed();
3942}
3943
3944/// Find the pack index for a particular parameter index in an instantiation of
3945/// a function template with specific arguments.
3946///
3947/// \return The pack index for whichever pack produced this parameter, or -1
3948/// if this was not produced by a parameter. Intended to be used as the
3949/// ArgumentPackSubstitutionIndex for further substitutions.
3950// FIXME: We should track this in OriginalCallArgs so we don't need to
3951// reconstruct it here.
3952static unsigned getPackIndexForParam(Sema &S,
3953 FunctionTemplateDecl *FunctionTemplate,
3955 unsigned ParamIdx) {
3956 unsigned Idx = 0;
3957 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3958 if (PD->isParameterPack()) {
3959 unsigned NumExpansions =
3960 S.getNumArgumentsInExpansion(PD->getType(), Args).value_or(1);
3961 if (Idx + NumExpansions > ParamIdx)
3962 return ParamIdx - Idx;
3963 Idx += NumExpansions;
3964 } else {
3965 if (Idx == ParamIdx)
3966 return -1; // Not a pack expansion
3967 ++Idx;
3968 }
3969 }
3970
3971 llvm_unreachable("parameter index would not be produced from template");
3972}
3973
3974// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`,
3975// we'll try to instantiate and update its explicit specifier after constraint
3976// checking.
3979 const MultiLevelTemplateArgumentList &SubstArgs,
3980 TemplateDeductionInfo &Info, FunctionTemplateDecl *FunctionTemplate,
3981 ArrayRef<TemplateArgument> DeducedArgs) {
3982 auto GetExplicitSpecifier = [](FunctionDecl *D) {
3983 return isa<CXXConstructorDecl>(D)
3984 ? cast<CXXConstructorDecl>(D)->getExplicitSpecifier()
3985 : cast<CXXConversionDecl>(D)->getExplicitSpecifier();
3986 };
3987 auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) {
3988 isa<CXXConstructorDecl>(D)
3989 ? cast<CXXConstructorDecl>(D)->setExplicitSpecifier(ES)
3990 : cast<CXXConversionDecl>(D)->setExplicitSpecifier(ES);
3991 };
3992
3993 ExplicitSpecifier ES = GetExplicitSpecifier(Specialization);
3994 Expr *ExplicitExpr = ES.getExpr();
3995 if (!ExplicitExpr)
3997 if (!ExplicitExpr->isValueDependent())
3999
4001 S, Info.getLocation(), FunctionTemplate, DeducedArgs,
4003 if (Inst.isInvalid())
4005 Sema::SFINAETrap Trap(S);
4006 const ExplicitSpecifier InstantiatedES =
4007 S.instantiateExplicitSpecifier(SubstArgs, ES);
4008 if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) {
4009 Specialization->setInvalidDecl(true);
4011 }
4012 SetExplicitSpecifier(Specialization, InstantiatedES);
4014}
4015
4017 FunctionTemplateDecl *FunctionTemplate,
4019 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
4021 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
4022 bool PartialOverloading, bool PartialOrdering,
4023 llvm::function_ref<bool()> CheckNonDependent) {
4024 // Unevaluated SFINAE context.
4027 SFINAETrap Trap(*this);
4028
4029 // Enter a new template instantiation context while we instantiate the
4030 // actual function declaration.
4031 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
4033 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
4035 if (Inst.isInvalid())
4037
4038 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
4039
4040 // C++ [temp.deduct.type]p2:
4041 // [...] or if any template argument remains neither deduced nor
4042 // explicitly specified, template argument deduction fails.
4043 bool IsIncomplete = false;
4046 *this, FunctionTemplate, /*IsDeduced=*/true, Deduced, Info, CTAI,
4047 CurrentInstantiationScope, NumExplicitlySpecified,
4048 PartialOverloading ? &IsIncomplete : nullptr);
4050 return Result;
4051
4052 // C++ [temp.deduct.call]p10: [DR1391]
4053 // If deduction succeeds for all parameters that contain
4054 // template-parameters that participate in template argument deduction,
4055 // and all template arguments are explicitly specified, deduced, or
4056 // obtained from default template arguments, remaining parameters are then
4057 // compared with the corresponding arguments. For each remaining parameter
4058 // P with a type that was non-dependent before substitution of any
4059 // explicitly-specified template arguments, if the corresponding argument
4060 // A cannot be implicitly converted to P, deduction fails.
4061 if (CheckNonDependent())
4063
4064 // Form the template argument list from the deduced template arguments.
4065 TemplateArgumentList *SugaredDeducedArgumentList =
4067 TemplateArgumentList *CanonicalDeducedArgumentList =
4069 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
4070
4071 // Substitute the deduced template arguments into the function template
4072 // declaration to produce the function template specialization.
4073 DeclContext *Owner = FunctionTemplate->getDeclContext();
4074 if (FunctionTemplate->getFriendObjectKind())
4075 Owner = FunctionTemplate->getLexicalDeclContext();
4076 FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
4077
4079 FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
4080 /*Final=*/false);
4081 Specialization = cast_or_null<FunctionDecl>(
4082 SubstDecl(FD, Owner, SubstArgs));
4083 if (!Specialization || Specialization->isInvalidDecl())
4085
4086 assert(isSameDeclaration(Specialization->getPrimaryTemplate(),
4088
4089 // If the template argument list is owned by the function template
4090 // specialization, release it.
4091 if (Specialization->getTemplateSpecializationArgs() ==
4092 CanonicalDeducedArgumentList &&
4093 !Trap.hasErrorOccurred())
4094 Info.takeCanonical();
4095
4096 // There may have been an error that did not prevent us from constructing a
4097 // declaration. Mark the declaration invalid and return with a substitution
4098 // failure.
4099 if (Trap.hasErrorOccurred()) {
4100 Specialization->setInvalidDecl(true);
4102 }
4103
4104 // C++2a [temp.deduct]p5
4105 // [...] When all template arguments have been deduced [...] all uses of
4106 // template parameters [...] are replaced with the corresponding deduced
4107 // or default argument values.
4108 // [...] If the function template has associated constraints
4109 // ([temp.constr.decl]), those constraints are checked for satisfaction
4110 // ([temp.constr.constr]). If the constraints are not satisfied, type
4111 // deduction fails.
4112 if (!IsIncomplete) {
4117
4122 }
4123 }
4124
4125 // We skipped the instantiation of the explicit-specifier during the
4126 // substitution of `FD` before. So, we try to instantiate it back if
4127 // `Specialization` is either a constructor or a conversion function.
4128 if (isa<CXXConstructorDecl, CXXConversionDecl>(Specialization)) {
4131 Info, FunctionTemplate,
4132 DeducedArgs)) {
4134 }
4135 }
4136
4137 if (OriginalCallArgs) {
4138 // C++ [temp.deduct.call]p4:
4139 // In general, the deduction process attempts to find template argument
4140 // values that will make the deduced A identical to A (after the type A
4141 // is transformed as described above). [...]
4142 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
4143 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
4144 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
4145
4146 auto ParamIdx = OriginalArg.ArgIdx;
4147 unsigned ExplicitOffset =
4148 Specialization->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
4149 if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset)
4150 // FIXME: This presumably means a pack ended up smaller than we
4151 // expected while deducing. Should this not result in deduction
4152 // failure? Can it even happen?
4153 continue;
4154
4155 QualType DeducedA;
4156 if (!OriginalArg.DecomposedParam) {
4157 // P is one of the function parameters, just look up its substituted
4158 // type.
4159 DeducedA =
4160 Specialization->getParamDecl(ParamIdx + ExplicitOffset)->getType();
4161 } else {
4162 // P is a decomposed element of a parameter corresponding to a
4163 // braced-init-list argument. Substitute back into P to find the
4164 // deduced A.
4165 QualType &CacheEntry =
4166 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
4167 if (CacheEntry.isNull()) {
4169 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
4170 ParamIdx));
4171 CacheEntry =
4172 SubstType(OriginalArg.OriginalParamType, SubstArgs,
4173 Specialization->getTypeSpecStartLoc(),
4174 Specialization->getDeclName());
4175 }
4176 DeducedA = CacheEntry;
4177 }
4178
4179 if (auto TDK =
4180 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
4182 return TDK;
4183 }
4184 }
4185
4186 // If we suppressed any diagnostics while performing template argument
4187 // deduction, and if we haven't already instantiated this declaration,
4188 // keep track of these diagnostics. They'll be emitted if this specialization
4189 // is actually used.
4190 if (Info.diag_begin() != Info.diag_end()) {
4191 auto [Pos, Inserted] =
4192 SuppressedDiagnostics.try_emplace(Specialization->getCanonicalDecl());
4193 if (Inserted)
4194 Pos->second.append(Info.diag_begin(), Info.diag_end());
4195 }
4196
4198}
4199
4200/// Gets the type of a function for template-argument-deducton
4201/// purposes when it's considered as part of an overload set.
4203 FunctionDecl *Fn) {
4204 // We may need to deduce the return type of the function now.
4205 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
4206 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
4207 return {};
4208
4209 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
4210 if (Method->isImplicitObjectMemberFunction()) {
4211 // An instance method that's referenced in a form that doesn't
4212 // look like a member pointer is just invalid.
4214 return {};
4215
4216 return S.Context.getMemberPointerType(Fn->getType(),
4217 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
4218 }
4219
4220 if (!R.IsAddressOfOperand) return Fn->getType();
4221 return S.Context.getPointerType(Fn->getType());
4222}
4223
4224/// Apply the deduction rules for overload sets.
4225///
4226/// \return the null type if this argument should be treated as an
4227/// undeduced context
4228static QualType
4230 Expr *Arg, QualType ParamType,
4231 bool ParamWasReference,
4232 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4233
4235
4236 OverloadExpr *Ovl = R.Expression;
4237
4238 // C++0x [temp.deduct.call]p4
4239 unsigned TDF = 0;
4240 if (ParamWasReference)
4242 if (R.IsAddressOfOperand)
4243 TDF |= TDF_IgnoreQualifiers;
4244
4245 // C++0x [temp.deduct.call]p6:
4246 // When P is a function type, pointer to function type, or pointer
4247 // to member function type:
4248
4249 if (!ParamType->isFunctionType() &&
4250 !ParamType->isFunctionPointerType() &&
4251 !ParamType->isMemberFunctionPointerType()) {
4252 if (Ovl->hasExplicitTemplateArgs()) {
4253 // But we can still look for an explicit specialization.
4254 if (FunctionDecl *ExplicitSpec =
4256 Ovl, /*Complain=*/false,
4257 /*FoundDeclAccessPair=*/nullptr, FailedTSC))
4258 return GetTypeOfFunction(S, R, ExplicitSpec);
4259 }
4260
4261 DeclAccessPair DAP;
4262 if (FunctionDecl *Viable =
4264 return GetTypeOfFunction(S, R, Viable);
4265
4266 return {};
4267 }
4268
4269 // Gather the explicit template arguments, if any.
4270 TemplateArgumentListInfo ExplicitTemplateArgs;
4271 if (Ovl->hasExplicitTemplateArgs())
4272 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4273 QualType Match;
4274 for (UnresolvedSetIterator I = Ovl->decls_begin(),
4275 E = Ovl->decls_end(); I != E; ++I) {
4276 NamedDecl *D = (*I)->getUnderlyingDecl();
4277
4278 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
4279 // - If the argument is an overload set containing one or more
4280 // function templates, the parameter is treated as a
4281 // non-deduced context.
4282 if (!Ovl->hasExplicitTemplateArgs())
4283 return {};
4284
4285 // Otherwise, see if we can resolve a function type
4286 FunctionDecl *Specialization = nullptr;
4287 TemplateDeductionInfo Info(Ovl->getNameLoc());
4288 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
4291 continue;
4292
4293 D = Specialization;
4294 }
4295
4296 FunctionDecl *Fn = cast<FunctionDecl>(D);
4297 QualType ArgType = GetTypeOfFunction(S, R, Fn);
4298 if (ArgType.isNull()) continue;
4299
4300 // Function-to-pointer conversion.
4301 if (!ParamWasReference && ParamType->isPointerType() &&
4302 ArgType->isFunctionType())
4303 ArgType = S.Context.getPointerType(ArgType);
4304
4305 // - If the argument is an overload set (not containing function
4306 // templates), trial argument deduction is attempted using each
4307 // of the members of the set. If deduction succeeds for only one
4308 // of the overload set members, that member is used as the
4309 // argument value for the deduction. If deduction succeeds for
4310 // more than one member of the overload set the parameter is
4311 // treated as a non-deduced context.
4312
4313 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
4314 // Type deduction is done independently for each P/A pair, and
4315 // the deduced template argument values are then combined.
4316 // So we do not reject deductions which were made elsewhere.
4318 Deduced(TemplateParams->size());
4319 TemplateDeductionInfo Info(Ovl->getNameLoc());
4321 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4322 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4323 /*HasDeducedAnyParam=*/nullptr);
4325 continue;
4326 if (!Match.isNull())
4327 return {};
4328 Match = ArgType;
4329 }
4330
4331 return Match;
4332}
4333
4334/// Perform the adjustments to the parameter and argument types
4335/// described in C++ [temp.deduct.call].
4336///
4337/// \returns true if the caller should not attempt to perform any template
4338/// argument deduction based on this P/A pair because the argument is an
4339/// overloaded function set that could not be resolved.
4341 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4342 QualType &ParamType, QualType &ArgType,
4343 Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
4344 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4345 // C++0x [temp.deduct.call]p3:
4346 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
4347 // are ignored for type deduction.
4348 if (ParamType.hasQualifiers())
4349 ParamType = ParamType.getUnqualifiedType();
4350
4351 // [...] If P is a reference type, the type referred to by P is
4352 // used for type deduction.
4353 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
4354 if (ParamRefType)
4355 ParamType = ParamRefType->getPointeeType();
4356
4357 // Overload sets usually make this parameter an undeduced context,
4358 // but there are sometimes special circumstances. Typically
4359 // involving a template-id-expr.
4360 if (ArgType == S.Context.OverloadTy) {
4361 assert(Arg && "expected a non-null arg expression");
4362 ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType,
4363 ParamRefType != nullptr, FailedTSC);
4364 if (ArgType.isNull())
4365 return true;
4366 }
4367
4368 if (ParamRefType) {
4369 // If the argument has incomplete array type, try to complete its type.
4370 if (ArgType->isIncompleteArrayType()) {
4371 assert(Arg && "expected a non-null arg expression");
4372 ArgType = S.getCompletedType(Arg);
4373 }
4374
4375 // C++1z [temp.deduct.call]p3:
4376 // If P is a forwarding reference and the argument is an lvalue, the type
4377 // "lvalue reference to A" is used in place of A for type deduction.
4378 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
4379 ArgClassification.isLValue()) {
4380 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
4381 ArgType = S.Context.getAddrSpaceQualType(
4383 ArgType = S.Context.getLValueReferenceType(ArgType);
4384 }
4385 } else {
4386 // C++ [temp.deduct.call]p2:
4387 // If P is not a reference type:
4388 // - If A is an array type, the pointer type produced by the
4389 // array-to-pointer standard conversion (4.2) is used in place of
4390 // A for type deduction; otherwise,
4391 // - If A is a function type, the pointer type produced by the
4392 // function-to-pointer standard conversion (4.3) is used in place
4393 // of A for type deduction; otherwise,
4394 if (ArgType->canDecayToPointerType())
4395 ArgType = S.Context.getDecayedType(ArgType);
4396 else {
4397 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
4398 // type are ignored for type deduction.
4399 ArgType = ArgType.getUnqualifiedType();
4400 }
4401 }
4402
4403 // C++0x [temp.deduct.call]p4:
4404 // In general, the deduction process attempts to find template argument
4405 // values that will make the deduced A identical to A (after the type A
4406 // is transformed as described above). [...]
4408
4409 // - If the original P is a reference type, the deduced A (i.e., the
4410 // type referred to by the reference) can be more cv-qualified than
4411 // the transformed A.
4412 if (ParamRefType)
4414 // - The transformed A can be another pointer or pointer to member
4415 // type that can be converted to the deduced A via a qualification
4416 // conversion (4.4).
4417 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
4418 ArgType->isObjCObjectPointerType())
4419 TDF |= TDF_IgnoreQualifiers;
4420 // - If P is a class and P has the form simple-template-id, then the
4421 // transformed A can be a derived class of the deduced A. Likewise,
4422 // if P is a pointer to a class of the form simple-template-id, the
4423 // transformed A can be a pointer to a derived class pointed to by
4424 // the deduced A.
4425 if (isSimpleTemplateIdType(ParamType) ||
4426 (isa<PointerType>(ParamType) &&
4428 ParamType->castAs<PointerType>()->getPointeeType())))
4429 TDF |= TDF_DerivedClass;
4430
4431 return false;
4432}
4433
4434static bool
4436 QualType T);
4437
4439 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4440 QualType ParamType, QualType ArgType,
4441 Expr::Classification ArgClassification, Expr *Arg,
4445 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4446 TemplateSpecCandidateSet *FailedTSC = nullptr);
4447
4448/// Attempt template argument deduction from an initializer list
4449/// deemed to be an argument in a function call.
4451 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
4454 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
4455 unsigned TDF) {
4456 // C++ [temp.deduct.call]p1: (CWG 1591)
4457 // If removing references and cv-qualifiers from P gives
4458 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
4459 // a non-empty initializer list, then deduction is performed instead for
4460 // each element of the initializer list, taking P0 as a function template
4461 // parameter type and the initializer element as its argument
4462 //
4463 // We've already removed references and cv-qualifiers here.
4464 if (!ILE->getNumInits())
4466
4467 QualType ElTy;
4468 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
4469 if (ArrTy)
4470 ElTy = ArrTy->getElementType();
4471 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
4472 // Otherwise, an initializer list argument causes the parameter to be
4473 // considered a non-deduced context
4475 }
4476
4477 // Resolving a core issue: a braced-init-list containing any designators is
4478 // a non-deduced context.
4479 for (Expr *E : ILE->inits())
4480 if (isa<DesignatedInitExpr>(E))
4482
4483 // Deduction only needs to be done for dependent types.
4484 if (ElTy->isDependentType()) {
4485 for (Expr *E : ILE->inits()) {
4487 S, TemplateParams, 0, ElTy, E->getType(),
4488 E->Classify(S.getASTContext()), E, Info, Deduced,
4489 OriginalCallArgs, true, ArgIdx, TDF);
4491 return Result;
4492 }
4493 }
4494
4495 // in the P0[N] case, if N is a non-type template parameter, N is deduced
4496 // from the length of the initializer list.
4497 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
4498 // Determine the array bound is something we can deduce.
4499 if (const NonTypeTemplateParmDecl *NTTP =
4500 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
4501 // We can perform template argument deduction for the given non-type
4502 // template parameter.
4503 // C++ [temp.deduct.type]p13:
4504 // The type of N in the type T[N] is std::size_t.
4506 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
4508 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
4509 /*ArrayBound=*/true, Info, /*PartialOrdering=*/false, Deduced,
4510 /*HasDeducedAnyParam=*/nullptr);
4512 return Result;
4513 }
4514 }
4515
4517}
4518
4519/// Perform template argument deduction per [temp.deduct.call] for a
4520/// single parameter / argument pair.
4522 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4523 QualType ParamType, QualType ArgType,
4524 Expr::Classification ArgClassification, Expr *Arg,
4528 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4529 TemplateSpecCandidateSet *FailedTSC) {
4530
4531 QualType OrigParamType = ParamType;
4532
4533 // If P is a reference type [...]
4534 // If P is a cv-qualified type [...]
4536 S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
4537 ArgClassification, Arg, TDF, FailedTSC))
4539
4540 // If [...] the argument is a non-empty initializer list [...]
4541 if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
4542 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
4543 Deduced, OriginalCallArgs, ArgIdx, TDF);
4544
4545 // [...] the deduction process attempts to find template argument values
4546 // that will make the deduced A identical to A
4547 //
4548 // Keep track of the argument type and corresponding parameter index,
4549 // so we can check for compatibility between the deduced A and A.
4550 if (Arg)
4551 OriginalCallArgs.push_back(
4552 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
4554 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4555 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4556 /*HasDeducedAnyParam=*/nullptr);
4557}
4558
4560 FunctionTemplateDecl *FunctionTemplate,
4561 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4563 bool PartialOverloading, bool AggregateDeductionCandidate,
4564 bool PartialOrdering, QualType ObjectType,
4565 Expr::Classification ObjectClassification,
4566 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
4567 if (FunctionTemplate->isInvalidDecl())
4569
4570 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4571 unsigned NumParams = Function->getNumParams();
4572 bool HasExplicitObject = false;
4573 int ExplicitObjectOffset = 0;
4574 if (Function->hasCXXExplicitFunctionObjectParameter()) {
4575 HasExplicitObject = true;
4576 ExplicitObjectOffset = 1;
4577 }
4578
4579 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
4580
4581 // C++ [temp.deduct.call]p1:
4582 // Template argument deduction is done by comparing each function template
4583 // parameter type (call it P) with the type of the corresponding argument
4584 // of the call (call it A) as described below.
4585 if (Args.size() < Function->getMinRequiredExplicitArguments() &&
4586 !PartialOverloading)
4588 else if (TooManyArguments(NumParams, Args.size() + ExplicitObjectOffset,
4589 PartialOverloading)) {
4590 const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
4591 if (Proto->isTemplateVariadic())
4592 /* Do nothing */;
4593 else if (!Proto->isVariadic())
4595 }
4596
4597 // The types of the parameters from which we will perform template argument
4598 // deduction.
4599 LocalInstantiationScope InstScope(*this);
4600 TemplateParameterList *TemplateParams
4601 = FunctionTemplate->getTemplateParameters();
4603 SmallVector<QualType, 8> ParamTypes;
4604 unsigned NumExplicitlySpecified = 0;
4605 if (ExplicitTemplateArgs) {
4608 Result = SubstituteExplicitTemplateArguments(
4609 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4610 Info);
4611 });
4613 return Result;
4614
4615 NumExplicitlySpecified = Deduced.size();
4616 } else {
4617 // Just fill in the parameter types from the function declaration.
4618 for (unsigned I = 0; I != NumParams; ++I)
4619 ParamTypes.push_back(Function->getParamDecl(I)->getType());
4620 }
4621
4622 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
4623
4624 // Deduce an argument of type ParamType from an expression with index ArgIdx.
4625 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx,
4626 bool ExplicitObjectArgument) {
4627 // C++ [demp.deduct.call]p1: (DR1391)
4628 // Template argument deduction is done by comparing each function template
4629 // parameter that contains template-parameters that participate in
4630 // template argument deduction ...
4631 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4633
4634 if (ExplicitObjectArgument) {
4635 // ... with the type of the corresponding argument
4637 *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
4638 ObjectClassification,
4639 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4640 /*Decomposed*/ false, ArgIdx, /*TDF*/ 0);
4641 }
4642
4643 // ... with the type of the corresponding argument
4645 *this, TemplateParams, FirstInnerIndex, ParamType,
4646 Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()),
4647 Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false,
4648 ArgIdx, /*TDF*/ 0);
4649 };
4650
4651 // Deduce template arguments from the function parameters.
4652 Deduced.resize(TemplateParams->size());
4653 SmallVector<QualType, 8> ParamTypesForArgChecking;
4654 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4655 ParamIdx != NumParamTypes; ++ParamIdx) {
4656 QualType ParamType = ParamTypes[ParamIdx];
4657
4658 const PackExpansionType *ParamExpansion =
4659 dyn_cast<PackExpansionType>(ParamType);
4660 if (!ParamExpansion) {
4661 // Simple case: matching a function parameter to a function argument.
4662 if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0))
4663 break;
4664
4665 ParamTypesForArgChecking.push_back(ParamType);
4666
4667 if (ParamIdx == 0 && HasExplicitObject) {
4668 if (ObjectType.isNull())
4670
4671 if (auto Result = DeduceCallArgument(ParamType, 0,
4672 /*ExplicitObjectArgument=*/true);
4674 return Result;
4675 continue;
4676 }
4677
4678 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4679 /*ExplicitObjectArgument=*/false);
4681 return Result;
4682
4683 continue;
4684 }
4685
4686 bool IsTrailingPack = ParamIdx + 1 == NumParamTypes;
4687
4688 QualType ParamPattern = ParamExpansion->getPattern();
4689 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
4690 ParamPattern,
4691 AggregateDeductionCandidate && IsTrailingPack);
4692
4693 // C++0x [temp.deduct.call]p1:
4694 // For a function parameter pack that occurs at the end of the
4695 // parameter-declaration-list, the type A of each remaining argument of
4696 // the call is compared with the type P of the declarator-id of the
4697 // function parameter pack. Each comparison deduces template arguments
4698 // for subsequent positions in the template parameter packs expanded by
4699 // the function parameter pack. When a function parameter pack appears
4700 // in a non-deduced context [not at the end of the list], the type of
4701 // that parameter pack is never deduced.
4702 //
4703 // FIXME: The above rule allows the size of the parameter pack to change
4704 // after we skip it (in the non-deduced case). That makes no sense, so
4705 // we instead notionally deduce the pack against N arguments, where N is
4706 // the length of the explicitly-specified pack if it's expanded by the
4707 // parameter pack and 0 otherwise, and we treat each deduction as a
4708 // non-deduced context.
4709 if (IsTrailingPack || PackScope.hasFixedArity()) {
4710 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4711 PackScope.nextPackElement(), ++ArgIdx) {
4712 ParamTypesForArgChecking.push_back(ParamPattern);
4713 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4714 /*ExplicitObjectArgument=*/false);
4716 return Result;
4717 }
4718 } else {
4719 // If the parameter type contains an explicitly-specified pack that we
4720 // could not expand, skip the number of parameters notionally created
4721 // by the expansion.
4722 std::optional<unsigned> NumExpansions =
4723 ParamExpansion->getNumExpansions();
4724 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4725 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4726 ++I, ++ArgIdx) {
4727 ParamTypesForArgChecking.push_back(ParamPattern);
4728 // FIXME: Should we add OriginalCallArgs for these? What if the
4729 // corresponding argument is a list?
4730 PackScope.nextPackElement();
4731 }
4732 } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4733 PackScope.isDeducedFromEarlierParameter()) {
4734 // [temp.deduct.general#3]
4735 // When all template arguments have been deduced
4736 // or obtained from default template arguments, all uses of template
4737 // parameters in the template parameter list of the template are
4738 // replaced with the corresponding deduced or default argument values
4739 //
4740 // If we have a trailing parameter pack, that has been deduced
4741 // previously we substitute the pack here in a similar fashion as
4742 // above with the trailing parameter packs. The main difference here is
4743 // that, in this case we are not processing all of the remaining
4744 // arguments. We are only process as many arguments as we have in
4745 // the already deduced parameter.
4746 std::optional<unsigned> ArgPosAfterSubstitution =
4747 PackScope.getSavedPackSizeIfAllEqual();
4748 if (!ArgPosAfterSubstitution)
4749 continue;
4750
4751 unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4752 for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4753 ParamTypesForArgChecking.push_back(ParamPattern);
4754 if (auto Result =
4755 DeduceCallArgument(ParamPattern, ArgIdx,
4756 /*ExplicitObjectArgument=*/false);
4758 return Result;
4759
4760 PackScope.nextPackElement();
4761 }
4762 }
4763 }
4764
4765 // Build argument packs for each of the parameter packs expanded by this
4766 // pack expansion.
4767 if (auto Result = PackScope.finish();
4769 return Result;
4770 }
4771
4772 // Capture the context in which the function call is made. This is the context
4773 // that is needed when the accessibility of template arguments is checked.
4774 DeclContext *CallingCtx = CurContext;
4775
4778 Result = FinishTemplateArgumentDeduction(
4779 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4780 &OriginalCallArgs, PartialOverloading, PartialOrdering,
4781 [&, CallingCtx]() {
4782 ContextRAII SavedContext(*this, CallingCtx);
4783 return CheckNonDependent(ParamTypesForArgChecking);
4784 });
4785 });
4786 return Result;
4787}
4788
4791 bool AdjustExceptionSpec) {
4792 if (ArgFunctionType.isNull())
4793 return ArgFunctionType;
4794
4795 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4796 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4797 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4798 bool Rebuild = false;
4799
4800 CallingConv CC = FunctionTypeP->getCallConv();
4801 if (EPI.ExtInfo.getCC() != CC) {
4802 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4803 Rebuild = true;
4804 }
4805
4806 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4807 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4808 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4809 Rebuild = true;
4810 }
4811
4812 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4813 ArgFunctionTypeP->hasExceptionSpec())) {
4814 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4815 Rebuild = true;
4816 }
4817
4818 if (!Rebuild)
4819 return ArgFunctionType;
4820
4821 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4822 ArgFunctionTypeP->getParamTypes(), EPI);
4823}
4824
4826 FunctionTemplateDecl *FunctionTemplate,
4827 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4829 bool IsAddressOfFunction) {
4830 if (FunctionTemplate->isInvalidDecl())
4832
4833 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4834 TemplateParameterList *TemplateParams
4835 = FunctionTemplate->getTemplateParameters();
4836 QualType FunctionType = Function->getType();
4837
4838 // Substitute any explicit template arguments.
4839 LocalInstantiationScope InstScope(*this);
4841 unsigned NumExplicitlySpecified = 0;
4842 SmallVector<QualType, 4> ParamTypes;
4843 if (ExplicitTemplateArgs) {
4846 Result = SubstituteExplicitTemplateArguments(
4847 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4848 &FunctionType, Info);
4849 });
4851 return Result;
4852
4853 NumExplicitlySpecified = Deduced.size();
4854 }
4855
4856 // When taking the address of a function, we require convertibility of
4857 // the resulting function type. Otherwise, we allow arbitrary mismatches
4858 // of calling convention and noreturn.
4859 if (!IsAddressOfFunction)
4860 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4861 /*AdjustExceptionSpec*/false);
4862
4863 // Unevaluated SFINAE context.
4866 SFINAETrap Trap(*this);
4867
4868 Deduced.resize(TemplateParams->size());
4869
4870 // If the function has a deduced return type, substitute it for a dependent
4871 // type so that we treat it as a non-deduced context in what follows.
4872 bool HasDeducedReturnType = false;
4873 if (getLangOpts().CPlusPlus14 &&
4874 Function->getReturnType()->getContainedAutoType()) {
4876 HasDeducedReturnType = true;
4877 }
4878
4879 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
4880 unsigned TDF =
4882 // Deduce template arguments from the function type.
4884 *this, TemplateParams, FunctionType, ArgFunctionType, Info, Deduced,
4885 TDF, PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4886 /*HasDeducedAnyParam=*/nullptr);
4888 return Result;
4889 }
4890
4893 Result = FinishTemplateArgumentDeduction(
4894 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4895 /*OriginalCallArgs=*/nullptr, /*PartialOverloading=*/false,
4896 /*PartialOrdering=*/true);
4897 });
4899 return Result;
4900
4901 // If the function has a deduced return type, deduce it now, so we can check
4902 // that the deduced function type matches the requested type.
4903 if (HasDeducedReturnType && IsAddressOfFunction &&
4904 Specialization->getReturnType()->isUndeducedType() &&
4907
4908 // [C++26][expr.const]/p17
4909 // An expression or conversion is immediate-escalating if it is not initially
4910 // in an immediate function context and it is [...]
4911 // a potentially-evaluated id-expression that denotes an immediate function.
4912 if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
4913 Specialization->isImmediateEscalating() &&
4914 parentEvaluationContext().isPotentiallyEvaluated() &&
4916 Info.getLocation()))
4918
4919 // Adjust the exception specification of the argument to match the
4920 // substituted and resolved type we just formed. (Calling convention and
4921 // noreturn can't be dependent, so we don't actually need this for them
4922 // right now.)
4923 QualType SpecializationType = Specialization->getType();
4924 if (!IsAddressOfFunction) {
4925 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4926 /*AdjustExceptionSpec*/true);
4927
4928 // Revert placeholder types in the return type back to undeduced types so
4929 // that the comparison below compares the declared return types.
4930 if (HasDeducedReturnType) {
4931 SpecializationType = SubstAutoType(SpecializationType, QualType());
4932 ArgFunctionType = SubstAutoType(ArgFunctionType, QualType());
4933 }
4934 }
4935
4936 // If the requested function type does not match the actual type of the
4937 // specialization with respect to arguments of compatible pointer to function
4938 // types, template argument deduction fails.
4939 if (!ArgFunctionType.isNull()) {
4940 if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
4941 SpecializationType, ArgFunctionType)
4943 SpecializationType, ArgFunctionType)) {
4944 Info.FirstArg = TemplateArgument(SpecializationType);
4945 Info.SecondArg = TemplateArgument(ArgFunctionType);
4947 }
4948 }
4949
4951}
4952
4954 FunctionTemplateDecl *ConversionTemplate, QualType ObjectType,
4955 Expr::Classification ObjectClassification, QualType A,
4957 if (ConversionTemplate->isInvalidDecl())
4959
4960 CXXConversionDecl *ConversionGeneric
4961 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4962
4963 QualType P = ConversionGeneric->getConversionType();
4964 bool IsReferenceP = P->isReferenceType();
4965 bool IsReferenceA = A->isReferenceType();
4966
4967 // C++0x [temp.deduct.conv]p2:
4968 // If P is a reference type, the type referred to by P is used for
4969 // type deduction.
4970 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4971 P = PRef->getPointeeType();
4972
4973 // C++0x [temp.deduct.conv]p4:
4974 // [...] If A is a reference type, the type referred to by A is used
4975 // for type deduction.
4976 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4977 A = ARef->getPointeeType();
4978 // We work around a defect in the standard here: cv-qualifiers are also
4979 // removed from P and A in this case, unless P was a reference type. This
4980 // seems to mostly match what other compilers are doing.
4981 if (!IsReferenceP) {
4982 A = A.getUnqualifiedType();
4983 P = P.getUnqualifiedType();
4984 }
4985
4986 // C++ [temp.deduct.conv]p3:
4987 //
4988 // If A is not a reference type:
4989 } else {
4990 assert(!A->isReferenceType() && "Reference types were handled above");
4991
4992 // - If P is an array type, the pointer type produced by the
4993 // array-to-pointer standard conversion (4.2) is used in place
4994 // of P for type deduction; otherwise,
4995 if (P->isArrayType())
4997 // - If P is a function type, the pointer type produced by the
4998 // function-to-pointer standard conversion (4.3) is used in
4999 // place of P for type deduction; otherwise,
5000 else if (P->isFunctionType())
5002 // - If P is a cv-qualified type, the top level cv-qualifiers of
5003 // P's type are ignored for type deduction.
5004 else
5005 P = P.getUnqualifiedType();
5006
5007 // C++0x [temp.deduct.conv]p4:
5008 // If A is a cv-qualified type, the top level cv-qualifiers of A's
5009 // type are ignored for type deduction. If A is a reference type, the type
5010 // referred to by A is used for type deduction.
5011 A = A.getUnqualifiedType();
5012 }
5013
5014 // Unevaluated SFINAE context.
5017 SFINAETrap Trap(*this);
5018
5019 // C++ [temp.deduct.conv]p1:
5020 // Template argument deduction is done by comparing the return
5021 // type of the template conversion function (call it P) with the
5022 // type that is required as the result of the conversion (call it
5023 // A) as described in 14.8.2.4.
5024 TemplateParameterList *TemplateParams
5025 = ConversionTemplate->getTemplateParameters();
5027 Deduced.resize(TemplateParams->size());
5028
5029 // C++0x [temp.deduct.conv]p4:
5030 // In general, the deduction process attempts to find template
5031 // argument values that will make the deduced A identical to
5032 // A. However, there are two cases that allow a difference:
5033 unsigned TDF = 0;
5034 // - If the original A is a reference type, A can be more
5035 // cv-qualified than the deduced A (i.e., the type referred to
5036 // by the reference)
5037 if (IsReferenceA)
5039 // - The deduced A can be another pointer or pointer to member
5040 // type that can be converted to A via a qualification
5041 // conversion.
5042 //
5043 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
5044 // both P and A are pointers or member pointers. In this case, we
5045 // just ignore cv-qualifiers completely).
5046 if ((P->isPointerType() && A->isPointerType()) ||
5047 (P->isMemberPointerType() && A->isMemberPointerType()))
5048 TDF |= TDF_IgnoreQualifiers;
5049
5051 if (ConversionGeneric->isExplicitObjectMemberFunction()) {
5052 QualType ParamType = ConversionGeneric->getParamDecl(0)->getType();
5055 *this, TemplateParams, getFirstInnerIndex(ConversionTemplate),
5056 ParamType, ObjectType, ObjectClassification,
5057 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
5058 /*Decomposed*/ false, 0, /*TDF*/ 0);
5060 return Result;
5061 }
5062
5064 *this, TemplateParams, P, A, Info, Deduced, TDF,
5065 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
5066 /*HasDeducedAnyParam=*/nullptr);
5068 return Result;
5069
5070 // Create an Instantiation Scope for finalizing the operator.
5071 LocalInstantiationScope InstScope(*this);
5072 // Finish template argument deduction.
5073 FunctionDecl *ConversionSpecialized = nullptr;
5076 Result = FinishTemplateArgumentDeduction(
5077 ConversionTemplate, Deduced, 0, ConversionSpecialized, Info,
5078 &OriginalCallArgs, /*PartialOverloading=*/false,
5079 /*PartialOrdering=*/false);
5080 });
5081 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
5082 return Result;
5083}
5084
5087 TemplateArgumentListInfo *ExplicitTemplateArgs,
5090 bool IsAddressOfFunction) {
5091 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
5092 QualType(), Specialization, Info,
5093 IsAddressOfFunction);
5094}
5095
5096namespace {
5097 struct DependentAuto { bool IsPack; };
5098
5099 /// Substitute the 'auto' specifier or deduced template specialization type
5100 /// specifier within a type for a given replacement type.
5101 class SubstituteDeducedTypeTransform :
5102 public TreeTransform<SubstituteDeducedTypeTransform> {
5103 QualType Replacement;
5104 bool ReplacementIsPack;
5105 bool UseTypeSugar;
5107
5108 public:
5109 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
5110 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5111 ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
5112
5113 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
5114 bool UseTypeSugar = true)
5115 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5116 Replacement(Replacement), ReplacementIsPack(false),
5117 UseTypeSugar(UseTypeSugar) {}
5118
5119 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
5120 assert(isa<TemplateTypeParmType>(Replacement) &&
5121 "unexpected unsugared replacement kind");
5122 QualType Result = Replacement;
5124 NewTL.setNameLoc(TL.getNameLoc());
5125 return Result;
5126 }
5127
5128 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
5129 // If we're building the type pattern to deduce against, don't wrap the
5130 // substituted type in an AutoType. Certain template deduction rules
5131 // apply only when a template type parameter appears directly (and not if
5132 // the parameter is found through desugaring). For instance:
5133 // auto &&lref = lvalue;
5134 // must transform into "rvalue reference to T" not "rvalue reference to
5135 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
5136 //
5137 // FIXME: Is this still necessary?
5138 if (!UseTypeSugar)
5139 return TransformDesugared(TLB, TL);
5140
5141 QualType Result = SemaRef.Context.getAutoType(
5142 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
5143 ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(),
5145 auto NewTL = TLB.push<AutoTypeLoc>(Result);
5146 NewTL.copy(TL);
5147 return Result;
5148 }
5149
5150 QualType TransformDeducedTemplateSpecializationType(
5152 if (!UseTypeSugar)
5153 return TransformDesugared(TLB, TL);
5154
5155 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
5157 Replacement, Replacement.isNull());
5158 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5159 NewTL.setNameLoc(TL.getNameLoc());
5160 return Result;
5161 }
5162
5163 ExprResult TransformLambdaExpr(LambdaExpr *E) {
5164 // Lambdas never need to be transformed.
5165 return E;
5166 }
5167 bool TransformExceptionSpec(SourceLocation Loc,
5169 SmallVectorImpl<QualType> &Exceptions,
5170 bool &Changed) {
5171 if (ESI.Type == EST_Uninstantiated) {
5172 ESI.instantiate();
5173 Changed = true;
5174 }
5175 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
5176 }
5177
5178 QualType Apply(TypeLoc TL) {
5179 // Create some scratch storage for the transformed type locations.
5180 // FIXME: We're just going to throw this information away. Don't build it.
5181 TypeLocBuilder TLB;
5182 TLB.reserve(TL.getFullDataSize());
5183 return TransformType(TLB, TL);
5184 }
5185 };
5186
5187} // namespace
5188
5191 QualType Deduced) {
5192 ConstraintSatisfaction Satisfaction;
5193 ConceptDecl *Concept = Type.getTypeConstraintConcept();
5194 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
5195 TypeLoc.getRAngleLoc());
5196 TemplateArgs.addArgument(
5199 Deduced, TypeLoc.getNameLoc())));
5200 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
5201 TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
5202
5204 if (S.CheckTemplateArgumentList(Concept, SourceLocation(), TemplateArgs,
5205 /*DefaultArgs=*/{},
5206 /*PartialTemplateArgs=*/false, CTAI))
5207 return true;
5209 /*Final=*/false);
5210 // Build up an EvaluationContext with an ImplicitConceptSpecializationDecl so
5211 // that the template arguments of the constraint can be preserved. For
5212 // example:
5213 //
5214 // template <class T>
5215 // concept C = []<D U = void>() { return true; }();
5216 //
5217 // We need the argument for T while evaluating type constraint D in
5218 // building the CallExpr to the lambda.
5222 S.getASTContext(), Concept->getDeclContext(), Concept->getLocation(),
5223 CTAI.CanonicalConverted));
5224 if (S.CheckConstraintSatisfaction(Concept, {Concept->getConstraintExpr()},
5226 Satisfaction))
5227 return true;
5228 if (!Satisfaction.IsSatisfied) {
5229 std::string Buf;
5230 llvm::raw_string_ostream OS(Buf);
5231 OS << "'" << Concept->getName();
5232 if (TypeLoc.hasExplicitTemplateArgs()) {
5234 OS, Type.getTypeConstraintArguments(), S.getPrintingPolicy(),
5235 Type.getTypeConstraintConcept()->getTemplateParameters());
5236 }
5237 OS << "'";
5238 S.Diag(TypeLoc.getConceptNameLoc(),
5239 diag::err_placeholder_constraints_not_satisfied)
5240 << Deduced << Buf << TypeLoc.getLocalSourceRange();
5241 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
5242 return true;
5243 }
5244 return false;
5245}
5246
5249 TemplateDeductionInfo &Info, bool DependentDeduction,
5250 bool IgnoreConstraints,
5251 TemplateSpecCandidateSet *FailedTSC) {
5252 assert(DependentDeduction || Info.getDeducedDepth() == 0);
5253 if (Init->containsErrors())
5255
5256 const AutoType *AT = Type.getType()->getContainedAutoType();
5257 assert(AT);
5258
5259 if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
5260 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
5261 if (NonPlaceholder.isInvalid())
5263 Init = NonPlaceholder.get();
5264 }
5265
5266 DependentAuto DependentResult = {
5267 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
5268
5269 if (!DependentDeduction &&
5270 (Type.getType()->isDependentType() || Init->isTypeDependent() ||
5271 Init->containsUnexpandedParameterPack())) {
5272 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5273 assert(!Result.isNull() && "substituting DependentTy can't fail");
5275 }
5276
5277 // Make sure that we treat 'char[]' equaly as 'char*' in C23 mode.
5278 auto *String = dyn_cast<StringLiteral>(Init);
5279 if (getLangOpts().C23 && String && Type.getType()->isArrayType()) {
5280 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5281 TypeLoc TL = TypeLoc(Init->getType(), Type.getOpaqueData());
5282 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(TL);
5283 assert(!Result.isNull() && "substituting DependentTy can't fail");
5285 }
5286
5287 // Emit a warning if 'auto*' is used in pedantic and in C23 mode.
5288 if (getLangOpts().C23 && Type.getType()->isPointerType()) {
5289 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5290 }
5291
5292 auto *InitList = dyn_cast<InitListExpr>(Init);
5293 if (!getLangOpts().CPlusPlus && InitList) {
5294 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c)
5295 << (int)AT->getKeyword() << getLangOpts().C23;
5297 }
5298
5299 // Deduce type of TemplParam in Func(Init)
5301 Deduced.resize(1);
5302
5303 // If deduction failed, don't diagnose if the initializer is dependent; it
5304 // might acquire a matching type in the instantiation.
5305 auto DeductionFailed = [&](TemplateDeductionResult TDK) {
5306 if (Init->isTypeDependent()) {
5307 Result =
5308 SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5309 assert(!Result.isNull() && "substituting DependentTy can't fail");
5311 }
5312 return TDK;
5313 };
5314
5315 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
5316
5318 // If this is a 'decltype(auto)' specifier, do the decltype dance.
5319 if (AT->isDecltypeAuto()) {
5320 if (InitList) {
5321 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
5323 }
5324
5326 assert(!DeducedType.isNull());
5327 } else {
5328 LocalInstantiationScope InstScope(*this);
5329
5330 // Build template<class TemplParam> void Func(FuncParam);
5331 SourceLocation Loc = Init->getExprLoc();
5333 Context, nullptr, SourceLocation(), Loc, Info.getDeducedDepth(), 0,
5334 nullptr, false, false, false);
5335 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
5336 NamedDecl *TemplParamPtr = TemplParam;
5338 Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
5339
5340 if (InitList) {
5341 // Notionally, we substitute std::initializer_list<T> for 'auto' and
5342 // deduce against that. Such deduction only succeeds if removing
5343 // cv-qualifiers and references results in std::initializer_list<T>.
5344 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
5346
5347 SourceRange DeducedFromInitRange;
5348 for (Expr *Init : InitList->inits()) {
5349 // Resolving a core issue: a braced-init-list containing any designators
5350 // is a non-deduced context.
5351 if (isa<DesignatedInitExpr>(Init))
5354 *this, TemplateParamsSt.get(), 0, TemplArg, Init->getType(),
5355 Init->Classify(getASTContext()), Init, Info, Deduced,
5356 OriginalCallArgs,
5357 /*Decomposed=*/true,
5358 /*ArgIdx=*/0, /*TDF=*/0);
5361 Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction)
5362 << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
5363 << Init->getSourceRange();
5364 return DeductionFailed(TemplateDeductionResult::AlreadyDiagnosed);
5365 }
5366 return DeductionFailed(TDK);
5367 }
5368
5369 if (DeducedFromInitRange.isInvalid() &&
5370 Deduced[0].getKind() != TemplateArgument::Null)
5371 DeducedFromInitRange = Init->getSourceRange();
5372 }
5373 } else {
5374 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
5375 Diag(Loc, diag::err_auto_bitfield);
5377 }
5378 QualType FuncParam =
5379 SubstituteDeducedTypeTransform(*this, TemplArg).Apply(Type);
5380 assert(!FuncParam.isNull() &&
5381 "substituting template parameter for 'auto' failed");
5383 *this, TemplateParamsSt.get(), 0, FuncParam, Init->getType(),
5384 Init->Classify(getASTContext()), Init, Info, Deduced,
5385 OriginalCallArgs,
5386 /*Decomposed=*/false, /*ArgIdx=*/0, /*TDF=*/0, FailedTSC);
5388 return DeductionFailed(TDK);
5389 }
5390
5391 // Could be null if somehow 'auto' appears in a non-deduced context.
5392 if (Deduced[0].getKind() != TemplateArgument::Type)
5393 return DeductionFailed(TemplateDeductionResult::Incomplete);
5394 DeducedType = Deduced[0].getAsType();
5395
5396 if (InitList) {
5398 if (DeducedType.isNull())
5400 }
5401 }
5402
5403 if (!Result.isNull()) {
5405 Info.FirstArg = Result;
5406 Info.SecondArg = DeducedType;
5407 return DeductionFailed(TemplateDeductionResult::Inconsistent);
5408 }
5410 }
5411
5412 if (AT->isConstrained() && !IgnoreConstraints &&
5414 *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType))
5416
5417 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
5418 if (Result.isNull())
5420
5421 // Check that the deduced argument type is compatible with the original
5422 // argument type per C++ [temp.deduct.call]p4.
5423 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
5424 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
5425 assert((bool)InitList == OriginalArg.DecomposedParam &&
5426 "decomposed non-init-list in auto deduction?");
5427 if (auto TDK =
5428 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
5430 Result = QualType();
5431 return DeductionFailed(TDK);
5432 }
5433 }
5434
5436}
5437
5439 QualType TypeToReplaceAuto) {
5440 assert(TypeToReplaceAuto != Context.DependentTy);
5441 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5442 .TransformType(TypeWithAuto);
5443}
5444
5446 QualType TypeToReplaceAuto) {
5447 assert(TypeToReplaceAuto != Context.DependentTy);
5448 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5449 .TransformType(TypeWithAuto);
5450}
5451
5453 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5454 .TransformType(TypeWithAuto);
5455}
5456
5459 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5460 .TransformType(TypeWithAuto);
5461}
5462
5464 QualType TypeToReplaceAuto) {
5465 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5466 /*UseTypeSugar*/ false)
5467 .TransformType(TypeWithAuto);
5468}
5469
5471 QualType TypeToReplaceAuto) {
5472 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5473 /*UseTypeSugar*/ false)
5474 .TransformType(TypeWithAuto);
5475}
5476
5478 const Expr *Init) {
5479 if (isa<InitListExpr>(Init))
5480 Diag(VDecl->getLocation(),
5481 VDecl->isInitCapture()
5482 ? diag::err_init_capture_deduction_failure_from_init_list
5483 : diag::err_auto_var_deduction_failure_from_init_list)
5484 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
5485 else
5486 Diag(VDecl->getLocation(),
5487 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
5488 : diag::err_auto_var_deduction_failure)
5489 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5490 << Init->getSourceRange();
5491}
5492
5494 bool Diagnose) {
5495 assert(FD->getReturnType()->isUndeducedType());
5496
5497 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
5498 // within the return type from the call operator's type.
5500 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5501 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5502
5503 // For a generic lambda, instantiate the call operator if needed.
5504 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5506 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5507 if (!CallOp || CallOp->isInvalidDecl())
5508 return true;
5509
5510 // We might need to deduce the return type by instantiating the definition
5511 // of the operator() function.
5512 if (CallOp->getReturnType()->isUndeducedType()) {
5515 });
5516 }
5517 }
5518
5519 if (CallOp->isInvalidDecl())
5520 return true;
5521 assert(!CallOp->getReturnType()->isUndeducedType() &&
5522 "failed to deduce lambda return type");
5523
5524 // Build the new return type from scratch.
5525 CallingConv RetTyCC = FD->getReturnType()
5526 ->getPointeeType()
5527 ->castAs<FunctionType>()
5528 ->getCallConv();
5530 CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
5531 if (FD->getReturnType()->getAs<PointerType>())
5532 RetType = Context.getPointerType(RetType);
5533 else {
5534 assert(FD->getReturnType()->getAs<BlockPointerType>());
5535 RetType = Context.getBlockPointerType(RetType);
5536 }
5538 return false;
5539 }
5540
5544 });
5545 }
5546
5547 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
5548 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
5549 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
5550 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
5551 }
5552
5553 return StillUndeduced;
5554}
5555
5558 assert(FD->isImmediateEscalating());
5559
5561 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5562 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5563
5564 // For a generic lambda, instantiate the call operator if needed.
5565 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5567 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5568 if (!CallOp || CallOp->isInvalidDecl())
5569 return true;
5571 Loc, [&] { InstantiateFunctionDefinition(Loc, CallOp); });
5572 }
5573 return CallOp->isInvalidDecl();
5574 }
5575
5578 Loc, [&] { InstantiateFunctionDefinition(Loc, FD); });
5579 }
5580 return false;
5581}
5582
5584 const CXXMethodDecl *Method,
5585 QualType RawType,
5586 bool IsOtherRvr) {
5587 // C++20 [temp.func.order]p3.1, p3.2:
5588 // - The type X(M) is "rvalue reference to cv A" if the optional
5589 // ref-qualifier of M is && or if M has no ref-qualifier and the
5590 // positionally-corresponding parameter of the other transformed template
5591 // has rvalue reference type; if this determination depends recursively
5592 // upon whether X(M) is an rvalue reference type, it is not considered to
5593 // have rvalue reference type.
5594 //
5595 // - Otherwise, X(M) is "lvalue reference to cv A".
5596 assert(Method && !Method->isExplicitObjectMemberFunction() &&
5597 "expected a member function with no explicit object parameter");
5598
5599 RawType = Context.getQualifiedType(RawType, Method->getMethodQualifiers());
5600 if (Method->getRefQualifier() == RQ_RValue ||
5601 (IsOtherRvr && Method->getRefQualifier() == RQ_None))
5602 return Context.getRValueReferenceType(RawType);
5603 return Context.getLValueReferenceType(RawType);
5604}
5605
5607 Sema &S, FunctionTemplateDecl *FTD, int ArgIdx, QualType P, QualType A,
5608 ArrayRef<TemplateArgument> DeducedArgs, bool CheckConsistency) {
5609 MultiLevelTemplateArgumentList MLTAL(FTD, DeducedArgs,
5610 /*Final=*/true);
5612 S, ArgIdx != -1 ? ::getPackIndexForParam(S, FTD, MLTAL, ArgIdx) : -1);
5613 bool IsIncompleteSubstitution = false;
5614 // FIXME: A substitution can be incomplete on a non-structural part of the
5615 // type. Use the canonical type for now, until the TemplateInstantiator can
5616 // deal with that.
5617 QualType InstP = S.SubstType(P.getCanonicalType(), MLTAL, FTD->getLocation(),
5618 FTD->getDeclName(), &IsIncompleteSubstitution);
5619 if (InstP.isNull() && !IsIncompleteSubstitution)
5621 if (!CheckConsistency)
5623 if (IsIncompleteSubstitution)
5625
5626 // [temp.deduct.call]/4 - Check we produced a consistent deduction.
5627 // This handles just the cases that can appear when partial ordering.
5628 if (auto *PA = dyn_cast<PackExpansionType>(A);
5629 PA && !isa<PackExpansionType>(InstP))
5630 A = PA->getPattern();
5631 if (!S.Context.hasSameType(
5636}
5637
5638template <class T>
5640 Sema &S, FunctionTemplateDecl *FTD,
5645 Sema::SFINAETrap Trap(S);
5646
5647 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(FTD));
5648
5649 // C++26 [temp.deduct.type]p2:
5650 // [...] or if any template argument remains neither deduced nor
5651 // explicitly specified, template argument deduction fails.
5652 bool IsIncomplete = false;
5653 Sema::CheckTemplateArgumentInfo CTAI(/*PartialOrdering=*/true);
5655 S, FTD, /*IsDeduced=*/true, Deduced, Info, CTAI,
5656 /*CurrentInstantiationScope=*/nullptr,
5657 /*NumAlreadyConverted=*/0, &IsIncomplete);
5659 return Result;
5660
5661 // Form the template argument list from the deduced template arguments.
5662 TemplateArgumentList *SugaredDeducedArgumentList =
5664 TemplateArgumentList *CanonicalDeducedArgumentList =
5666
5667 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
5668
5669 // Substitute the deduced template arguments into the argument
5670 // and verify that the instantiated argument is both valid
5671 // and equivalent to the parameter.
5672 LocalInstantiationScope InstScope(S);
5673
5674 if (auto TDR = CheckDeductionConsistency(S, FTD, CTAI.SugaredConverted);
5676 return TDR;
5677
5680}
5681
5682/// Determine whether the function template \p FT1 is at least as
5683/// specialized as \p FT2.
5687 ArrayRef<QualType> Args1, ArrayRef<QualType> Args2, bool Args1Offset) {
5688 FunctionDecl *FD1 = FT1->getTemplatedDecl();
5689 FunctionDecl *FD2 = FT2->getTemplatedDecl();
5690 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
5691 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
5692 assert(Proto1 && Proto2 && "Function templates must have prototypes");
5693
5694 // C++26 [temp.deduct.partial]p3:
5695 // The types used to determine the ordering depend on the context in which
5696 // the partial ordering is done:
5697 // - In the context of a function call, the types used are those function
5698 // parameter types for which the function call has arguments.
5699 // - In the context of a call to a conversion operator, the return types
5700 // of the conversion function templates are used.
5701 // - In other contexts (14.6.6.2) the function template's function type
5702 // is used.
5703
5704 if (TPOC == TPOC_Other) {
5705 // We wouldn't be partial ordering these candidates if these didn't match.
5706 assert(Proto1->getMethodQuals() == Proto2->getMethodQuals() &&
5707 Proto1->getRefQualifier() == Proto2->getRefQualifier() &&
5708 Proto1->isVariadic() == Proto2->isVariadic() &&
5709 "shouldn't partial order functions with different qualifiers in a "
5710 "context where the function type is used");
5711
5712 assert(Args1.empty() && Args2.empty() &&
5713 "Only call context should have arguments");
5714 Args1 = Proto1->getParamTypes();
5715 Args2 = Proto2->getParamTypes();
5716 }
5717
5718 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
5719 SmallVector<DeducedTemplateArgument, 4> Deduced(TemplateParams->size());
5721
5722 bool HasDeducedAnyParamFromReturnType = false;
5723 if (TPOC != TPOC_Call) {
5725 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
5726 Info, Deduced, TDF_None, PartialOrderingKind::Call,
5727 /*DeducedFromArrayBound=*/false,
5728 &HasDeducedAnyParamFromReturnType) !=
5730 return false;
5731 }
5732
5733 llvm::SmallBitVector HasDeducedParam;
5734 if (TPOC != TPOC_Conversion) {
5735 HasDeducedParam.resize(Args2.size());
5736 if (DeduceTemplateArguments(S, TemplateParams, Args2, Args1, Info, Deduced,
5737 TDF_None, PartialOrderingKind::Call,
5738 /*HasDeducedAnyParam=*/nullptr,
5739 &HasDeducedParam) !=
5741 return false;
5742 }
5743
5744 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
5746 S, Info.getLocation(), FT2, DeducedArgs,
5748 if (Inst.isInvalid())
5749 return false;
5750
5751 bool AtLeastAsSpecialized;
5753 AtLeastAsSpecialized =
5754 ::FinishTemplateArgumentDeduction(
5755 S, FT2, Deduced, Info,
5756 [&](Sema &S, FunctionTemplateDecl *FTD,
5757 ArrayRef<TemplateArgument> DeducedArgs) {
5758 // As a provisional fix for a core issue that does not
5759 // exist yet, which may be related to CWG2160, only check the
5760 // consistency of parameters and return types which participated
5761 // in deduction. We will still try to substitute them though.
5762 if (TPOC != TPOC_Call) {
5763 if (auto TDR = ::CheckDeductionConsistency(
5764 S, FTD, /*ArgIdx=*/-1, Proto2->getReturnType(),
5765 Proto1->getReturnType(), DeducedArgs,
5766 /*CheckConsistency=*/HasDeducedAnyParamFromReturnType);
5767 TDR != TemplateDeductionResult::Success)
5768 return TDR;
5769 }
5770
5771 if (TPOC == TPOC_Conversion)
5772 return TemplateDeductionResult::Success;
5773
5774 return ::DeduceForEachType(
5775 S, TemplateParams, Args2, Args1, Info, Deduced,
5776 PartialOrderingKind::Call, /*FinishingDeduction=*/true,
5777 [&](Sema &S, TemplateParameterList *, int ParamIdx,
5778 int ArgIdx, QualType P, QualType A,
5779 TemplateDeductionInfo &Info,
5780 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5781 PartialOrderingKind) {
5782 if (ArgIdx != -1)
5783 ArgIdx -= Args1Offset;
5784 return ::CheckDeductionConsistency(
5785 S, FTD, ArgIdx, P, A, DeducedArgs,
5786 /*CheckConsistency=*/HasDeducedParam[ParamIdx]);
5787 });
5789 });
5790 if (!AtLeastAsSpecialized)
5791 return false;
5792
5793 // C++0x [temp.deduct.partial]p11:
5794 // In most cases, all template parameters must have values in order for
5795 // deduction to succeed, but for partial ordering purposes a template
5796 // parameter may remain without a value provided it is not used in the
5797 // types being used for partial ordering. [ Note: a template parameter used
5798 // in a non-deduced context is considered used. -end note]
5799 unsigned ArgIdx = 0, NumArgs = Deduced.size();
5800 for (; ArgIdx != NumArgs; ++ArgIdx)
5801 if (Deduced[ArgIdx].isNull())
5802 break;
5803
5804 if (ArgIdx == NumArgs) {
5805 // All template arguments were deduced. FT1 is at least as specialized
5806 // as FT2.
5807 return true;
5808 }
5809
5810 // Figure out which template parameters were used.
5811 llvm::SmallBitVector UsedParameters(TemplateParams->size());
5812 switch (TPOC) {
5813 case TPOC_Call:
5814 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
5815 ::MarkUsedTemplateParameters(S.Context, Args2[I], /*OnlyDeduced=*/false,
5816 TemplateParams->getDepth(), UsedParameters);
5817 break;
5818
5819 case TPOC_Conversion:
5820 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(),
5821 /*OnlyDeduced=*/false,
5822 TemplateParams->getDepth(), UsedParameters);
5823 break;
5824
5825 case TPOC_Other:
5826 // We do not deduce template arguments from the exception specification
5827 // when determining the primary template of a function template
5828 // specialization or when taking the address of a function template.
5829 // Therefore, we do not mark template parameters in the exception
5830 // specification as used during partial ordering to prevent the following
5831 // from being ambiguous:
5832 //
5833 // template<typename T, typename U>
5834 // void f(U) noexcept(noexcept(T())); // #1
5835 //
5836 // template<typename T>
5837 // void f(T*) noexcept; // #2
5838 //
5839 // template<>
5840 // void f<int>(int*) noexcept; // explicit specialization of #2
5841 //
5842 // Although there is no corresponding wording in the standard, this seems
5843 // to be the intended behavior given the definition of
5844 // 'deduction substitution loci' in [temp.deduct].
5846 S.Context,
5848 /*OnlyDeduced=*/false, TemplateParams->getDepth(), UsedParameters);
5849 break;
5850 }
5851
5852 for (; ArgIdx != NumArgs; ++ArgIdx)
5853 // If this argument had no value deduced but was used in one of the types
5854 // used for partial ordering, then deduction fails.
5855 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
5856 return false;
5857
5858 return true;
5859}
5860
5863 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
5864 QualType RawObj1Ty, QualType RawObj2Ty, bool Reversed) {
5867 const FunctionDecl *FD1 = FT1->getTemplatedDecl();
5868 const FunctionDecl *FD2 = FT2->getTemplatedDecl();
5869 bool ShouldConvert1 = false;
5870 bool ShouldConvert2 = false;
5871 bool Args1Offset = false;
5872 bool Args2Offset = false;
5873 QualType Obj1Ty;
5874 QualType Obj2Ty;
5875 if (TPOC == TPOC_Call) {
5876 const FunctionProtoType *Proto1 =
5877 FD1->getType()->castAs<FunctionProtoType>();
5878 const FunctionProtoType *Proto2 =
5879 FD2->getType()->castAs<FunctionProtoType>();
5880
5881 // - In the context of a function call, the function parameter types are
5882 // used.
5883 const CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
5884 const CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
5885 // C++20 [temp.func.order]p3
5886 // [...] Each function template M that is a member function is
5887 // considered to have a new first parameter of type
5888 // X(M), described below, inserted in its function parameter list.
5889 //
5890 // Note that we interpret "that is a member function" as
5891 // "that is a member function with no expicit object argument".
5892 // Otherwise the ordering rules for methods with expicit objet arguments
5893 // against anything else make no sense.
5894
5895 bool NonStaticMethod1 = Method1 && !Method1->isStatic(),
5896 NonStaticMethod2 = Method2 && !Method2->isStatic();
5897
5898 auto Params1Begin = Proto1->param_type_begin(),
5899 Params2Begin = Proto2->param_type_begin();
5900
5901 size_t NumComparedArguments = NumCallArguments1;
5902
5903 if (auto OO = FD1->getOverloadedOperator();
5904 (NonStaticMethod1 && NonStaticMethod2) ||
5905 (OO != OO_None && OO != OO_Call && OO != OO_Subscript)) {
5906 ShouldConvert1 =
5907 NonStaticMethod1 && !Method1->hasCXXExplicitFunctionObjectParameter();
5908 ShouldConvert2 =
5909 NonStaticMethod2 && !Method2->hasCXXExplicitFunctionObjectParameter();
5910 NumComparedArguments += 1;
5911
5912 if (ShouldConvert1) {
5913 bool IsRValRef2 =
5914 ShouldConvert2
5915 ? Method2->getRefQualifier() == RQ_RValue
5916 : Proto2->param_type_begin()[0]->isRValueReferenceType();
5917 // Compare 'this' from Method1 against first parameter from Method2.
5918 Obj1Ty = GetImplicitObjectParameterType(this->Context, Method1,
5919 RawObj1Ty, IsRValRef2);
5920 Args1.push_back(Obj1Ty);
5921 Args1Offset = true;
5922 }
5923 if (ShouldConvert2) {
5924 bool IsRValRef1 =
5925 ShouldConvert1
5926 ? Method1->getRefQualifier() == RQ_RValue
5927 : Proto1->param_type_begin()[0]->isRValueReferenceType();
5928 // Compare 'this' from Method2 against first parameter from Method1.
5929 Obj2Ty = GetImplicitObjectParameterType(this->Context, Method2,
5930 RawObj2Ty, IsRValRef1);
5931 Args2.push_back(Obj2Ty);
5932 Args2Offset = true;
5933 }
5934 } else {
5935 if (NonStaticMethod1 && Method1->hasCXXExplicitFunctionObjectParameter())
5936 Params1Begin += 1;
5937 if (NonStaticMethod2 && Method2->hasCXXExplicitFunctionObjectParameter())
5938 Params2Begin += 1;
5939 }
5940 Args1.insert(Args1.end(), Params1Begin, Proto1->param_type_end());
5941 Args2.insert(Args2.end(), Params2Begin, Proto2->param_type_end());
5942
5943 // C++ [temp.func.order]p5:
5944 // The presence of unused ellipsis and default arguments has no effect on
5945 // the partial ordering of function templates.
5946 Args1.resize(std::min(Args1.size(), NumComparedArguments));
5947 Args2.resize(std::min(Args2.size(), NumComparedArguments));
5948
5949 if (Reversed)
5950 std::reverse(Args2.begin(), Args2.end());
5951 } else {
5952 assert(!Reversed && "Only call context could have reversed arguments");
5953 }
5954 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, Args1,
5955 Args2, Args2Offset);
5956 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, Args2,
5957 Args1, Args1Offset);
5958 // C++ [temp.deduct.partial]p10:
5959 // F is more specialized than G if F is at least as specialized as G and G
5960 // is not at least as specialized as F.
5961 if (Better1 != Better2) // We have a clear winner
5962 return Better1 ? FT1 : FT2;
5963
5964 if (!Better1 && !Better2) // Neither is better than the other
5965 return nullptr;
5966
5967 // C++ [temp.deduct.partial]p11:
5968 // ... and if G has a trailing function parameter pack for which F does not
5969 // have a corresponding parameter, and if F does not have a trailing
5970 // function parameter pack, then F is more specialized than G.
5971
5972 SmallVector<QualType> Param1;
5973 Param1.reserve(FD1->param_size() + ShouldConvert1);
5974 if (ShouldConvert1)
5975 Param1.push_back(Obj1Ty);
5976 for (const auto &P : FD1->parameters())
5977 Param1.push_back(P->getType());
5978
5979 SmallVector<QualType> Param2;
5980 Param2.reserve(FD2->param_size() + ShouldConvert2);
5981 if (ShouldConvert2)
5982 Param2.push_back(Obj2Ty);
5983 for (const auto &P : FD2->parameters())
5984 Param2.push_back(P->getType());
5985
5986 unsigned NumParams1 = Param1.size();
5987 unsigned NumParams2 = Param2.size();
5988
5989 bool Variadic1 =
5990 FD1->param_size() && FD1->parameters().back()->isParameterPack();
5991 bool Variadic2 =
5992 FD2->param_size() && FD2->parameters().back()->isParameterPack();
5993 if (Variadic1 != Variadic2) {
5994 if (Variadic1 && NumParams1 > NumParams2)
5995 return FT2;
5996 if (Variadic2 && NumParams2 > NumParams1)
5997 return FT1;
5998 }
5999
6000 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
6001 // there is no wording or even resolution for this issue.
6002 for (int i = 0, e = std::min(NumParams1, NumParams2); i < e; ++i) {
6003 QualType T1 = Param1[i].getCanonicalType();
6004 QualType T2 = Param2[i].getCanonicalType();
6005 auto *TST1 = dyn_cast<TemplateSpecializationType>(T1);
6006 auto *TST2 = dyn_cast<TemplateSpecializationType>(T2);
6007 if (!TST1 || !TST2)
6008 continue;
6009 const TemplateArgument &TA1 = TST1->template_arguments().back();
6010 if (TA1.getKind() == TemplateArgument::Pack) {
6011 assert(TST1->template_arguments().size() ==
6012 TST2->template_arguments().size());
6013 const TemplateArgument &TA2 = TST2->template_arguments().back();
6014 assert(TA2.getKind() == TemplateArgument::Pack);
6015 unsigned PackSize1 = TA1.pack_size();
6016 unsigned PackSize2 = TA2.pack_size();
6017 bool IsPackExpansion1 =
6018 PackSize1 && TA1.pack_elements().back().isPackExpansion();
6019 bool IsPackExpansion2 =
6020 PackSize2 && TA2.pack_elements().back().isPackExpansion();
6021 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
6022 if (PackSize1 > PackSize2 && IsPackExpansion1)
6023 return FT2;
6024 if (PackSize1 < PackSize2 && IsPackExpansion2)
6025 return FT1;
6026 }
6027 }
6028 }
6029
6030 if (!Context.getLangOpts().CPlusPlus20)
6031 return nullptr;
6032
6033 // Match GCC on not implementing [temp.func.order]p6.2.1.
6034
6035 // C++20 [temp.func.order]p6:
6036 // If deduction against the other template succeeds for both transformed
6037 // templates, constraints can be considered as follows:
6038
6039 // C++20 [temp.func.order]p6.1:
6040 // If their template-parameter-lists (possibly including template-parameters
6041 // invented for an abbreviated function template ([dcl.fct])) or function
6042 // parameter lists differ in length, neither template is more specialized
6043 // than the other.
6046 if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
6047 return nullptr;
6048
6049 // C++20 [temp.func.order]p6.2.2:
6050 // Otherwise, if the corresponding template-parameters of the
6051 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6052 // function parameters that positionally correspond between the two
6053 // templates are not of the same type, neither template is more specialized
6054 // than the other.
6055 if (!TemplateParameterListsAreEqual(TPL1, TPL2, false,
6057 return nullptr;
6058
6059 // [dcl.fct]p5:
6060 // Any top-level cv-qualifiers modifying a parameter type are deleted when
6061 // forming the function type.
6062 for (unsigned i = 0; i < NumParams1; ++i)
6063 if (!Context.hasSameUnqualifiedType(Param1[i], Param2[i]))
6064 return nullptr;
6065
6066 // C++20 [temp.func.order]p6.3:
6067 // Otherwise, if the context in which the partial ordering is done is
6068 // that of a call to a conversion function and the return types of the
6069 // templates are not the same, then neither template is more specialized
6070 // than the other.
6071 if (TPOC == TPOC_Conversion &&
6073 return nullptr;
6074
6076 FT1->getAssociatedConstraints(AC1);
6077 FT2->getAssociatedConstraints(AC2);
6078 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6079 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
6080 return nullptr;
6081 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
6082 return nullptr;
6083 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6084 return nullptr;
6085 return AtLeastAsConstrained1 ? FT1 : FT2;
6086}
6087
6090 TemplateSpecCandidateSet &FailedCandidates,
6091 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
6092 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
6093 bool Complain, QualType TargetType) {
6094 if (SpecBegin == SpecEnd) {
6095 if (Complain) {
6096 Diag(Loc, NoneDiag);
6097 FailedCandidates.NoteCandidates(*this, Loc);
6098 }
6099 return SpecEnd;
6100 }
6101
6102 if (SpecBegin + 1 == SpecEnd)
6103 return SpecBegin;
6104
6105 // Find the function template that is better than all of the templates it
6106 // has been compared to.
6107 UnresolvedSetIterator Best = SpecBegin;
6108 FunctionTemplateDecl *BestTemplate
6109 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
6110 assert(BestTemplate && "Not a function template specialization?");
6111 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
6112 FunctionTemplateDecl *Challenger
6113 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6114 assert(Challenger && "Not a function template specialization?");
6115 if (declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6116 Loc, TPOC_Other, 0),
6117 Challenger)) {
6118 Best = I;
6119 BestTemplate = Challenger;
6120 }
6121 }
6122
6123 // Make sure that the "best" function template is more specialized than all
6124 // of the others.
6125 bool Ambiguous = false;
6126 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6127 FunctionTemplateDecl *Challenger
6128 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6129 if (I != Best &&
6130 !declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6131 Loc, TPOC_Other, 0),
6132 BestTemplate)) {
6133 Ambiguous = true;
6134 break;
6135 }
6136 }
6137
6138 if (!Ambiguous) {
6139 // We found an answer. Return it.
6140 return Best;
6141 }
6142
6143 // Diagnose the ambiguity.
6144 if (Complain) {
6145 Diag(Loc, AmbigDiag);
6146
6147 // FIXME: Can we order the candidates in some sane way?
6148 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6149 PartialDiagnostic PD = CandidateDiag;
6150 const auto *FD = cast<FunctionDecl>(*I);
6152 FD->getPrimaryTemplate()->getTemplateParameters(),
6153 *FD->getTemplateSpecializationArgs());
6154 if (!TargetType.isNull())
6155 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
6156 Diag((*I)->getLocation(), PD);
6157 }
6158 }
6159
6160 return SpecEnd;
6161}
6162
6164 FunctionDecl *FD2) {
6165 assert(!FD1->getDescribedTemplate() && !FD2->getDescribedTemplate() &&
6166 "not for function templates");
6167 assert(!FD1->isFunctionTemplateSpecialization() ||
6168 isa<CXXConversionDecl>(FD1));
6169 assert(!FD2->isFunctionTemplateSpecialization() ||
6170 isa<CXXConversionDecl>(FD2));
6171
6172 FunctionDecl *F1 = FD1;
6174 F1 = P;
6175
6176 FunctionDecl *F2 = FD2;
6178 F2 = P;
6179
6181 F1->getAssociatedConstraints(AC1);
6182 F2->getAssociatedConstraints(AC2);
6183 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6184 if (IsAtLeastAsConstrained(F1, AC1, F2, AC2, AtLeastAsConstrained1))
6185 return nullptr;
6186 if (IsAtLeastAsConstrained(F2, AC2, F1, AC1, AtLeastAsConstrained2))
6187 return nullptr;
6188 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6189 return nullptr;
6190 return AtLeastAsConstrained1 ? FD1 : FD2;
6191}
6192
6193/// Determine whether one partial specialization, P1, is at least as
6194/// specialized than another, P2.
6195///
6196/// \tparam TemplateLikeDecl The kind of P2, which must be a
6197/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
6198/// \param T1 The injected-class-name of P1 (faked for a variable template).
6199/// \param T2 The injected-class-name of P2 (faked for a variable template).
6200template<typename TemplateLikeDecl>
6202 TemplateLikeDecl *P2,
6203 TemplateDeductionInfo &Info) {
6204 // C++ [temp.class.order]p1:
6205 // For two class template partial specializations, the first is at least as
6206 // specialized as the second if, given the following rewrite to two
6207 // function templates, the first function template is at least as
6208 // specialized as the second according to the ordering rules for function
6209 // templates (14.6.6.2):
6210 // - the first function template has the same template parameters as the
6211 // first partial specialization and has a single function parameter
6212 // whose type is a class template specialization with the template
6213 // arguments of the first partial specialization, and
6214 // - the second function template has the same template parameters as the
6215 // second partial specialization and has a single function parameter
6216 // whose type is a class template specialization with the template
6217 // arguments of the second partial specialization.
6218 //
6219 // Rather than synthesize function templates, we merely perform the
6220 // equivalent partial ordering by performing deduction directly on
6221 // the template arguments of the class template partial
6222 // specializations. This computation is slightly simpler than the
6223 // general problem of function template partial ordering, because
6224 // class template partial specializations are more constrained. We
6225 // know that every template parameter is deducible from the class
6226 // template partial specialization's template arguments, for
6227 // example.
6229
6230 // Determine whether P1 is at least as specialized as P2.
6231 Deduced.resize(P2->getTemplateParameters()->size());
6233 S, P2->getTemplateParameters(), T2, T1, Info, Deduced, TDF_None,
6234 PartialOrderingKind::Call, /*DeducedFromArrayBound=*/false,
6235 /*HasDeducedAnyParam=*/nullptr) != TemplateDeductionResult::Success)
6236 return false;
6237
6238 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
6239 Deduced.end());
6240 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
6241 Info);
6242 if (Inst.isInvalid())
6243 return false;
6244
6245 const auto *TST1 = cast<TemplateSpecializationType>(T1);
6246
6247 Sema::SFINAETrap Trap(S);
6248
6251 Result = ::FinishTemplateArgumentDeduction(
6252 S, P2, /*IsPartialOrdering=*/true, TST1->template_arguments(), Deduced,
6253 Info);
6254 });
6255
6257 return false;
6258
6259 if (Trap.hasErrorOccurred())
6260 return false;
6261
6262 return true;
6263}
6264
6265namespace {
6266// A dummy class to return nullptr instead of P2 when performing "more
6267// specialized than primary" check.
6268struct GetP2 {
6269 template <typename T1, typename T2,
6270 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6271 T2 *operator()(T1 *, T2 *P2) {
6272 return P2;
6273 }
6274 template <typename T1, typename T2,
6275 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6276 T1 *operator()(T1 *, T2 *) {
6277 return nullptr;
6278 }
6279};
6280
6281// The assumption is that two template argument lists have the same size.
6282struct TemplateArgumentListAreEqual {
6283 ASTContext &Ctx;
6284 TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
6285
6286 template <typename T1, typename T2,
6287 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6288 bool operator()(T1 *PS1, T2 *PS2) {
6289 ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
6290 Args2 = PS2->getTemplateArgs().asArray();
6291
6292 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6293 // We use profile, instead of structural comparison of the arguments,
6294 // because canonicalization can't do the right thing for dependent
6295 // expressions.
6296 llvm::FoldingSetNodeID IDA, IDB;
6297 Args1[I].Profile(IDA, Ctx);
6298 Args2[I].Profile(IDB, Ctx);
6299 if (IDA != IDB)
6300 return false;
6301 }
6302 return true;
6303 }
6304
6305 template <typename T1, typename T2,
6306 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6307 bool operator()(T1 *Spec, T2 *Primary) {
6308 ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
6309 Args2 = Primary->getInjectedTemplateArgs(Ctx);
6310
6311 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6312 // We use profile, instead of structural comparison of the arguments,
6313 // because canonicalization can't do the right thing for dependent
6314 // expressions.
6315 llvm::FoldingSetNodeID IDA, IDB;
6316 Args1[I].Profile(IDA, Ctx);
6317 // Unlike the specialization arguments, the injected arguments are not
6318 // always canonical.
6319 Ctx.getCanonicalTemplateArgument(Args2[I]).Profile(IDB, Ctx);
6320 if (IDA != IDB)
6321 return false;
6322 }
6323 return true;
6324 }
6325};
6326} // namespace
6327
6328/// Returns the more specialized template specialization between T1/P1 and
6329/// T2/P2.
6330/// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
6331/// specialization and T2/P2 is the primary template.
6332/// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
6333///
6334/// \param T1 the type of the first template partial specialization
6335///
6336/// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
6337/// template partial specialization; otherwise, the type of the
6338/// primary template.
6339///
6340/// \param P1 the first template partial specialization
6341///
6342/// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
6343/// partial specialization; otherwise, the primary template.
6344///
6345/// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
6346/// more specialized, returns nullptr if P1 is not more specialized.
6347/// - otherwise, returns the more specialized template partial
6348/// specialization. If neither partial specialization is more
6349/// specialized, returns NULL.
6350template <typename TemplateLikeDecl, typename PrimaryDel>
6351static TemplateLikeDecl *
6352getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
6353 PrimaryDel *P2, TemplateDeductionInfo &Info) {
6354 constexpr bool IsMoreSpecialThanPrimaryCheck =
6355 !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
6356
6357 bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, Info);
6358 if (IsMoreSpecialThanPrimaryCheck && !Better1)
6359 return nullptr;
6360
6361 bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1, Info);
6362 if (IsMoreSpecialThanPrimaryCheck && !Better2)
6363 return P1;
6364
6365 // C++ [temp.deduct.partial]p10:
6366 // F is more specialized than G if F is at least as specialized as G and G
6367 // is not at least as specialized as F.
6368 if (Better1 != Better2) // We have a clear winner
6369 return Better1 ? P1 : GetP2()(P1, P2);
6370
6371 if (!Better1 && !Better2)
6372 return nullptr;
6373
6374 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
6375 // there is no wording or even resolution for this issue.
6376 auto *TST1 = cast<TemplateSpecializationType>(T1);
6377 auto *TST2 = cast<TemplateSpecializationType>(T2);
6378 const TemplateArgument &TA1 = TST1->template_arguments().back();
6379 if (TA1.getKind() == TemplateArgument::Pack) {
6380 assert(TST1->template_arguments().size() ==
6381 TST2->template_arguments().size());
6382 const TemplateArgument &TA2 = TST2->template_arguments().back();
6383 assert(TA2.getKind() == TemplateArgument::Pack);
6384 unsigned PackSize1 = TA1.pack_size();
6385 unsigned PackSize2 = TA2.pack_size();
6386 bool IsPackExpansion1 =
6387 PackSize1 && TA1.pack_elements().back().isPackExpansion();
6388 bool IsPackExpansion2 =
6389 PackSize2 && TA2.pack_elements().back().isPackExpansion();
6390 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
6391 if (PackSize1 > PackSize2 && IsPackExpansion1)
6392 return GetP2()(P1, P2);
6393 if (PackSize1 < PackSize2 && IsPackExpansion2)
6394 return P1;
6395 }
6396 }
6397
6398 if (!S.Context.getLangOpts().CPlusPlus20)
6399 return nullptr;
6400
6401 // Match GCC on not implementing [temp.func.order]p6.2.1.
6402
6403 // C++20 [temp.func.order]p6:
6404 // If deduction against the other template succeeds for both transformed
6405 // templates, constraints can be considered as follows:
6406
6407 TemplateParameterList *TPL1 = P1->getTemplateParameters();
6408 TemplateParameterList *TPL2 = P2->getTemplateParameters();
6409 if (TPL1->size() != TPL2->size())
6410 return nullptr;
6411
6412 // C++20 [temp.func.order]p6.2.2:
6413 // Otherwise, if the corresponding template-parameters of the
6414 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6415 // function parameters that positionally correspond between the two
6416 // templates are not of the same type, neither template is more specialized
6417 // than the other.
6418 if (!S.TemplateParameterListsAreEqual(TPL1, TPL2, false,
6420 return nullptr;
6421
6422 if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
6423 return nullptr;
6424
6426 P1->getAssociatedConstraints(AC1);
6427 P2->getAssociatedConstraints(AC2);
6428 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6429 if (S.IsAtLeastAsConstrained(P1, AC1, P2, AC2, AtLeastAsConstrained1) ||
6430 (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
6431 return nullptr;
6432 if (S.IsAtLeastAsConstrained(P2, AC2, P1, AC1, AtLeastAsConstrained2))
6433 return nullptr;
6434 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6435 return nullptr;
6436 return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
6437}
6438
6446
6448 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6449}
6450
6453 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
6454 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
6455 QualType PartialT = Spec->getInjectedSpecializationType();
6456
6458 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6459 if (MaybeSpec)
6460 Info.clearSFINAEDiagnostic();
6461 return MaybeSpec;
6462}
6463
6468 // Pretend the variable template specializations are class template
6469 // specializations and form a fake injected class name type for comparison.
6470 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
6471 "the partial specializations being compared should specialize"
6472 " the same template.");
6475 Name, PS1->getTemplateArgs().asArray());
6477 Name, PS2->getTemplateArgs().asArray());
6478
6480 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6481}
6482
6485 VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
6486 TemplateName Name(Primary);
6488 Name, Primary->getInjectedTemplateArgs(Context));
6490 Name, Spec->getTemplateArgs().asArray());
6491
6493 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6494 if (MaybeSpec)
6495 Info.clearSFINAEDiagnostic();
6496 return MaybeSpec;
6497}
6498
6501 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
6502 bool PartialOrdering, bool *MatchedPackOnParmToNonPackOnArg) {
6503 // C++1z [temp.arg.template]p4: (DR 150)
6504 // A template template-parameter P is at least as specialized as a
6505 // template template-argument A if, given the following rewrite to two
6506 // function templates...
6507
6508 // Rather than synthesize function templates, we merely perform the
6509 // equivalent partial ordering by performing deduction directly on
6510 // the template parameter lists of the template template parameters.
6511 //
6513
6516 SourceRange(P->getTemplateLoc(), P->getRAngleLoc()));
6517 if (Inst.isInvalid())
6518 return false;
6519
6520 // Given an invented class template X with the template parameter list of
6521 // A (including default arguments):
6522 // - Each function template has a single function parameter whose type is
6523 // a specialization of X with template arguments corresponding to the
6524 // template parameters from the respective function template
6526
6527 // Check P's arguments against A's parameter list. This will fill in default
6528 // template arguments as needed. AArgs are already correct by construction.
6529 // We can't just use CheckTemplateIdType because that will expand alias
6530 // templates.
6531 SmallVector<TemplateArgument, 4> PArgs(P->getInjectedTemplateArgs(Context));
6532 {
6533 TemplateArgumentListInfo PArgList(P->getLAngleLoc(),
6534 P->getRAngleLoc());
6535 for (unsigned I = 0, N = P->size(); I != N; ++I) {
6536 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
6537 // expansions, to form an "as written" argument list.
6538 TemplateArgument Arg = PArgs[I];
6539 if (Arg.getKind() == TemplateArgument::Pack) {
6540 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
6541 Arg = *Arg.pack_begin();
6542 }
6544 Arg, QualType(), P->getParam(I)->getLocation()));
6545 }
6546 PArgs.clear();
6547
6548 // C++1z [temp.arg.template]p3:
6549 // If the rewrite produces an invalid type, then P is not at least as
6550 // specialized as A.
6552 /*PartialOrdering=*/false, /*MatchingTTP=*/true);
6553 CTAI.SugaredConverted = std::move(PArgs);
6554 if (CheckTemplateArgumentList(AArg, ArgLoc, PArgList, DefaultArgs,
6555 /*PartialTemplateArgs=*/false, CTAI,
6556 /*UpdateArgsWithConversions=*/true,
6557 /*ConstraintsNotSatisfied=*/nullptr))
6558 return false;
6559 PArgs = std::move(CTAI.SugaredConverted);
6560 if (MatchedPackOnParmToNonPackOnArg)
6561 *MatchedPackOnParmToNonPackOnArg |= CTAI.MatchedPackOnParmToNonPackOnArg;
6562 }
6563
6564 // Determine whether P1 is at least as specialized as P2.
6565 TemplateDeductionInfo Info(ArgLoc, A->getDepth());
6567 Deduced.resize(A->size());
6568
6569 // ... the function template corresponding to P is at least as specialized
6570 // as the function template corresponding to A according to the partial
6571 // ordering rules for function templates.
6572
6573 // Provisional resolution for CWG2398: Regarding temp.arg.template]p4, when
6574 // applying the partial ordering rules for function templates on
6575 // the rewritten template template parameters:
6576 // - In a deduced context, the matching of packs versus fixed-size needs to
6577 // be inverted between Ps and As. On non-deduced context, matching needs to
6578 // happen both ways, according to [temp.arg.template]p3, but this is
6579 // currently implemented as a special case elsewhere.
6581 *this, A, AArgs, PArgs, Info, Deduced,
6582 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/true,
6583 PartialOrdering ? PackFold::ArgumentToParameter : PackFold::Both,
6584 /*HasDeducedAnyParam=*/nullptr)) {
6586 if (MatchedPackOnParmToNonPackOnArg &&
6588 *MatchedPackOnParmToNonPackOnArg = true;
6589 break;
6590
6592 Diag(AArg->getLocation(), diag::err_template_param_list_different_arity)
6593 << (A->size() > P->size()) << /*isTemplateTemplateParameter=*/true
6594 << SourceRange(A->getTemplateLoc(), P->getRAngleLoc());
6595 return false;
6597 Diag(AArg->getLocation(), diag::err_non_deduced_mismatch)
6598 << Info.FirstArg << Info.SecondArg;
6599 return false;
6602 diag::err_inconsistent_deduction)
6603 << Info.FirstArg << Info.SecondArg;
6604 return false;
6606 return false;
6607
6608 // None of these should happen for a plain deduction.
6623 llvm_unreachable("Unexpected Result");
6624 }
6625
6626 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
6627
6630 TDK = ::FinishTemplateArgumentDeduction(
6631 *this, AArg, /*IsPartialOrdering=*/true, PArgs, Deduced, Info);
6632 });
6633 switch (TDK) {
6635 return true;
6636
6637 // It doesn't seem possible to get a non-deduced mismatch when partial
6638 // ordering TTPs.
6640 llvm_unreachable("Unexpected NonDeducedMismatch");
6641
6642 // Substitution failures should have already been diagnosed.
6646 return false;
6647
6648 // None of these should happen when just converting deduced arguments.
6663 llvm_unreachable("Unexpected Result");
6664 }
6665 llvm_unreachable("Unexpected TDK");
6666}
6667
6668namespace {
6669struct MarkUsedTemplateParameterVisitor : DynamicRecursiveASTVisitor {
6670 llvm::SmallBitVector &Used;
6671 unsigned Depth;
6672
6673 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used,
6674 unsigned Depth)
6675 : Used(Used), Depth(Depth) { }
6676
6677 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
6678 if (T->getDepth() == Depth)
6679 Used[T->getIndex()] = true;
6680 return true;
6681 }
6682
6683 bool TraverseTemplateName(TemplateName Template) override {
6684 if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
6685 Template.getAsTemplateDecl()))
6686 if (TTP->getDepth() == Depth)
6687 Used[TTP->getIndex()] = true;
6689 return true;
6690 }
6691
6692 bool VisitDeclRefExpr(DeclRefExpr *E) override {
6693 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
6694 if (NTTP->getDepth() == Depth)
6695 Used[NTTP->getIndex()] = true;
6696 return true;
6697 }
6698};
6699}
6700
6701/// Mark the template parameters that are used by the given
6702/// expression.
6703static void
6705 const Expr *E,
6706 bool OnlyDeduced,
6707 unsigned Depth,
6708 llvm::SmallBitVector &Used) {
6709 if (!OnlyDeduced) {
6710 MarkUsedTemplateParameterVisitor(Used, Depth)
6711 .TraverseStmt(const_cast<Expr *>(E));
6712 return;
6713 }
6714
6715 // We can deduce from a pack expansion.
6716 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
6717 E = Expansion->getPattern();
6718
6720 if (!NTTP)
6721 return;
6722
6723 if (NTTP->getDepth() == Depth)
6724 Used[NTTP->getIndex()] = true;
6725
6726 // In C++17 mode, additional arguments may be deduced from the type of a
6727 // non-type argument.
6728 if (Ctx.getLangOpts().CPlusPlus17)
6729 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
6730}
6731
6732/// Mark the template parameters that are used by the given
6733/// nested name specifier.
6734static void
6737 bool OnlyDeduced,
6738 unsigned Depth,
6739 llvm::SmallBitVector &Used) {
6740 if (!NNS)
6741 return;
6742
6743 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
6744 Used);
6746 OnlyDeduced, Depth, Used);
6747}
6748
6749/// Mark the template parameters that are used by the given
6750/// template name.
6751static void
6753 TemplateName Name,
6754 bool OnlyDeduced,
6755 unsigned Depth,
6756 llvm::SmallBitVector &Used) {
6757 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
6759 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
6760 if (TTP->getDepth() == Depth)
6761 Used[TTP->getIndex()] = true;
6762 }
6763 return;
6764 }
6765
6766 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
6767 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
6768 Depth, Used);
6769 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
6770 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
6771 Depth, Used);
6772}
6773
6774/// Mark the template parameters that are used by the given
6775/// type.
6776static void
6778 bool OnlyDeduced,
6779 unsigned Depth,
6780 llvm::SmallBitVector &Used) {
6781 if (T.isNull())
6782 return;
6783
6784 // Non-dependent types have nothing deducible
6785 if (!T->isDependentType())
6786 return;
6787
6788 T = Ctx.getCanonicalType(T);
6789 switch (T->getTypeClass()) {
6790 case Type::Pointer:
6792 cast<PointerType>(T)->getPointeeType(),
6793 OnlyDeduced,
6794 Depth,
6795 Used);
6796 break;
6797
6798 case Type::BlockPointer:
6800 cast<BlockPointerType>(T)->getPointeeType(),
6801 OnlyDeduced,
6802 Depth,
6803 Used);
6804 break;
6805
6806 case Type::LValueReference:
6807 case Type::RValueReference:
6809 cast<ReferenceType>(T)->getPointeeType(),
6810 OnlyDeduced,
6811 Depth,
6812 Used);
6813 break;
6814
6815 case Type::MemberPointer: {
6816 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
6817 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
6818 Depth, Used);
6819 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
6820 OnlyDeduced, Depth, Used);
6821 break;
6822 }
6823
6824 case Type::DependentSizedArray:
6826 cast<DependentSizedArrayType>(T)->getSizeExpr(),
6827 OnlyDeduced, Depth, Used);
6828 // Fall through to check the element type
6829 [[fallthrough]];
6830
6831 case Type::ConstantArray:
6832 case Type::IncompleteArray:
6833 case Type::ArrayParameter:
6835 cast<ArrayType>(T)->getElementType(),
6836 OnlyDeduced, Depth, Used);
6837 break;
6838 case Type::Vector:
6839 case Type::ExtVector:
6841 cast<VectorType>(T)->getElementType(),
6842 OnlyDeduced, Depth, Used);
6843 break;
6844
6845 case Type::DependentVector: {
6846 const auto *VecType = cast<DependentVectorType>(T);
6847 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6848 Depth, Used);
6849 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
6850 Used);
6851 break;
6852 }
6853 case Type::DependentSizedExtVector: {
6854 const DependentSizedExtVectorType *VecType
6855 = cast<DependentSizedExtVectorType>(T);
6856 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6857 Depth, Used);
6858 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
6859 Depth, Used);
6860 break;
6861 }
6862
6863 case Type::DependentAddressSpace: {
6864 const DependentAddressSpaceType *DependentASType =
6865 cast<DependentAddressSpaceType>(T);
6866 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
6867 OnlyDeduced, Depth, Used);
6869 DependentASType->getAddrSpaceExpr(),
6870 OnlyDeduced, Depth, Used);
6871 break;
6872 }
6873
6874 case Type::ConstantMatrix: {
6875 const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T);
6876 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6877 Depth, Used);
6878 break;
6879 }
6880
6881 case Type::DependentSizedMatrix: {
6882 const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(T);
6883 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6884 Depth, Used);
6885 MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
6886 Used);
6887 MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
6888 Depth, Used);
6889 break;
6890 }
6891
6892 case Type::FunctionProto: {
6893 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
6894 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
6895 Used);
6896 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
6897 // C++17 [temp.deduct.type]p5:
6898 // The non-deduced contexts are: [...]
6899 // -- A function parameter pack that does not occur at the end of the
6900 // parameter-declaration-list.
6901 if (!OnlyDeduced || I + 1 == N ||
6902 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
6903 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
6904 Depth, Used);
6905 } else {
6906 // FIXME: C++17 [temp.deduct.call]p1:
6907 // When a function parameter pack appears in a non-deduced context,
6908 // the type of that pack is never deduced.
6909 //
6910 // We should also track a set of "never deduced" parameters, and
6911 // subtract that from the list of deduced parameters after marking.
6912 }
6913 }
6914 if (auto *E = Proto->getNoexceptExpr())
6915 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
6916 break;
6917 }
6918
6919 case Type::TemplateTypeParm: {
6920 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
6921 if (TTP->getDepth() == Depth)
6922 Used[TTP->getIndex()] = true;
6923 break;
6924 }
6925
6926 case Type::SubstTemplateTypeParmPack: {
6928 = cast<SubstTemplateTypeParmPackType>(T);
6929 if (Subst->getReplacedParameter()->getDepth() == Depth)
6930 Used[Subst->getIndex()] = true;
6932 OnlyDeduced, Depth, Used);
6933 break;
6934 }
6935
6936 case Type::InjectedClassName:
6937 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
6938 [[fallthrough]];
6939
6940 case Type::TemplateSpecialization: {
6941 const TemplateSpecializationType *Spec
6942 = cast<TemplateSpecializationType>(T);
6943 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
6944 Depth, Used);
6945
6946 // C++0x [temp.deduct.type]p9:
6947 // If the template argument list of P contains a pack expansion that is
6948 // not the last template argument, the entire template argument list is a
6949 // non-deduced context.
6950 if (OnlyDeduced &&
6952 break;
6953
6954 for (const auto &Arg : Spec->template_arguments())
6955 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6956 break;
6957 }
6958
6959 case Type::Complex:
6960 if (!OnlyDeduced)
6962 cast<ComplexType>(T)->getElementType(),
6963 OnlyDeduced, Depth, Used);
6964 break;
6965
6966 case Type::Atomic:
6967 if (!OnlyDeduced)
6969 cast<AtomicType>(T)->getValueType(),
6970 OnlyDeduced, Depth, Used);
6971 break;
6972
6973 case Type::DependentName:
6974 if (!OnlyDeduced)
6976 cast<DependentNameType>(T)->getQualifier(),
6977 OnlyDeduced, Depth, Used);
6978 break;
6979
6980 case Type::DependentTemplateSpecialization: {
6981 // C++14 [temp.deduct.type]p5:
6982 // The non-deduced contexts are:
6983 // -- The nested-name-specifier of a type that was specified using a
6984 // qualified-id
6985 //
6986 // C++14 [temp.deduct.type]p6:
6987 // When a type name is specified in a way that includes a non-deduced
6988 // context, all of the types that comprise that type name are also
6989 // non-deduced.
6990 if (OnlyDeduced)
6991 break;
6992
6994 = cast<DependentTemplateSpecializationType>(T);
6995
6997 OnlyDeduced, Depth, Used);
6998
6999 for (const auto &Arg : Spec->template_arguments())
7000 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
7001 break;
7002 }
7003
7004 case Type::TypeOf:
7005 if (!OnlyDeduced)
7006 MarkUsedTemplateParameters(Ctx, cast<TypeOfType>(T)->getUnmodifiedType(),
7007 OnlyDeduced, Depth, Used);
7008 break;
7009
7010 case Type::TypeOfExpr:
7011 if (!OnlyDeduced)
7013 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
7014 OnlyDeduced, Depth, Used);
7015 break;
7016
7017 case Type::Decltype:
7018 if (!OnlyDeduced)
7020 cast<DecltypeType>(T)->getUnderlyingExpr(),
7021 OnlyDeduced, Depth, Used);
7022 break;
7023
7024 case Type::PackIndexing:
7025 if (!OnlyDeduced) {
7026 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getPattern(),
7027 OnlyDeduced, Depth, Used);
7028 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getIndexExpr(),
7029 OnlyDeduced, Depth, Used);
7030 }
7031 break;
7032
7033 case Type::UnaryTransform:
7034 if (!OnlyDeduced)
7036 cast<UnaryTransformType>(T)->getUnderlyingType(),
7037 OnlyDeduced, Depth, Used);
7038 break;
7039
7040 case Type::PackExpansion:
7042 cast<PackExpansionType>(T)->getPattern(),
7043 OnlyDeduced, Depth, Used);
7044 break;
7045
7046 case Type::Auto:
7047 case Type::DeducedTemplateSpecialization:
7049 cast<DeducedType>(T)->getDeducedType(),
7050 OnlyDeduced, Depth, Used);
7051 break;
7052 case Type::DependentBitInt:
7054 cast<DependentBitIntType>(T)->getNumBitsExpr(),
7055 OnlyDeduced, Depth, Used);
7056 break;
7057
7058 case Type::HLSLAttributedResource:
7060 Ctx, cast<HLSLAttributedResourceType>(T)->getWrappedType(), OnlyDeduced,
7061 Depth, Used);
7062 if (cast<HLSLAttributedResourceType>(T)->hasContainedType())
7064 Ctx, cast<HLSLAttributedResourceType>(T)->getContainedType(),
7065 OnlyDeduced, Depth, Used);
7066 break;
7067
7068 // None of these types have any template parameters in them.
7069 case Type::Builtin:
7070 case Type::VariableArray:
7071 case Type::FunctionNoProto:
7072 case Type::Record:
7073 case Type::Enum:
7074 case Type::ObjCInterface:
7075 case Type::ObjCObject:
7076 case Type::ObjCObjectPointer:
7077 case Type::UnresolvedUsing:
7078 case Type::Pipe:
7079 case Type::BitInt:
7080#define TYPE(Class, Base)
7081#define ABSTRACT_TYPE(Class, Base)
7082#define DEPENDENT_TYPE(Class, Base)
7083#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7084#include "clang/AST/TypeNodes.inc"
7085 break;
7086 }
7087}
7088
7089/// Mark the template parameters that are used by this
7090/// template argument.
7091static void
7094 bool OnlyDeduced,
7095 unsigned Depth,
7096 llvm::SmallBitVector &Used) {
7097 switch (TemplateArg.getKind()) {
7103 break;
7104
7106 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
7107 Depth, Used);
7108 break;
7109
7113 TemplateArg.getAsTemplateOrTemplatePattern(),
7114 OnlyDeduced, Depth, Used);
7115 break;
7116
7118 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
7119 Depth, Used);
7120 break;
7121
7123 for (const auto &P : TemplateArg.pack_elements())
7124 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
7125 break;
7126 }
7127}
7128
7129void
7130Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
7131 unsigned Depth,
7132 llvm::SmallBitVector &Used) {
7133 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
7134}
7135
7136void
7138 bool OnlyDeduced, unsigned Depth,
7139 llvm::SmallBitVector &Used) {
7140 // C++0x [temp.deduct.type]p9:
7141 // If the template argument list of P contains a pack expansion that is not
7142 // the last template argument, the entire template argument list is a
7143 // non-deduced context.
7144 if (OnlyDeduced &&
7145 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
7146 return;
7147
7148 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7149 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
7150 Depth, Used);
7151}
7152
7154 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
7155 llvm::SmallBitVector &Deduced) {
7156 TemplateParameterList *TemplateParams
7157 = FunctionTemplate->getTemplateParameters();
7158 Deduced.clear();
7159 Deduced.resize(TemplateParams->size());
7160
7161 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
7162 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
7163 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
7164 true, TemplateParams->getDepth(), Deduced);
7165}
7166
7168 FunctionTemplateDecl *FunctionTemplate,
7169 QualType T) {
7170 if (!T->isDependentType())
7171 return false;
7172
7173 TemplateParameterList *TemplateParams
7174 = FunctionTemplate->getTemplateParameters();
7175 llvm::SmallBitVector Deduced(TemplateParams->size());
7176 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
7177 Deduced);
7178
7179 return Deduced.any();
7180}
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:1181
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 bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template, TemplateDeductionInfo &Info, bool IsDeduced, Sema::CheckTemplateArgumentInfo &CTAI)
Convert the given deduced template argument and add it to the set of fully-converted template argumen...
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 ConvertDeducedTemplateArguments(Sema &S, TemplateDeclT *Template, bool IsDeduced, SmallVectorImpl< DeducedTemplateArgument > &Deduced, TemplateDeductionInfo &Info, Sema::CheckTemplateArgumentInfo &CTAI, LocalInstantiationScope *CurrentInstantiationScope, unsigned NumAlreadyConverted, bool *IsIncomplete)
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 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...
PackFold
What directions packs are allowed to match non-packs.
@ 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)
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:2922
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:2723
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2739
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:2928
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:2296
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:2770
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:2489
CanQualType UnsignedIntTy
Definition: ASTContext.h:1170
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false)
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1681
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y, bool IgnoreDeduced=false) const
Determine whether the given template names refer to the same template.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
TemplateName getDeducedTemplateName(TemplateName Underlying, DefaultArguments DefaultArgs) const
Represents a TemplateName which had some of its default arguments deduced.
const DependentSizedArrayType * getAsDependentSizedArrayType(QualType T) const
Definition: ASTContext.h:2931
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:6562
ArrayRef< TemplateArgument > getTypeConstraintArguments() const
Definition: Type.h:6572
bool isDecltypeAuto() const
Definition: Type.h:6585
ConceptDecl * getTypeConstraintConcept() const
Definition: Type.h:6577
AutoTypeKeyword getKeyword() const
Definition: Type.h:6593
bool isConstrained() const
Definition: Type.h:6581
A fixed int type of a specified bitwidth.
Definition: Type.h:7820
Pointer to a block type.
Definition: Type.h:3409
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2924
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2964
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2117
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:2594
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2293
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2278
bool isStatic() const
Definition: DeclCXX.cpp:2325
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:1700
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:3146
Declaration of a C++20 concept.
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:422
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4233
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4254
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4251
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:1439
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2106
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:266
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:247
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:237
DeclContext * getDeclContext()
Definition: DeclBase.h:451
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:971
Kind getKind() const
Definition: DeclBase.h:445
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:6629
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6528
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3921
Expr * getAddrSpaceExpr() const
Definition: Type.h:3932
QualType getPointeeType() const
Definition: Type.h:3933
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3961
QualType getElementType() const
Definition: Type.h:3976
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4292
Expr * getColumnExpr() const
Definition: Type.h:4305
Expr * getRowExpr() const
Definition: Type.h:4304
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:7082
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:7101
NestedNameSpecifier * getQualifier() const
Definition: Type.h:7098
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4087
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:6949
RAII object that enters a new expression evaluation context.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1912
bool isInvalid() const
Determine if the explicit specifier is invalid.
Definition: DeclCXX.h:1941
const Expr * getExpr() const
Definition: DeclCXX.h:1921
The return type of classify().
Definition: Expr.h:330
bool isLValue() const
Definition: Expr.h:380
This represents one expression.
Definition: Expr.h:110
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:276
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:405
QualType getType() const
Definition: Expr.h:142
ExtVectorType - Extended vector type.
Definition: Type.h:4127
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:2679
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4076
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4064
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3753
QualType getReturnType() const
Definition: Decl.h:2727
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2656
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:4135
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4200
bool isImmediateEscalating() const
Definition: Decl.cpp:3272
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:4001
void getAssociatedConstraints(SmallVectorImpl< const Expr * > &AC) const
Get the associated-constraints of this function declaration.
Definition: Decl.h:2634
size_t param_size() const
Definition: Decl.h:2672
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5108
param_type_iterator param_type_begin() const
Definition: Type.h:5521
const ExtParameterInfo * getExtParameterInfosOrNull() const
Return a pointer to the beginning of the array of extra parameter information, if present,...
Definition: Type.h:5559
unsigned getNumParams() const
Definition: Type.h:5361
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: Type.h:5501
Qualifiers getMethodQuals() const
Definition: Type.h:5503
QualType getParamType(unsigned i) const
Definition: Type.h:5363
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5394
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5485
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5372
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:5446
param_type_iterator param_type_end() const
Definition: Type.h:5525
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5368
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition: Type.h:5511
Declaration of a template function.
Definition: DeclTemplate.h:958
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4322
QualType getReturnType() const
Definition: Type.h:4649
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:515
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:6799
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3484
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...
NamedDecl * getPartiallySubstitutedPack(const TemplateArgument **ExplicitArgs=nullptr, unsigned *NumExplicitArgs=nullptr) const
Retrieve the partially-substitued template parameter pack.
void ResetPartiallySubstitutedPack()
Reset the partially-substituted pack when it is no longer of interest.
Definition: Template.h:547
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: Type.h:4197
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4211
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3520
QualType getPointeeType() const
Definition: Type.h:3536
const Type * getClass() const
Definition: Type.h:3550
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:7586
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:7147
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:7168
std::optional< unsigned > getNumExpansions() const
Retrieve the number of expansions that this pack expansion will generate, if known.
Definition: Type.h:7172
bool hasSelectedType() const
Definition: Type.h:5960
QualType getSelectedType() const
Definition: Type.h:5953
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:3199
QualType getPointeeType() const
Definition: Type.h:3209
A (possibly-)qualified type.
Definition: Type.h:929
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8026
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:7937
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8063
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7977
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:8140
QualType getCanonicalType() const
Definition: Type.h:7989
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8031
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:8058
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7983
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:3502
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6078
ArrayRef< TemplateArgument > getInjectedTemplateArgs(const ASTContext &Context) const
Retrieve the "injected" template arguments that correspond to the template parameters of this templat...
Definition: DeclTemplate.h:921
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3440
QualType getPointeeType() const
Definition: Type.h:3458
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:13243
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8062
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3013
A helper class for building up ExtParameterInfos.
Definition: Sema.h:12646
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:12665
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12116
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12146
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:466
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:12675
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:1073
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:6463
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg, const DefaultArguments &DefaultArgs, SourceLocation ArgLoc, bool PartialOrdering, bool *MatchedPackOnParmToNonPackOnArg)
@ CTAK_DeducedFromArrayBound
The template argument was deduced from an array bound via template argument deduction.
Definition: Sema.h:11664
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:11656
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition: Sema.h:11660
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition: Sema.h:911
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
Definition: SemaType.cpp:2633
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
ASTContext & getASTContext() const
Definition: Sema.h:534
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:692
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:819
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:11850
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, CheckTemplateArgumentInfo &CTAI, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
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:527
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:14426
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.
TemplateDeductionResult FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl< OriginalCallArg > const *OriginalCallArgs, bool PartialOverloading, bool PartialOrdering, llvm::function_ref< bool()> CheckNonDependent=[] { return false;})
Finish template argument deduction for a function template, checking the deduced template arguments f...
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:1046
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:12179
QualType getDecltypeForExpr(Expr *E)
getDecltypeForExpr - Given an expr, will return the decltype for that expression, according to the ru...
Definition: SemaType.cpp:9632
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20995
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:14989
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),...
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:9095
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)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:564
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
Definition: SemaType.cpp:8180
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition: Sema.h:12519
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:6470
TemplateArgument getArgumentPack() const
Definition: Type.cpp:4305
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
Definition: Type.h:6496
const TemplateTypeParmDecl * getReplacedParameter() const
Gets the template parameter declaration that was substituted for.
Definition: Type.cpp:4297
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:398
bool isTypeAlias() const
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: DeclTemplate.h:442
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:417
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
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:205
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:6667
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6735
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6733
QualType desugar() const
Definition: Type.h:6744
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:759
unsigned getIndex() const
Definition: Type.h:6349
unsigned getDepth() const
Definition: Type.h:6348
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
const Type * getTypeForDecl() const
Definition: Decl.h:3416
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:7908
SourceLocation getNameLoc() const
Definition: TypeLoc.h:536
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:540
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:8516
bool isIncompleteArrayType() const
Definition: Type.h:8272
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:8492
bool isRValueReferenceType() const
Definition: Type.h:8218
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8678
bool isArrayType() const
Definition: Type.h:8264
bool isFunctionPointerType() const
Definition: Type.h:8232
bool isPointerType() const
Definition: Type.h:8192
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8810
bool isReferenceType() const
Definition: Type.h:8210
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:2812
bool isLValueReferenceType() const
Definition: Type.h:8214
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2707
QualType getCanonicalTypeInternal() const
Definition: Type.h:2990
bool isMemberPointerType() const
Definition: Type.h:8246
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:5046
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8654
bool isFunctionType() const
Definition: Type.h:8188
bool isObjCObjectPointerType() const
Definition: Type.h:8334
bool isMemberFunctionPointerType() const
Definition: Type.h:8250
bool isAnyPointerType() const
Definition: Type.h:8200
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:8741
bool isRecordType() const
Definition: Type.h:8292
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:886
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1526
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:4035
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.
__inline void unsigned int _2
Definition: larchintrin.h:181
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:78
@ 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
NamedDecl * getAsNamedDecl(TemplateParameter P)
unsigned toTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:82
@ 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:69
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:1278
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:367
@ 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.
@ CUDATargetMismatch
CUDA Target attributes do not match.
@ 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
@ None
The alignment was not explicit in code.
@ 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:5165
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5167
Extra information about a function prototype.
Definition: Type.h:5193
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:5201
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5194
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition: Sema.h:11687
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition: Sema.h:11680
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition: Sema.h:11677
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition: Sema.h:11677
bool MatchedPackOnParmToNonPackOnArg
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition: Sema.h:11691
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition: Sema.h:12713
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:12720
A stack object to be created when performing template instantiation.
Definition: Sema.h:12880
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:13040
brief A function argument from which we performed template argument
Definition: Sema.h:12279
Location information for a TemplateArgument.
Definition: TemplateBase.h:472