clang 20.0.0git
SemaTemplateDeduction.cpp
Go to the documentation of this file.
1//===- SemaTemplateDeduction.cpp - Template Argument Deduction ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TreeTransform.h"
14#include "TypeLocBuilder.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
29#include "clang/AST/Type.h"
30#include "clang/AST/TypeLoc.h"
35#include "clang/Basic/LLVM.h"
42#include "clang/Sema/Sema.h"
43#include "clang/Sema/Template.h"
45#include "llvm/ADT/APInt.h"
46#include "llvm/ADT/APSInt.h"
47#include "llvm/ADT/ArrayRef.h"
48#include "llvm/ADT/DenseMap.h"
49#include "llvm/ADT/FoldingSet.h"
50#include "llvm/ADT/SmallBitVector.h"
51#include "llvm/ADT/SmallPtrSet.h"
52#include "llvm/ADT/SmallVector.h"
53#include "llvm/Support/Casting.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/Support/ErrorHandling.h"
56#include <algorithm>
57#include <cassert>
58#include <optional>
59#include <tuple>
60#include <type_traits>
61#include <utility>
62
63namespace clang {
64
65 /// Various flags that control template argument deduction.
66 ///
67 /// These flags can be bitwise-OR'd together.
69 /// No template argument deduction flags, which indicates the
70 /// strictest results for template argument deduction (as used for, e.g.,
71 /// matching class template partial specializations).
73
74 /// Within template argument deduction from a function call, we are
75 /// matching with a parameter type for which the original parameter was
76 /// a reference.
78
79 /// Within template argument deduction from a function call, we
80 /// are matching in a case where we ignore cv-qualifiers.
82
83 /// Within template argument deduction from a function call,
84 /// we are matching in a case where we can perform template argument
85 /// deduction from a template-id of a derived class of the argument type.
87
88 /// Allow non-dependent types to differ, e.g., when performing
89 /// template argument deduction from a function call where conversions
90 /// may apply.
92
93 /// Whether we are performing template argument deduction for
94 /// parameters and arguments in a top-level template argument
96
97 /// Within template argument deduction from overload resolution per
98 /// C++ [over.over] allow matching function types that are compatible in
99 /// terms of noreturn and default calling convention adjustments, or
100 /// similarly matching a declared template specialization against a
101 /// possible template, per C++ [temp.deduct.decl]. In either case, permit
102 /// deduction where the parameter is a function type that can be converted
103 /// to the argument type.
105
106 /// Within template argument deduction for a conversion function, we are
107 /// matching with an argument type for which the original argument was
108 /// a reference.
110 };
111}
112
113using namespace clang;
114using namespace sema;
115
116/// Compare two APSInts, extending and switching the sign as
117/// necessary to compare their values regardless of underlying type.
118static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
119 if (Y.getBitWidth() > X.getBitWidth())
120 X = X.extend(Y.getBitWidth());
121 else if (Y.getBitWidth() < X.getBitWidth())
122 Y = Y.extend(X.getBitWidth());
123
124 // If there is a signedness mismatch, correct it.
125 if (X.isSigned() != Y.isSigned()) {
126 // If the signed value is negative, then the values cannot be the same.
127 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
128 return false;
129
130 Y.setIsSigned(true);
131 X.setIsSigned(true);
132 }
133
134 return X == Y;
135}
136
137/// The kind of PartialOrdering we're performing template argument deduction
138/// for (C++11 [temp.deduct.partial]).
140
142 Sema &S, TemplateParameterList *TemplateParams, QualType Param,
144 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
145 PartialOrderingKind POK, bool DeducedFromArrayBound,
146 bool *HasDeducedAnyParam);
147
148/// What directions packs are allowed to match non-packs.
150
157 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
158 PackFold PackFold, bool *HasDeducedAnyParam);
159
162 bool OnlyDeduced, unsigned Depth,
163 llvm::SmallBitVector &Used);
164
166 bool OnlyDeduced, unsigned Level,
167 llvm::SmallBitVector &Deduced);
168
169/// If the given expression is of a form that permits the deduction
170/// of a non-type template parameter, return the declaration of that
171/// non-type template parameter.
172static const NonTypeTemplateParmDecl *
173getDeducedParameterFromExpr(const Expr *E, unsigned Depth) {
174 // If we are within an alias template, the expression may have undergone
175 // any number of parameter substitutions already.
176 while (true) {
177 if (const auto *IC = dyn_cast<ImplicitCastExpr>(E))
178 E = IC->getSubExpr();
179 else if (const auto *CE = dyn_cast<ConstantExpr>(E))
180 E = CE->getSubExpr();
181 else if (const auto *Subst = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
182 E = Subst->getReplacement();
183 else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) {
184 // Look through implicit copy construction from an lvalue of the same type.
185 if (CCE->getParenOrBraceRange().isValid())
186 break;
187 // Note, there could be default arguments.
188 assert(CCE->getNumArgs() >= 1 && "implicit construct expr should have 1 arg");
189 E = CCE->getArg(0);
190 } else
191 break;
192 }
193
194 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
195 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
196 if (NTTP->getDepth() == Depth)
197 return NTTP;
198
199 return nullptr;
200}
201
202static const NonTypeTemplateParmDecl *
205}
206
207/// Determine whether two declaration pointers refer to the same
208/// declaration.
209static bool isSameDeclaration(Decl *X, Decl *Y) {
210 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
211 X = NX->getUnderlyingDecl();
212 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
213 Y = NY->getUnderlyingDecl();
214
215 return X->getCanonicalDecl() == Y->getCanonicalDecl();
216}
217
218/// Verify that the given, deduced template arguments are compatible.
219///
220/// \returns The deduced template argument, or a NULL template argument if
221/// the deduced template arguments were incompatible.
226 bool AggregateCandidateDeduction = false) {
227 // We have no deduction for one or both of the arguments; they're compatible.
228 if (X.isNull())
229 return Y;
230 if (Y.isNull())
231 return X;
232
233 // If we have two non-type template argument values deduced for the same
234 // parameter, they must both match the type of the parameter, and thus must
235 // match each other's type. As we're only keeping one of them, we must check
236 // for that now. The exception is that if either was deduced from an array
237 // bound, the type is permitted to differ.
238 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
239 QualType XType = X.getNonTypeTemplateArgumentType();
240 if (!XType.isNull()) {
242 if (YType.isNull() || !Context.hasSameType(XType, YType))
244 }
245 }
246
247 switch (X.getKind()) {
249 llvm_unreachable("Non-deduced template arguments handled above");
250
252 // If two template type arguments have the same type, they're compatible.
253 QualType TX = X.getAsType(), TY = Y.getAsType();
254 if (Y.getKind() == TemplateArgument::Type && Context.hasSameType(TX, TY))
255 return DeducedTemplateArgument(Context.getCommonSugaredType(TX, TY),
256 X.wasDeducedFromArrayBound() ||
258
259 // If one of the two arguments was deduced from an array bound, the other
260 // supersedes it.
261 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
262 return X.wasDeducedFromArrayBound() ? Y : X;
263
264 // The arguments are not compatible.
266 }
267
269 // If we deduced a constant in one case and either a dependent expression or
270 // declaration in another case, keep the integral constant.
271 // If both are integral constants with the same value, keep that value.
275 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
276 return X.wasDeducedFromArrayBound() ? Y : X;
277
278 // All other combinations are incompatible.
280
282 // If we deduced a value and a dependent expression, keep the value.
285 X.structurallyEquals(Y)))
286 return X;
287
288 // All other combinations are incompatible.
290
293 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
294 return X;
295
296 // All other combinations are incompatible.
298
301 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
303 return X;
304
305 // All other combinations are incompatible.
307
310 return checkDeducedTemplateArguments(Context, Y, X);
311
312 // Compare the expressions for equality
313 llvm::FoldingSetNodeID ID1, ID2;
314 X.getAsExpr()->Profile(ID1, Context, true);
315 Y.getAsExpr()->Profile(ID2, Context, true);
316 if (ID1 == ID2)
317 return X.wasDeducedFromArrayBound() ? Y : X;
318
319 // Differing dependent expressions are incompatible.
321 }
322
324 assert(!X.wasDeducedFromArrayBound());
325
326 // If we deduced a declaration and a dependent expression, keep the
327 // declaration.
329 return X;
330
331 // If we deduced a declaration and an integral constant, keep the
332 // integral constant and whichever type did not come from an array
333 // bound.
336 return TemplateArgument(Context, Y.getAsIntegral(),
337 X.getParamTypeForDecl());
338 return Y;
339 }
340
341 // If we deduced two declarations, make sure that they refer to the
342 // same declaration.
344 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
345 return X;
346
347 // All other combinations are incompatible.
349
351 // If we deduced a null pointer and a dependent expression, keep the
352 // null pointer.
355 X.getNullPtrType(), Y.getAsExpr()->getType()),
356 true);
357
358 // If we deduced a null pointer and an integral constant, keep the
359 // integral constant.
361 return Y;
362
363 // If we deduced two null pointers, they are the same.
365 return TemplateArgument(
366 Context.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
367 true);
368
369 // All other combinations are incompatible.
371
373 if (Y.getKind() != TemplateArgument::Pack ||
374 (!AggregateCandidateDeduction && X.pack_size() != Y.pack_size()))
376
379 XA = X.pack_begin(),
380 XAEnd = X.pack_end(), YA = Y.pack_begin(), YAEnd = Y.pack_end();
381 XA != XAEnd; ++XA) {
382 if (YA != YAEnd) {
384 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
386 if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
388 NewPack.push_back(Merged);
389 ++YA;
390 } else {
391 NewPack.push_back(*XA);
392 }
393 }
394
396 TemplateArgument::CreatePackCopy(Context, NewPack),
397 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
398 }
399 }
400
401 llvm_unreachable("Invalid TemplateArgument Kind!");
402}
403
404/// Deduce the value of the given non-type template parameter
405/// as the given deduced template argument. All non-type template parameter
406/// deduction is funneled through here.
409 const NonTypeTemplateParmDecl *NTTP,
410 const DeducedTemplateArgument &NewDeduced,
411 QualType ValueType, TemplateDeductionInfo &Info,
412 bool PartialOrdering,
414 bool *HasDeducedAnyParam) {
415 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
416 "deducing non-type template argument with wrong depth");
417
419 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
420 if (Result.isNull()) {
421 Info.Param = const_cast<NonTypeTemplateParmDecl*>(NTTP);
422 Info.FirstArg = Deduced[NTTP->getIndex()];
423 Info.SecondArg = NewDeduced;
424 return TemplateDeductionResult::Inconsistent;
425 }
426
427 Deduced[NTTP->getIndex()] = Result;
428 if (!S.getLangOpts().CPlusPlus17)
429 return TemplateDeductionResult::Success;
430
431 if (NTTP->isExpandedParameterPack())
432 // FIXME: We may still need to deduce parts of the type here! But we
433 // don't have any way to find which slice of the type to use, and the
434 // type stored on the NTTP itself is nonsense. Perhaps the type of an
435 // expanded NTTP should be a pack expansion type?
436 return TemplateDeductionResult::Success;
437
438 // Get the type of the parameter for deduction. If it's a (dependent) array
439 // or function type, we will not have decayed it yet, so do that now.
440 QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
441 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
442 ParamType = Expansion->getPattern();
443
444 // FIXME: It's not clear how deduction of a parameter of reference
445 // type from an argument (of non-reference type) should be performed.
446 // For now, we just make the argument have same reference type as the
447 // parameter.
448 if (ParamType->isReferenceType() && !ValueType->isReferenceType()) {
449 if (ParamType->isRValueReferenceType())
450 ValueType = S.Context.getRValueReferenceType(ValueType);
451 else
452 ValueType = S.Context.getLValueReferenceType(ValueType);
453 }
454
456 S, TemplateParams, ParamType, ValueType, Info, Deduced,
460 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound(), HasDeducedAnyParam);
461}
462
463/// Deduce the value of the given non-type template parameter
464/// from the given integral constant.
466 Sema &S, TemplateParameterList *TemplateParams,
467 const NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
468 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
470 bool *HasDeducedAnyParam) {
472 S, TemplateParams, NTTP,
474 DeducedFromArrayBound),
475 ValueType, Info, PartialOrdering, Deduced, HasDeducedAnyParam);
476}
477
478/// Deduce the value of the given non-type template parameter
479/// from the given null pointer template argument type.
482 const NonTypeTemplateParmDecl *NTTP,
483 QualType NullPtrType, TemplateDeductionInfo &Info,
484 bool PartialOrdering,
486 bool *HasDeducedAnyParam) {
489 NTTP->getLocation()),
490 NullPtrType,
491 NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer
492 : CK_NullToPointer)
493 .get();
495 S, TemplateParams, NTTP, DeducedTemplateArgument(Value), Value->getType(),
496 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
497}
498
499/// Deduce the value of the given non-type template parameter
500/// from the given type- or value-dependent expression.
501///
502/// \returns true if deduction succeeded, false otherwise.
505 const NonTypeTemplateParmDecl *NTTP, Expr *Value,
508 bool *HasDeducedAnyParam) {
510 S, TemplateParams, NTTP, DeducedTemplateArgument(Value), Value->getType(),
511 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
512}
513
514/// Deduce the value of the given non-type template parameter
515/// from the given declaration.
516///
517/// \returns true if deduction succeeded, false otherwise.
520 const NonTypeTemplateParmDecl *NTTP, ValueDecl *D,
522 bool PartialOrdering,
524 bool *HasDeducedAnyParam) {
525 TemplateArgument New(D, T);
527 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info,
528 PartialOrdering, Deduced, HasDeducedAnyParam);
529}
530
532 Sema &S, TemplateParameterList *TemplateParams, TemplateName Param,
536 bool *HasDeducedAnyParam) {
537 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
538 if (!ParamDecl) {
539 // The parameter type is dependent and is not a template template parameter,
540 // so there is nothing that we can deduce.
541 return TemplateDeductionResult::Success;
542 }
543
544 if (auto *TempParam = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
545 // If we're not deducing at this depth, there's nothing to deduce.
546 if (TempParam->getDepth() != Info.getDeducedDepth())
547 return TemplateDeductionResult::Success;
548
549 ArrayRef<NamedDecl *> Params =
550 ParamDecl->getTemplateParameters()->asArray();
551 unsigned StartPos = 0;
552 for (unsigned I = 0, E = std::min(Params.size(), DefaultArguments.size());
553 I < E; ++I) {
554 if (Params[I]->isParameterPack()) {
555 StartPos = DefaultArguments.size();
556 break;
557 }
558 StartPos = I + 1;
559 }
560
561 // Provisional resolution for CWG2398: If Arg names a template
562 // specialization, then we deduce a synthesized template name
563 // based on A, but using the TS's extra arguments, relative to P, as
564 // defaults.
565 DeducedTemplateArgument NewDeduced =
568 Arg, {StartPos, DefaultArguments.drop_front(StartPos)}))
569 : Arg;
570
572 S.Context, Deduced[TempParam->getIndex()], NewDeduced);
573 if (Result.isNull()) {
574 Info.Param = TempParam;
575 Info.FirstArg = Deduced[TempParam->getIndex()];
576 Info.SecondArg = NewDeduced;
577 return TemplateDeductionResult::Inconsistent;
578 }
579
580 Deduced[TempParam->getIndex()] = Result;
581 if (HasDeducedAnyParam)
582 *HasDeducedAnyParam = true;
583 return TemplateDeductionResult::Success;
584 }
585
586 // Verify that the two template names are equivalent.
588 Param, Arg, /*IgnoreDeduced=*/DefaultArguments.size() != 0))
589 return TemplateDeductionResult::Success;
590
591 // Mismatch of non-dependent template parameter to argument.
592 Info.FirstArg = TemplateArgument(Param);
593 Info.SecondArg = TemplateArgument(Arg);
594 return TemplateDeductionResult::NonDeducedMismatch;
595}
596
597/// Deduce the template arguments by comparing the template parameter
598/// type (which is a template-id) with the template argument type.
599///
600/// \param S the Sema
601///
602/// \param TemplateParams the template parameters that we are deducing
603///
604/// \param P the parameter type
605///
606/// \param A the argument type
607///
608/// \param Info information about the template argument deduction itself
609///
610/// \param Deduced the deduced template arguments
611///
612/// \returns the result of template argument deduction so far. Note that a
613/// "success" result means that template argument deduction has not yet failed,
614/// but it may still fail, later, for other reasons.
615
617 for (const Type *T = QT.getTypePtr(); /**/; /**/) {
618 const TemplateSpecializationType *TST =
620 assert(TST && "Expected a TemplateSpecializationType");
621 if (!TST->isSugared())
622 return TST;
623 T = TST->desugar().getTypePtr();
624 }
625}
626
629 const QualType P, QualType A,
632 bool *HasDeducedAnyParam) {
633 QualType UP = P;
634 if (const auto *IP = P->getAs<InjectedClassNameType>())
635 UP = IP->getInjectedSpecializationType();
636
637 assert(isa<TemplateSpecializationType>(UP.getCanonicalType()));
639 TemplateName TNP = TP->getTemplateName();
640
641 // If the parameter is an alias template, there is nothing to deduce.
642 if (const auto *TD = TNP.getAsTemplateDecl(); TD && TD->isTypeAlias())
643 return TemplateDeductionResult::Success;
644
645 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
646 // arguments.
650 ->template_arguments();
651
652 QualType UA = A;
653 std::optional<NestedNameSpecifier *> NNS;
654 // Treat an injected-class-name as its underlying template-id.
655 if (const auto *Elaborated = A->getAs<ElaboratedType>()) {
656 NNS = Elaborated->getQualifier();
657 } else if (const auto *Injected = A->getAs<InjectedClassNameType>()) {
658 UA = Injected->getInjectedSpecializationType();
659 NNS = nullptr;
660 }
661
662 // Check whether the template argument is a dependent template-id.
663 if (isa<TemplateSpecializationType>(UA.getCanonicalType())) {
665 TemplateName TNA = SA->getTemplateName();
666
667 // If the argument is an alias template, there is nothing to deduce.
668 if (const auto *TD = TNA.getAsTemplateDecl(); TD && TD->isTypeAlias())
669 return TemplateDeductionResult::Success;
670
671 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
672 // arguments.
676 ->template_arguments();
677
678 // Perform template argument deduction for the template name.
679 if (auto Result = DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
680 /*DefaultArguments=*/AResolved,
681 PartialOrdering, Deduced,
682 HasDeducedAnyParam);
683 Result != TemplateDeductionResult::Success)
684 return Result;
685
686 // Perform template argument deduction on each template
687 // argument. Ignore any missing/extra arguments, since they could be
688 // filled in by default arguments.
690 S, TemplateParams, PResolved, AResolved, Info, Deduced,
691 /*NumberOfArgumentsMustMatch=*/false, PartialOrdering,
692 PackFold::ParameterToArgument, HasDeducedAnyParam);
693 }
694
695 // If the argument type is a class template specialization, we
696 // perform template argument deduction using its template
697 // arguments.
698 const auto *RA = UA->getAs<RecordType>();
699 const auto *SA =
700 RA ? dyn_cast<ClassTemplateSpecializationDecl>(RA->getDecl()) : nullptr;
701 if (!SA) {
703 Info.SecondArg = TemplateArgument(A);
704 return TemplateDeductionResult::NonDeducedMismatch;
705 }
706
707 TemplateName TNA = TemplateName(SA->getSpecializedTemplate());
708 if (NNS)
710 *NNS, false, TemplateName(SA->getSpecializedTemplate()));
711
712 // Perform template argument deduction for the template name.
713 if (auto Result = DeduceTemplateArguments(
714 S, TemplateParams, TNP, TNA, Info,
715 /*DefaultArguments=*/SA->getTemplateArgs().asArray(), PartialOrdering,
716 Deduced, HasDeducedAnyParam);
717 Result != TemplateDeductionResult::Success)
718 return Result;
719
720 // Perform template argument deduction for the template arguments.
721 return DeduceTemplateArguments(S, TemplateParams, PResolved,
722 SA->getTemplateArgs().asArray(), Info, Deduced,
723 /*NumberOfArgumentsMustMatch=*/true,
725 HasDeducedAnyParam);
726}
727
729 assert(T->isCanonicalUnqualified());
730
731 switch (T->getTypeClass()) {
732 case Type::TypeOfExpr:
733 case Type::TypeOf:
734 case Type::DependentName:
735 case Type::Decltype:
736 case Type::PackIndexing:
737 case Type::UnresolvedUsing:
738 case Type::TemplateTypeParm:
739 case Type::Auto:
740 return true;
741
742 case Type::ConstantArray:
743 case Type::IncompleteArray:
744 case Type::VariableArray:
745 case Type::DependentSizedArray:
747 cast<ArrayType>(T)->getElementType().getTypePtr());
748
749 default:
750 return false;
751 }
752}
753
754/// Determines whether the given type is an opaque type that
755/// might be more qualified when instantiated.
759}
760
761/// Helper function to build a TemplateParameter when we don't
762/// know its type statically.
764 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
765 return TemplateParameter(TTP);
766 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
767 return TemplateParameter(NTTP);
768
769 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
770}
771
772/// A pack that we're currently deducing.
774 // The index of the pack.
775 unsigned Index;
776
777 // The old value of the pack before we started deducing it.
779
780 // A deferred value of this pack from an inner deduction, that couldn't be
781 // deduced because this deduction hadn't happened yet.
783
784 // The new value of the pack.
786
787 // The outer deduction for this pack, if any.
788 DeducedPack *Outer = nullptr;
789
790 DeducedPack(unsigned Index) : Index(Index) {}
791};
792
793namespace {
794
795/// A scope in which we're performing pack deduction.
796class PackDeductionScope {
797public:
798 /// Prepare to deduce the packs named within Pattern.
799 /// \param FinishingDeduction Don't attempt to deduce the pack. Useful when
800 /// just checking a previous deduction of the pack.
801 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
804 bool DeducePackIfNotAlreadyDeduced = false,
805 bool FinishingDeduction = false)
806 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info),
807 DeducePackIfNotAlreadyDeduced(DeducePackIfNotAlreadyDeduced),
808 FinishingDeduction(FinishingDeduction) {
809 unsigned NumNamedPacks = addPacks(Pattern);
810 finishConstruction(NumNamedPacks);
811 }
812
813 /// Prepare to directly deduce arguments of the parameter with index \p Index.
814 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
816 TemplateDeductionInfo &Info, unsigned Index)
817 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
818 addPack(Index);
819 finishConstruction(1);
820 }
821
822private:
823 void addPack(unsigned Index) {
824 // Save the deduced template argument for the parameter pack expanded
825 // by this pack expansion, then clear out the deduction.
826 DeducedFromEarlierParameter = !Deduced[Index].isNull();
827 DeducedPack Pack(Index);
828 if (!FinishingDeduction) {
829 Pack.Saved = Deduced[Index];
830 Deduced[Index] = TemplateArgument();
831 }
832
833 // FIXME: What if we encounter multiple packs with different numbers of
834 // pre-expanded expansions? (This should already have been diagnosed
835 // during substitution.)
836 if (std::optional<unsigned> ExpandedPackExpansions =
837 getExpandedPackSize(TemplateParams->getParam(Index)))
838 FixedNumExpansions = ExpandedPackExpansions;
839
840 Packs.push_back(Pack);
841 }
842
843 unsigned addPacks(TemplateArgument Pattern) {
844 // Compute the set of template parameter indices that correspond to
845 // parameter packs expanded by the pack expansion.
846 llvm::SmallBitVector SawIndices(TemplateParams->size());
848
849 auto AddPack = [&](unsigned Index) {
850 if (SawIndices[Index])
851 return;
852 SawIndices[Index] = true;
853 addPack(Index);
854
855 // Deducing a parameter pack that is a pack expansion also constrains the
856 // packs appearing in that parameter to have the same deduced arity. Also,
857 // in C++17 onwards, deducing a non-type template parameter deduces its
858 // type, so we need to collect the pending deduced values for those packs.
859 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
860 TemplateParams->getParam(Index))) {
861 if (!NTTP->isExpandedParameterPack())
862 // FIXME: CWG2982 suggests a type-constraint forms a non-deduced
863 // context, however it is not yet resolved.
864 if (auto *Expansion = dyn_cast<PackExpansionType>(
865 S.Context.getUnconstrainedType(NTTP->getType())))
866 ExtraDeductions.push_back(Expansion->getPattern());
867 }
868 // FIXME: Also collect the unexpanded packs in any type and template
869 // parameter packs that are pack expansions.
870 };
871
872 auto Collect = [&](TemplateArgument Pattern) {
874 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
875 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
876 unsigned Depth, Index;
877 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
878 if (Depth == Info.getDeducedDepth())
879 AddPack(Index);
880 }
881 };
882
883 // Look for unexpanded packs in the pattern.
884 Collect(Pattern);
885 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
886
887 unsigned NumNamedPacks = Packs.size();
888
889 // Also look for unexpanded packs that are indirectly deduced by deducing
890 // the sizes of the packs in this pattern.
891 while (!ExtraDeductions.empty())
892 Collect(ExtraDeductions.pop_back_val());
893
894 return NumNamedPacks;
895 }
896
897 void finishConstruction(unsigned NumNamedPacks) {
898 // Dig out the partially-substituted pack, if there is one.
899 const TemplateArgument *PartialPackArgs = nullptr;
900 unsigned NumPartialPackArgs = 0;
901 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
902 if (auto *Scope = S.CurrentInstantiationScope)
903 if (auto *Partial = Scope->getPartiallySubstitutedPack(
904 &PartialPackArgs, &NumPartialPackArgs))
905 PartialPackDepthIndex = getDepthAndIndex(Partial);
906
907 // This pack expansion will have been partially or fully expanded if
908 // it only names explicitly-specified parameter packs (including the
909 // partially-substituted one, if any).
910 bool IsExpanded = true;
911 for (unsigned I = 0; I != NumNamedPacks; ++I) {
912 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
913 IsExpanded = false;
914 IsPartiallyExpanded = false;
915 break;
916 }
917 if (PartialPackDepthIndex ==
918 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
919 IsPartiallyExpanded = true;
920 }
921 }
922
923 // Skip over the pack elements that were expanded into separate arguments.
924 // If we partially expanded, this is the number of partial arguments.
925 // FIXME: `&& FixedNumExpansions` is a workaround for UB described in
926 // https://github.com/llvm/llvm-project/issues/100095
927 if (IsPartiallyExpanded)
928 PackElements += NumPartialPackArgs;
929 else if (IsExpanded && FixedNumExpansions)
930 PackElements += *FixedNumExpansions;
931
932 for (auto &Pack : Packs) {
933 if (Info.PendingDeducedPacks.size() > Pack.Index)
934 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
935 else
936 Info.PendingDeducedPacks.resize(Pack.Index + 1);
937 Info.PendingDeducedPacks[Pack.Index] = &Pack;
938
939 if (PartialPackDepthIndex ==
940 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
941 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
942 // We pre-populate the deduced value of the partially-substituted
943 // pack with the specified value. This is not entirely correct: the
944 // value is supposed to have been substituted, not deduced, but the
945 // cases where this is observable require an exact type match anyway.
946 //
947 // FIXME: If we could represent a "depth i, index j, pack elem k"
948 // parameter, we could substitute the partially-substituted pack
949 // everywhere and avoid this.
950 if (!FinishingDeduction && !IsPartiallyExpanded)
951 Deduced[Pack.Index] = Pack.New[PackElements];
952 }
953 }
954 }
955
956public:
957 ~PackDeductionScope() {
958 for (auto &Pack : Packs)
959 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
960 }
961
962 // Return the size of the saved packs if all of them has the same size.
963 std::optional<unsigned> getSavedPackSizeIfAllEqual() const {
964 unsigned PackSize = Packs[0].Saved.pack_size();
965
966 if (std::all_of(Packs.begin() + 1, Packs.end(), [&PackSize](const auto &P) {
967 return P.Saved.pack_size() == PackSize;
968 }))
969 return PackSize;
970 return {};
971 }
972
973 /// Determine whether this pack has already been deduced from a previous
974 /// argument.
975 bool isDeducedFromEarlierParameter() const {
976 return DeducedFromEarlierParameter;
977 }
978
979 /// Determine whether this pack has already been partially expanded into a
980 /// sequence of (prior) function parameters / template arguments.
981 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
982
983 /// Determine whether this pack expansion scope has a known, fixed arity.
984 /// This happens if it involves a pack from an outer template that has
985 /// (notionally) already been expanded.
986 bool hasFixedArity() { return FixedNumExpansions.has_value(); }
987
988 /// Determine whether the next element of the argument is still part of this
989 /// pack. This is the case unless the pack is already expanded to a fixed
990 /// length.
991 bool hasNextElement() {
992 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
993 }
994
995 /// Move to deducing the next element in each pack that is being deduced.
996 void nextPackElement() {
997 // Capture the deduced template arguments for each parameter pack expanded
998 // by this pack expansion, add them to the list of arguments we've deduced
999 // for that pack, then clear out the deduced argument.
1000 if (!FinishingDeduction) {
1001 for (auto &Pack : Packs) {
1002 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
1003 if (!Pack.New.empty() || !DeducedArg.isNull()) {
1004 while (Pack.New.size() < PackElements)
1005 Pack.New.push_back(DeducedTemplateArgument());
1006 if (Pack.New.size() == PackElements)
1007 Pack.New.push_back(DeducedArg);
1008 else
1009 Pack.New[PackElements] = DeducedArg;
1010 DeducedArg = Pack.New.size() > PackElements + 1
1011 ? Pack.New[PackElements + 1]
1013 }
1014 }
1015 }
1016 ++PackElements;
1017 }
1018
1019 /// Finish template argument deduction for a set of argument packs,
1020 /// producing the argument packs and checking for consistency with prior
1021 /// deductions.
1022 TemplateDeductionResult finish() {
1023 if (FinishingDeduction)
1024 return TemplateDeductionResult::Success;
1025 // Build argument packs for each of the parameter packs expanded by this
1026 // pack expansion.
1027 for (auto &Pack : Packs) {
1028 // Put back the old value for this pack.
1029 if (!FinishingDeduction)
1030 Deduced[Pack.Index] = Pack.Saved;
1031
1032 // Always make sure the size of this pack is correct, even if we didn't
1033 // deduce any values for it.
1034 //
1035 // FIXME: This isn't required by the normative wording, but substitution
1036 // and post-substitution checking will always fail if the arity of any
1037 // pack is not equal to the number of elements we processed. (Either that
1038 // or something else has gone *very* wrong.) We're permitted to skip any
1039 // hard errors from those follow-on steps by the intent (but not the
1040 // wording) of C++ [temp.inst]p8:
1041 //
1042 // If the function selected by overload resolution can be determined
1043 // without instantiating a class template definition, it is unspecified
1044 // whether that instantiation actually takes place
1045 Pack.New.resize(PackElements);
1046
1047 // Build or find a new value for this pack.
1049 if (Pack.New.empty()) {
1050 // If we deduced an empty argument pack, create it now.
1052 } else {
1053 TemplateArgument *ArgumentPack =
1054 new (S.Context) TemplateArgument[Pack.New.size()];
1055 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
1056 NewPack = DeducedTemplateArgument(
1057 TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())),
1058 // FIXME: This is wrong, it's possible that some pack elements are
1059 // deduced from an array bound and others are not:
1060 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
1061 // g({1, 2, 3}, {{}, {}});
1062 // ... should deduce T = {int, size_t (from array bound)}.
1063 Pack.New[0].wasDeducedFromArrayBound());
1064 }
1065
1066 // Pick where we're going to put the merged pack.
1068 if (Pack.Outer) {
1069 if (Pack.Outer->DeferredDeduction.isNull()) {
1070 // Defer checking this pack until we have a complete pack to compare
1071 // it against.
1072 Pack.Outer->DeferredDeduction = NewPack;
1073 continue;
1074 }
1075 Loc = &Pack.Outer->DeferredDeduction;
1076 } else {
1077 Loc = &Deduced[Pack.Index];
1078 }
1079
1080 // Check the new pack matches any previous value.
1081 DeducedTemplateArgument OldPack = *Loc;
1083 S.Context, OldPack, NewPack, DeducePackIfNotAlreadyDeduced);
1084
1085 Info.AggregateDeductionCandidateHasMismatchedArity =
1086 OldPack.getKind() == TemplateArgument::Pack &&
1087 NewPack.getKind() == TemplateArgument::Pack &&
1088 OldPack.pack_size() != NewPack.pack_size() && !Result.isNull();
1089
1090 // If we deferred a deduction of this pack, check that one now too.
1091 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
1092 OldPack = Result;
1093 NewPack = Pack.DeferredDeduction;
1094 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
1095 }
1096
1097 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
1098 if (Result.isNull()) {
1099 Info.Param = makeTemplateParameter(Param);
1100 Info.FirstArg = OldPack;
1101 Info.SecondArg = NewPack;
1102 return TemplateDeductionResult::Inconsistent;
1103 }
1104
1105 // If we have a pre-expanded pack and we didn't deduce enough elements
1106 // for it, fail deduction.
1107 if (std::optional<unsigned> Expansions = getExpandedPackSize(Param)) {
1108 if (*Expansions != PackElements) {
1109 Info.Param = makeTemplateParameter(Param);
1110 Info.FirstArg = Result;
1111 return TemplateDeductionResult::IncompletePack;
1112 }
1113 }
1114
1115 *Loc = Result;
1116 }
1117
1118 return TemplateDeductionResult::Success;
1119 }
1120
1121private:
1122 Sema &S;
1123 TemplateParameterList *TemplateParams;
1126 unsigned PackElements = 0;
1127 bool IsPartiallyExpanded = false;
1128 bool DeducePackIfNotAlreadyDeduced = false;
1129 bool DeducedFromEarlierParameter = false;
1130 bool FinishingDeduction = false;
1131 /// The number of expansions, if we have a fully-expanded pack in this scope.
1132 std::optional<unsigned> FixedNumExpansions;
1133
1135};
1136
1137} // namespace
1138
1139template <class T>
1141 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1144 bool FinishingDeduction, T &&DeductFunc) {
1145 // C++0x [temp.deduct.type]p10:
1146 // Similarly, if P has a form that contains (T), then each parameter type
1147 // Pi of the respective parameter-type- list of P is compared with the
1148 // corresponding parameter type Ai of the corresponding parameter-type-list
1149 // of A. [...]
1150 unsigned ArgIdx = 0, ParamIdx = 0;
1151 for (; ParamIdx != Params.size(); ++ParamIdx) {
1152 // Check argument types.
1153 const PackExpansionType *Expansion
1154 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1155 if (!Expansion) {
1156 // Simple case: compare the parameter and argument types at this point.
1157
1158 // Make sure we have an argument.
1159 if (ArgIdx >= Args.size())
1160 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1161
1162 if (isa<PackExpansionType>(Args[ArgIdx])) {
1163 // C++0x [temp.deduct.type]p22:
1164 // If the original function parameter associated with A is a function
1165 // parameter pack and the function parameter associated with P is not
1166 // a function parameter pack, then template argument deduction fails.
1167 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1168 }
1169
1170 if (TemplateDeductionResult Result =
1171 DeductFunc(S, TemplateParams, ParamIdx, ArgIdx,
1172 Params[ParamIdx].getUnqualifiedType(),
1173 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, POK);
1174 Result != TemplateDeductionResult::Success)
1175 return Result;
1176
1177 ++ArgIdx;
1178 continue;
1179 }
1180
1181 // C++0x [temp.deduct.type]p10:
1182 // If the parameter-declaration corresponding to Pi is a function
1183 // parameter pack, then the type of its declarator- id is compared with
1184 // each remaining parameter type in the parameter-type-list of A. Each
1185 // comparison deduces template arguments for subsequent positions in the
1186 // template parameter packs expanded by the function parameter pack.
1187
1188 QualType Pattern = Expansion->getPattern();
1189 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern,
1190 /*DeducePackIfNotAlreadyDeduced=*/false,
1191 FinishingDeduction);
1192
1193 // A pack scope with fixed arity is not really a pack any more, so is not
1194 // a non-deduced context.
1195 if (ParamIdx + 1 == Params.size() || PackScope.hasFixedArity()) {
1196 for (; ArgIdx < Args.size() && PackScope.hasNextElement(); ++ArgIdx) {
1197 // Deduce template arguments from the pattern.
1198 if (TemplateDeductionResult Result = DeductFunc(
1199 S, TemplateParams, ParamIdx, ArgIdx,
1200 Pattern.getUnqualifiedType(), Args[ArgIdx].getUnqualifiedType(),
1201 Info, Deduced, POK);
1202 Result != TemplateDeductionResult::Success)
1203 return Result;
1204 PackScope.nextPackElement();
1205 }
1206 } else {
1207 // C++0x [temp.deduct.type]p5:
1208 // The non-deduced contexts are:
1209 // - A function parameter pack that does not occur at the end of the
1210 // parameter-declaration-clause.
1211 //
1212 // FIXME: There is no wording to say what we should do in this case. We
1213 // choose to resolve this by applying the same rule that is applied for a
1214 // function call: that is, deduce all contained packs to their
1215 // explicitly-specified values (or to <> if there is no such value).
1216 //
1217 // This is seemingly-arbitrarily different from the case of a template-id
1218 // with a non-trailing pack-expansion in its arguments, which renders the
1219 // entire template-argument-list a non-deduced context.
1220
1221 // If the parameter type contains an explicitly-specified pack that we
1222 // could not expand, skip the number of parameters notionally created
1223 // by the expansion.
1224 std::optional<unsigned> NumExpansions = Expansion->getNumExpansions();
1225 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1226 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
1227 ++I, ++ArgIdx)
1228 PackScope.nextPackElement();
1229 }
1230 }
1231
1232 // Build argument packs for each of the parameter packs expanded by this
1233 // pack expansion.
1234 if (auto Result = PackScope.finish();
1235 Result != TemplateDeductionResult::Success)
1236 return Result;
1237 }
1238
1239 // DR692, DR1395
1240 // C++0x [temp.deduct.type]p10:
1241 // If the parameter-declaration corresponding to P_i ...
1242 // During partial ordering, if Ai was originally a function parameter pack:
1243 // - if P does not contain a function parameter type corresponding to Ai then
1244 // Ai is ignored;
1245 if (POK == PartialOrderingKind::Call && ArgIdx + 1 == Args.size() &&
1246 isa<PackExpansionType>(Args[ArgIdx]))
1247 return TemplateDeductionResult::Success;
1248
1249 // Make sure we don't have any extra arguments.
1250 if (ArgIdx < Args.size())
1251 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1252
1253 return TemplateDeductionResult::Success;
1254}
1255
1256/// Deduce the template arguments by comparing the list of parameter
1257/// types to the list of argument types, as in the parameter-type-lists of
1258/// function types (C++ [temp.deduct.type]p10).
1259///
1260/// \param S The semantic analysis object within which we are deducing
1261///
1262/// \param TemplateParams The template parameters that we are deducing
1263///
1264/// \param Params The list of parameter types
1265///
1266/// \param Args The list of argument types
1267///
1268/// \param Info information about the template argument deduction itself
1269///
1270/// \param Deduced the deduced template arguments
1271///
1272/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1273/// how template argument deduction is performed.
1274///
1275/// \param PartialOrdering If true, we are performing template argument
1276/// deduction for during partial ordering for a call
1277/// (C++0x [temp.deduct.partial]).
1278///
1279/// \param HasDeducedAnyParam If set, the object pointed at will indicate
1280/// whether any template parameter was deduced.
1281///
1282/// \param HasDeducedParam If set, the bit vector will be used to represent
1283/// which template parameters were deduced, in order.
1284///
1285/// \returns the result of template argument deduction so far. Note that a
1286/// "success" result means that template argument deduction has not yet failed,
1287/// but it may still fail, later, for other reasons.
1289 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1291 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1292 PartialOrderingKind POK, bool *HasDeducedAnyParam,
1293 llvm::SmallBitVector *HasDeducedParam) {
1294 return ::DeduceForEachType(
1295 S, TemplateParams, Params, Args, Info, Deduced, POK,
1296 /*FinishingDeduction=*/false,
1297 [&](Sema &S, TemplateParameterList *TemplateParams, int ParamIdx,
1298 int ArgIdx, QualType P, QualType A, TemplateDeductionInfo &Info,
1300 PartialOrderingKind POK) {
1301 bool HasDeducedAnyParamCopy = false;
1303 S, TemplateParams, P, A, Info, Deduced, TDF, POK,
1304 /*DeducedFromArrayBound=*/false, &HasDeducedAnyParamCopy);
1305 if (HasDeducedAnyParam && HasDeducedAnyParamCopy)
1306 *HasDeducedAnyParam = true;
1307 if (HasDeducedParam && HasDeducedAnyParamCopy)
1308 (*HasDeducedParam)[ParamIdx] = true;
1309 return TDR;
1310 });
1311}
1312
1313/// Determine whether the parameter has qualifiers that the argument
1314/// lacks. Put another way, determine whether there is no way to add
1315/// a deduced set of qualifiers to the ParamType that would result in
1316/// its qualifiers matching those of the ArgType.
1318 QualType ArgType) {
1319 Qualifiers ParamQs = ParamType.getQualifiers();
1320 Qualifiers ArgQs = ArgType.getQualifiers();
1321
1322 if (ParamQs == ArgQs)
1323 return false;
1324
1325 // Mismatched (but not missing) Objective-C GC attributes.
1326 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1327 ParamQs.hasObjCGCAttr())
1328 return true;
1329
1330 // Mismatched (but not missing) address spaces.
1331 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1332 ParamQs.hasAddressSpace())
1333 return true;
1334
1335 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1336 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1337 ParamQs.hasObjCLifetime())
1338 return true;
1339
1340 // CVR qualifiers inconsistent or a superset.
1341 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1342}
1343
1345 const FunctionType *PF = P->getAs<FunctionType>(),
1346 *AF = A->getAs<FunctionType>();
1347
1348 // Just compare if not functions.
1349 if (!PF || !AF)
1350 return Context.hasSameType(P, A);
1351
1352 // Noreturn and noexcept adjustment.
1353 if (QualType AdjustedParam; IsFunctionConversion(P, A, AdjustedParam))
1354 P = AdjustedParam;
1355
1356 // FIXME: Compatible calling conventions.
1358}
1359
1360/// Get the index of the first template parameter that was originally from the
1361/// innermost template-parameter-list. This is 0 except when we concatenate
1362/// the template parameter lists of a class template and a constructor template
1363/// when forming an implicit deduction guide.
1365 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1366 if (!Guide || !Guide->isImplicit())
1367 return 0;
1368 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1369}
1370
1371/// Determine whether a type denotes a forwarding reference.
1372static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1373 // C++1z [temp.deduct.call]p3:
1374 // A forwarding reference is an rvalue reference to a cv-unqualified
1375 // template parameter that does not represent a template parameter of a
1376 // class template.
1377 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1378 if (ParamRef->getPointeeType().getQualifiers())
1379 return false;
1380 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1381 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1382 }
1383 return false;
1384}
1385
1386/// Attempt to deduce the template arguments by checking the base types
1387/// according to (C++20 [temp.deduct.call] p4b3.
1388///
1389/// \param S the semantic analysis object within which we are deducing.
1390///
1391/// \param RD the top level record object we are deducing against.
1392///
1393/// \param TemplateParams the template parameters that we are deducing.
1394///
1395/// \param P the template specialization parameter type.
1396///
1397/// \param Info information about the template argument deduction itself.
1398///
1399/// \param Deduced the deduced template arguments.
1400///
1401/// \returns the result of template argument deduction with the bases. "invalid"
1402/// means no matches, "success" found a single item, and the
1403/// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
1406 TemplateParameterList *TemplateParams, QualType P,
1409 bool *HasDeducedAnyParam) {
1410 // C++14 [temp.deduct.call] p4b3:
1411 // If P is a class and P has the form simple-template-id, then the
1412 // transformed A can be a derived class of the deduced A. Likewise if
1413 // P is a pointer to a class of the form simple-template-id, the
1414 // transformed A can be a pointer to a derived class pointed to by the
1415 // deduced A. However, if there is a class C that is a (direct or
1416 // indirect) base class of D and derived (directly or indirectly) from a
1417 // class B and that would be a valid deduced A, the deduced A cannot be
1418 // B or pointer to B, respectively.
1419 //
1420 // These alternatives are considered only if type deduction would
1421 // otherwise fail. If they yield more than one possible deduced A, the
1422 // type deduction fails.
1423
1424 // Use a breadth-first search through the bases to collect the set of
1425 // successful matches. Visited contains the set of nodes we have already
1426 // visited, while ToVisit is our stack of records that we still need to
1427 // visit. Matches contains a list of matches that have yet to be
1428 // disqualified.
1431 // We iterate over this later, so we have to use MapVector to ensure
1432 // determinism.
1433 struct MatchValue {
1435 bool HasDeducedAnyParam;
1436 };
1437 llvm::MapVector<const CXXRecordDecl *, MatchValue> Matches;
1438
1439 auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
1440 for (const auto &Base : RD->bases()) {
1441 QualType T = Base.getType();
1442 assert(T->isRecordType() && "Base class that isn't a record?");
1443 if (Visited.insert(T->getAsCXXRecordDecl()).second)
1444 ToVisit.push_back(T);
1445 }
1446 };
1447
1448 // Set up the loop by adding all the bases.
1449 AddBases(RD);
1450
1451 // Search each path of bases until we either run into a successful match
1452 // (where all bases of it are invalid), or we run out of bases.
1453 while (!ToVisit.empty()) {
1454 QualType NextT = ToVisit.pop_back_val();
1455
1456 SmallVector<DeducedTemplateArgument, 8> DeducedCopy(Deduced.begin(),
1457 Deduced.end());
1459 bool HasDeducedAnyParamCopy = false;
1461 S, TemplateParams, P, NextT, BaseInfo, PartialOrdering, DeducedCopy,
1462 &HasDeducedAnyParamCopy);
1463
1464 // If this was a successful deduction, add it to the list of matches,
1465 // otherwise we need to continue searching its bases.
1466 const CXXRecordDecl *RD = NextT->getAsCXXRecordDecl();
1468 Matches.insert({RD, {DeducedCopy, HasDeducedAnyParamCopy}});
1469 else
1470 AddBases(RD);
1471 }
1472
1473 // At this point, 'Matches' contains a list of seemingly valid bases, however
1474 // in the event that we have more than 1 match, it is possible that the base
1475 // of one of the matches might be disqualified for being a base of another
1476 // valid match. We can count on cyclical instantiations being invalid to
1477 // simplify the disqualifications. That is, if A & B are both matches, and B
1478 // inherits from A (disqualifying A), we know that A cannot inherit from B.
1479 if (Matches.size() > 1) {
1480 Visited.clear();
1481 for (const auto &Match : Matches)
1482 AddBases(Match.first);
1483
1484 // We can give up once we have a single item (or have run out of things to
1485 // search) since cyclical inheritance isn't valid.
1486 while (Matches.size() > 1 && !ToVisit.empty()) {
1487 const CXXRecordDecl *RD = ToVisit.pop_back_val()->getAsCXXRecordDecl();
1488 Matches.erase(RD);
1489
1490 // Always add all bases, since the inheritance tree can contain
1491 // disqualifications for multiple matches.
1492 AddBases(RD);
1493 }
1494 }
1495
1496 if (Matches.empty())
1498 if (Matches.size() > 1)
1500
1501 std::swap(Matches.front().second.Deduced, Deduced);
1502 if (bool HasDeducedAnyParamCopy = Matches.front().second.HasDeducedAnyParam;
1503 HasDeducedAnyParamCopy && HasDeducedAnyParam)
1504 *HasDeducedAnyParam = HasDeducedAnyParamCopy;
1506}
1507
1508/// When propagating a partial ordering kind into a NonCall context,
1509/// this is used to downgrade a 'Call' into a 'NonCall', so that
1510/// the kind still reflects whether we are in a partial ordering context.
1513 return std::min(POK, PartialOrderingKind::NonCall);
1514}
1515
1516/// Deduce the template arguments by comparing the parameter type and
1517/// the argument type (C++ [temp.deduct.type]).
1518///
1519/// \param S the semantic analysis object within which we are deducing
1520///
1521/// \param TemplateParams the template parameters that we are deducing
1522///
1523/// \param P the parameter type
1524///
1525/// \param A the argument type
1526///
1527/// \param Info information about the template argument deduction itself
1528///
1529/// \param Deduced the deduced template arguments
1530///
1531/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1532/// how template argument deduction is performed.
1533///
1534/// \param PartialOrdering Whether we're performing template argument deduction
1535/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1536///
1537/// \returns the result of template argument deduction so far. Note that a
1538/// "success" result means that template argument deduction has not yet failed,
1539/// but it may still fail, later, for other reasons.
1541 Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
1543 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1544 PartialOrderingKind POK, bool DeducedFromArrayBound,
1545 bool *HasDeducedAnyParam) {
1546
1547 // If the argument type is a pack expansion, look at its pattern.
1548 // This isn't explicitly called out
1549 if (const auto *AExp = dyn_cast<PackExpansionType>(A))
1550 A = AExp->getPattern();
1551 assert(!isa<PackExpansionType>(A.getCanonicalType()));
1552
1553 if (POK == PartialOrderingKind::Call) {
1554 // C++11 [temp.deduct.partial]p5:
1555 // Before the partial ordering is done, certain transformations are
1556 // performed on the types used for partial ordering:
1557 // - If P is a reference type, P is replaced by the type referred to.
1558 const ReferenceType *PRef = P->getAs<ReferenceType>();
1559 if (PRef)
1560 P = PRef->getPointeeType();
1561
1562 // - If A is a reference type, A is replaced by the type referred to.
1563 const ReferenceType *ARef = A->getAs<ReferenceType>();
1564 if (ARef)
1565 A = A->getPointeeType();
1566
1567 if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
1568 // C++11 [temp.deduct.partial]p9:
1569 // If, for a given type, deduction succeeds in both directions (i.e.,
1570 // the types are identical after the transformations above) and both
1571 // P and A were reference types [...]:
1572 // - if [one type] was an lvalue reference and [the other type] was
1573 // not, [the other type] is not considered to be at least as
1574 // specialized as [the first type]
1575 // - if [one type] is more cv-qualified than [the other type],
1576 // [the other type] is not considered to be at least as specialized
1577 // as [the first type]
1578 // Objective-C ARC adds:
1579 // - [one type] has non-trivial lifetime, [the other type] has
1580 // __unsafe_unretained lifetime, and the types are otherwise
1581 // identical
1582 //
1583 // A is "considered to be at least as specialized" as P iff deduction
1584 // succeeds, so we model this as a deduction failure. Note that
1585 // [the first type] is P and [the other type] is A here; the standard
1586 // gets this backwards.
1587 Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
1588 if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
1589 PQuals.isStrictSupersetOf(AQuals) ||
1590 (PQuals.hasNonTrivialObjCLifetime() &&
1591 AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1592 PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
1593 Info.FirstArg = TemplateArgument(P);
1594 Info.SecondArg = TemplateArgument(A);
1596 }
1597 }
1598 Qualifiers DiscardedQuals;
1599 // C++11 [temp.deduct.partial]p7:
1600 // Remove any top-level cv-qualifiers:
1601 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1602 // version of P.
1603 P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
1604 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1605 // version of A.
1606 A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
1607 } else {
1608 // C++0x [temp.deduct.call]p4 bullet 1:
1609 // - If the original P is a reference type, the deduced A (i.e., the type
1610 // referred to by the reference) can be more cv-qualified than the
1611 // transformed A.
1612 if (TDF & TDF_ParamWithReferenceType) {
1613 Qualifiers Quals;
1614 QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
1616 P = S.Context.getQualifiedType(UnqualP, Quals);
1617 }
1618
1619 if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
1620 // C++0x [temp.deduct.type]p10:
1621 // If P and A are function types that originated from deduction when
1622 // taking the address of a function template (14.8.2.2) or when deducing
1623 // template arguments from a function declaration (14.8.2.6) and Pi and
1624 // Ai are parameters of the top-level parameter-type-list of P and A,
1625 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1626 // is an lvalue reference, in
1627 // which case the type of Pi is changed to be the template parameter
1628 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1629 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1630 // deduced as X&. - end note ]
1631 TDF &= ~TDF_TopLevelParameterTypeList;
1632 if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
1634 P = P->getPointeeType();
1635 }
1636 }
1637
1638 // C++ [temp.deduct.type]p9:
1639 // A template type argument T, a template template argument TT or a
1640 // template non-type argument i can be deduced if P and A have one of
1641 // the following forms:
1642 //
1643 // T
1644 // cv-list T
1645 if (const auto *TTP = P->getAs<TemplateTypeParmType>()) {
1646 // Just skip any attempts to deduce from a placeholder type or a parameter
1647 // at a different depth.
1648 if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
1650
1651 unsigned Index = TTP->getIndex();
1652
1653 // If the argument type is an array type, move the qualifiers up to the
1654 // top level, so they can be matched with the qualifiers on the parameter.
1655 if (A->isArrayType()) {
1656 Qualifiers Quals;
1657 A = S.Context.getUnqualifiedArrayType(A, Quals);
1658 if (Quals)
1659 A = S.Context.getQualifiedType(A, Quals);
1660 }
1661
1662 // The argument type can not be less qualified than the parameter
1663 // type.
1664 if (!(TDF & TDF_IgnoreQualifiers) &&
1666 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1667 Info.FirstArg = TemplateArgument(P);
1668 Info.SecondArg = TemplateArgument(A);
1670 }
1671
1672 // Do not match a function type with a cv-qualified type.
1673 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1674 if (A->isFunctionType() && P.hasQualifiers())
1676
1677 assert(TTP->getDepth() == Info.getDeducedDepth() &&
1678 "saw template type parameter with wrong depth");
1679 assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&
1680 "Unresolved overloaded function");
1682
1683 // Remove any qualifiers on the parameter from the deduced type.
1684 // We checked the qualifiers for consistency above.
1685 Qualifiers DeducedQs = DeducedType.getQualifiers();
1686 Qualifiers ParamQs = P.getQualifiers();
1687 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1688 if (ParamQs.hasObjCGCAttr())
1689 DeducedQs.removeObjCGCAttr();
1690 if (ParamQs.hasAddressSpace())
1691 DeducedQs.removeAddressSpace();
1692 if (ParamQs.hasObjCLifetime())
1693 DeducedQs.removeObjCLifetime();
1694
1695 // Objective-C ARC:
1696 // If template deduction would produce a lifetime qualifier on a type
1697 // that is not a lifetime type, template argument deduction fails.
1698 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1700 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1701 Info.FirstArg = TemplateArgument(P);
1702 Info.SecondArg = TemplateArgument(A);
1704 }
1705
1706 // Objective-C ARC:
1707 // If template deduction would produce an argument type with lifetime type
1708 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1709 if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
1710 !DeducedQs.hasObjCLifetime())
1712
1713 DeducedType =
1714 S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
1715
1716 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1718 checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
1719 if (Result.isNull()) {
1720 // We can also get inconsistencies when matching NTTP type.
1721 switch (NamedDecl *Param = TemplateParams->getParam(Index);
1722 Param->getKind()) {
1723 case Decl::TemplateTypeParm:
1724 Info.Param = cast<TemplateTypeParmDecl>(Param);
1725 break;
1726 case Decl::NonTypeTemplateParm:
1727 Info.Param = cast<NonTypeTemplateParmDecl>(Param);
1728 break;
1729 case Decl::TemplateTemplateParm:
1730 Info.Param = cast<TemplateTemplateParmDecl>(Param);
1731 break;
1732 default:
1733 llvm_unreachable("unexpected kind");
1734 }
1735 Info.FirstArg = Deduced[Index];
1736 Info.SecondArg = NewDeduced;
1738 }
1739
1740 Deduced[Index] = Result;
1741 if (HasDeducedAnyParam)
1742 *HasDeducedAnyParam = true;
1744 }
1745
1746 // Set up the template argument deduction information for a failure.
1747 Info.FirstArg = TemplateArgument(P);
1748 Info.SecondArg = TemplateArgument(A);
1749
1750 // If the parameter is an already-substituted template parameter
1751 // pack, do nothing: we don't know which of its arguments to look
1752 // at, so we have to wait until all of the parameter packs in this
1753 // expansion have arguments.
1754 if (P->getAs<SubstTemplateTypeParmPackType>())
1756
1757 // Check the cv-qualifiers on the parameter and argument types.
1758 if (!(TDF & TDF_IgnoreQualifiers)) {
1759 if (TDF & TDF_ParamWithReferenceType) {
1762 } else if (TDF & TDF_ArgWithReferenceType) {
1763 // C++ [temp.deduct.conv]p4:
1764 // If the original A is a reference type, A can be more cv-qualified
1765 // than the deduced A
1766 if (!A.getQualifiers().compatiblyIncludes(P.getQualifiers(),
1767 S.getASTContext()))
1769
1770 // Strip out all extra qualifiers from the argument to figure out the
1771 // type we're converting to, prior to the qualification conversion.
1772 Qualifiers Quals;
1773 A = S.Context.getUnqualifiedArrayType(A, Quals);
1774 A = S.Context.getQualifiedType(A, P.getQualifiers());
1775 } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
1776 if (P.getCVRQualifiers() != A.getCVRQualifiers())
1778 }
1779 }
1780
1781 // If the parameter type is not dependent, there is nothing to deduce.
1782 if (!P->isDependentType()) {
1783 if (TDF & TDF_SkipNonDependent)
1786 : S.Context.hasSameType(P, A))
1791 if (!(TDF & TDF_IgnoreQualifiers))
1793 // Otherwise, when ignoring qualifiers, the types not having the same
1794 // unqualified type does not mean they do not match, so in this case we
1795 // must keep going and analyze with a non-dependent parameter type.
1796 }
1797
1798 switch (P.getCanonicalType()->getTypeClass()) {
1799 // Non-canonical types cannot appear here.
1800#define NON_CANONICAL_TYPE(Class, Base) \
1801 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1802#define TYPE(Class, Base)
1803#include "clang/AST/TypeNodes.inc"
1804
1805 case Type::TemplateTypeParm:
1806 case Type::SubstTemplateTypeParmPack:
1807 llvm_unreachable("Type nodes handled above");
1808
1809 case Type::Auto:
1810 // C++23 [temp.deduct.funcaddr]/3:
1811 // A placeholder type in the return type of a function template is a
1812 // non-deduced context.
1813 // There's no corresponding wording for [temp.deduct.decl], but we treat
1814 // it the same to match other compilers.
1815 if (P->isDependentType())
1817 [[fallthrough]];
1818 case Type::Builtin:
1819 case Type::VariableArray:
1820 case Type::Vector:
1821 case Type::FunctionNoProto:
1822 case Type::Record:
1823 case Type::Enum:
1824 case Type::ObjCObject:
1825 case Type::ObjCInterface:
1826 case Type::ObjCObjectPointer:
1827 case Type::BitInt:
1828 return (TDF & TDF_SkipNonDependent) ||
1829 ((TDF & TDF_IgnoreQualifiers)
1831 : S.Context.hasSameType(P, A))
1834
1835 // _Complex T [placeholder extension]
1836 case Type::Complex: {
1837 const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
1838 if (!CA)
1841 S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
1842 Deduced, TDF, degradeCallPartialOrderingKind(POK),
1843 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1844 }
1845
1846 // _Atomic T [extension]
1847 case Type::Atomic: {
1848 const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
1849 if (!AA)
1852 S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
1853 Deduced, TDF, degradeCallPartialOrderingKind(POK),
1854 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1855 }
1856
1857 // T *
1858 case Type::Pointer: {
1859 QualType PointeeType;
1860 if (const auto *PA = A->getAs<PointerType>()) {
1861 PointeeType = PA->getPointeeType();
1862 } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
1863 PointeeType = PA->getPointeeType();
1864 } else {
1866 }
1868 S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
1869 PointeeType, Info, Deduced,
1872 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1873 }
1874
1875 // T &
1876 case Type::LValueReference: {
1877 const auto *RP = P->castAs<LValueReferenceType>(),
1878 *RA = A->getAs<LValueReferenceType>();
1879 if (!RA)
1881
1883 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1884 Deduced, 0, degradeCallPartialOrderingKind(POK),
1885 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1886 }
1887
1888 // T && [C++0x]
1889 case Type::RValueReference: {
1890 const auto *RP = P->castAs<RValueReferenceType>(),
1891 *RA = A->getAs<RValueReferenceType>();
1892 if (!RA)
1894
1896 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1897 Deduced, 0, degradeCallPartialOrderingKind(POK),
1898 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1899 }
1900
1901 // T [] (implied, but not stated explicitly)
1902 case Type::IncompleteArray: {
1903 const auto *IAA = S.Context.getAsIncompleteArrayType(A);
1904 if (!IAA)
1906
1907 const auto *IAP = S.Context.getAsIncompleteArrayType(P);
1908 assert(IAP && "Template parameter not of incomplete array type");
1909
1911 S, TemplateParams, IAP->getElementType(), IAA->getElementType(), Info,
1912 Deduced, TDF & TDF_IgnoreQualifiers,
1914 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1915 }
1916
1917 // T [integer-constant]
1918 case Type::ConstantArray: {
1919 const auto *CAA = S.Context.getAsConstantArrayType(A),
1921 assert(CAP);
1922 if (!CAA || CAA->getSize() != CAP->getSize())
1924
1926 S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
1927 Deduced, TDF & TDF_IgnoreQualifiers,
1929 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1930 }
1931
1932 // type [i]
1933 case Type::DependentSizedArray: {
1934 const auto *AA = S.Context.getAsArrayType(A);
1935 if (!AA)
1937
1938 // Check the element type of the arrays
1939 const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
1940 assert(DAP);
1942 S, TemplateParams, DAP->getElementType(), AA->getElementType(),
1943 Info, Deduced, TDF & TDF_IgnoreQualifiers,
1945 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1947 return Result;
1948
1949 // Determine the array bound is something we can deduce.
1950 const NonTypeTemplateParmDecl *NTTP =
1951 getDeducedParameterFromExpr(Info, DAP->getSizeExpr());
1952 if (!NTTP)
1954
1955 // We can perform template argument deduction for the given non-type
1956 // template parameter.
1957 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1958 "saw non-type template parameter with wrong depth");
1959 if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
1960 llvm::APSInt Size(CAA->getSize());
1962 S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
1963 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
1964 Deduced, HasDeducedAnyParam);
1965 }
1966 if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
1967 if (DAA->getSizeExpr())
1969 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info,
1970 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
1971
1972 // Incomplete type does not match a dependently-sized array type
1974 }
1975
1976 // type(*)(T)
1977 // T(*)()
1978 // T(*)(T)
1979 case Type::FunctionProto: {
1980 const auto *FPP = P->castAs<FunctionProtoType>(),
1981 *FPA = A->getAs<FunctionProtoType>();
1982 if (!FPA)
1984
1985 if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
1986 FPP->getRefQualifier() != FPA->getRefQualifier() ||
1987 FPP->isVariadic() != FPA->isVariadic())
1989
1990 // Check return types.
1992 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
1993 Info, Deduced, 0, degradeCallPartialOrderingKind(POK),
1994 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1996 return Result;
1997
1998 // Check parameter types.
2000 S, TemplateParams, FPP->param_types(), FPA->param_types(), Info,
2001 Deduced, TDF & TDF_TopLevelParameterTypeList, POK,
2002 HasDeducedAnyParam,
2003 /*HasDeducedParam=*/nullptr);
2005 return Result;
2006
2009
2010 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
2011 // deducing through the noexcept-specifier if it's part of the canonical
2012 // type. libstdc++ relies on this.
2013 Expr *NoexceptExpr = FPP->getNoexceptExpr();
2014 if (const NonTypeTemplateParmDecl *NTTP =
2015 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
2016 : nullptr) {
2017 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
2018 "saw non-type template parameter with wrong depth");
2019
2020 llvm::APSInt Noexcept(1);
2021 switch (FPA->canThrow()) {
2022 case CT_Cannot:
2023 Noexcept = 1;
2024 [[fallthrough]];
2025
2026 case CT_Can:
2027 // We give E in noexcept(E) the "deduced from array bound" treatment.
2028 // FIXME: Should we?
2030 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
2031 /*DeducedFromArrayBound=*/true, Info,
2032 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2033
2034 case CT_Dependent:
2035 if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
2037 S, TemplateParams, NTTP, ArgNoexceptExpr, Info,
2038 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2039 // Can't deduce anything from throw(T...).
2040 break;
2041 }
2042 }
2043 // FIXME: Detect non-deduced exception specification mismatches?
2044 //
2045 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
2046 // top-level differences in noexcept-specifications.
2047
2049 }
2050
2051 case Type::InjectedClassName:
2052 // Treat a template's injected-class-name as if the template
2053 // specialization type had been used.
2054
2055 // template-name<T> (where template-name refers to a class template)
2056 // template-name<i>
2057 // TT<T>
2058 // TT<i>
2059 // TT<>
2060 case Type::TemplateSpecialization: {
2061 // When Arg cannot be a derived class, we can just try to deduce template
2062 // arguments from the template-id.
2063 if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
2064 return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
2065 POK != PartialOrderingKind::None,
2066 Deduced, HasDeducedAnyParam);
2067
2068 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
2069 Deduced.end());
2070
2072 S, TemplateParams, P, A, Info, POK != PartialOrderingKind::None,
2073 Deduced, HasDeducedAnyParam);
2075 return Result;
2076
2077 // We cannot inspect base classes as part of deduction when the type
2078 // is incomplete, so either instantiate any templates necessary to
2079 // complete the type, or skip over it if it cannot be completed.
2080 if (!S.isCompleteType(Info.getLocation(), A))
2081 return Result;
2082
2083 const CXXRecordDecl *RD = A->getAsCXXRecordDecl();
2084 if (RD->isInvalidDecl())
2085 return Result;
2086
2087 // Reset the incorrectly deduced argument from above.
2088 Deduced = DeducedOrig;
2089
2090 // Check bases according to C++14 [temp.deduct.call] p4b3:
2091 auto BaseResult = DeduceTemplateBases(S, RD, TemplateParams, P, Info,
2092 POK != PartialOrderingKind::None,
2093 Deduced, HasDeducedAnyParam);
2095 : Result;
2096 }
2097
2098 // T type::*
2099 // T T::*
2100 // T (type::*)()
2101 // type (T::*)()
2102 // type (type::*)(T)
2103 // type (T::*)(T)
2104 // T (type::*)(T)
2105 // T (T::*)()
2106 // T (T::*)(T)
2107 case Type::MemberPointer: {
2108 const auto *MPP = P->castAs<MemberPointerType>(),
2109 *MPA = A->getAs<MemberPointerType>();
2110 if (!MPA)
2112
2113 QualType PPT = MPP->getPointeeType();
2114 if (PPT->isFunctionType())
2115 S.adjustMemberFunctionCC(PPT, /*HasThisPointer=*/false,
2116 /*IsCtorOrDtor=*/false, Info.getLocation());
2117 QualType APT = MPA->getPointeeType();
2118 if (APT->isFunctionType())
2119 S.adjustMemberFunctionCC(APT, /*HasThisPointer=*/false,
2120 /*IsCtorOrDtor=*/false, Info.getLocation());
2121
2122 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
2124 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF,
2126 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2128 return Result;
2130 S, TemplateParams, QualType(MPP->getClass(), 0),
2131 QualType(MPA->getClass(), 0), Info, Deduced, SubTDF,
2133 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2134 }
2135
2136 // (clang extension)
2137 //
2138 // type(^)(T)
2139 // T(^)()
2140 // T(^)(T)
2141 case Type::BlockPointer: {
2142 const auto *BPP = P->castAs<BlockPointerType>(),
2143 *BPA = A->getAs<BlockPointerType>();
2144 if (!BPA)
2147 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
2148 Deduced, 0, degradeCallPartialOrderingKind(POK),
2149 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2150 }
2151
2152 // (clang extension)
2153 //
2154 // T __attribute__(((ext_vector_type(<integral constant>))))
2155 case Type::ExtVector: {
2156 const auto *VP = P->castAs<ExtVectorType>();
2157 QualType ElementType;
2158 if (const auto *VA = A->getAs<ExtVectorType>()) {
2159 // Make sure that the vectors have the same number of elements.
2160 if (VP->getNumElements() != VA->getNumElements())
2162 ElementType = VA->getElementType();
2163 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2164 // We can't check the number of elements, since the argument has a
2165 // dependent number of elements. This can only occur during partial
2166 // ordering.
2167 ElementType = VA->getElementType();
2168 } else {
2170 }
2171 // Perform deduction on the element types.
2173 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
2175 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2176 }
2177
2178 case Type::DependentVector: {
2179 const auto *VP = P->castAs<DependentVectorType>();
2180
2181 if (const auto *VA = A->getAs<VectorType>()) {
2182 // Perform deduction on the element types.
2184 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2185 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2186 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2188 return Result;
2189
2190 // Perform deduction on the vector size, if we can.
2191 const NonTypeTemplateParmDecl *NTTP =
2192 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2193 if (!NTTP)
2195
2196 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2197 ArgSize = VA->getNumElements();
2198 // Note that we use the "array bound" rules here; just like in that
2199 // case, we don't have any particular type for the vector size, but
2200 // we can provide one if necessary.
2202 S, TemplateParams, NTTP, ArgSize, S.Context.UnsignedIntTy, true,
2203 Info, POK != PartialOrderingKind::None, Deduced,
2204 HasDeducedAnyParam);
2205 }
2206
2207 if (const auto *VA = A->getAs<DependentVectorType>()) {
2208 // Perform deduction on the element types.
2210 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2211 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2212 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2214 return Result;
2215
2216 // Perform deduction on the vector size, if we can.
2217 const NonTypeTemplateParmDecl *NTTP =
2218 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2219 if (!NTTP)
2221
2223 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2224 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2225 }
2226
2228 }
2229
2230 // (clang extension)
2231 //
2232 // T __attribute__(((ext_vector_type(N))))
2233 case Type::DependentSizedExtVector: {
2234 const auto *VP = P->castAs<DependentSizedExtVectorType>();
2235
2236 if (const auto *VA = A->getAs<ExtVectorType>()) {
2237 // Perform deduction on the element types.
2239 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2240 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2241 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2243 return Result;
2244
2245 // Perform deduction on the vector size, if we can.
2246 const NonTypeTemplateParmDecl *NTTP =
2247 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2248 if (!NTTP)
2250
2251 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2252 ArgSize = VA->getNumElements();
2253 // Note that we use the "array bound" rules here; just like in that
2254 // case, we don't have any particular type for the vector size, but
2255 // we can provide one if necessary.
2257 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2258 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2259 }
2260
2261 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2262 // Perform deduction on the element types.
2264 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2265 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2266 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2268 return Result;
2269
2270 // Perform deduction on the vector size, if we can.
2271 const NonTypeTemplateParmDecl *NTTP =
2272 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2273 if (!NTTP)
2275
2277 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2278 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2279 }
2280
2282 }
2283
2284 // (clang extension)
2285 //
2286 // T __attribute__((matrix_type(<integral constant>,
2287 // <integral constant>)))
2288 case Type::ConstantMatrix: {
2289 const auto *MP = P->castAs<ConstantMatrixType>(),
2290 *MA = A->getAs<ConstantMatrixType>();
2291 if (!MA)
2293
2294 // Check that the dimensions are the same
2295 if (MP->getNumRows() != MA->getNumRows() ||
2296 MP->getNumColumns() != MA->getNumColumns()) {
2298 }
2299 // Perform deduction on element types.
2301 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2302 Deduced, TDF, degradeCallPartialOrderingKind(POK),
2303 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2304 }
2305
2306 case Type::DependentSizedMatrix: {
2307 const auto *MP = P->castAs<DependentSizedMatrixType>();
2308 const auto *MA = A->getAs<MatrixType>();
2309 if (!MA)
2311
2312 // Check the element type of the matrixes.
2314 S, TemplateParams, MP->getElementType(), MA->getElementType(),
2315 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2316 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2318 return Result;
2319
2320 // Try to deduce a matrix dimension.
2321 auto DeduceMatrixArg =
2322 [&S, &Info, &Deduced, &TemplateParams, &HasDeducedAnyParam, POK](
2323 Expr *ParamExpr, const MatrixType *A,
2324 unsigned (ConstantMatrixType::*GetArgDimension)() const,
2325 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2326 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2327 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
2328 if (!ParamExpr->isValueDependent()) {
2329 std::optional<llvm::APSInt> ParamConst =
2330 ParamExpr->getIntegerConstantExpr(S.Context);
2331 if (!ParamConst)
2333
2334 if (ACM) {
2335 if ((ACM->*GetArgDimension)() == *ParamConst)
2338 }
2339
2340 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2341 if (std::optional<llvm::APSInt> ArgConst =
2342 ArgExpr->getIntegerConstantExpr(S.Context))
2343 if (*ArgConst == *ParamConst)
2346 }
2347
2348 const NonTypeTemplateParmDecl *NTTP =
2349 getDeducedParameterFromExpr(Info, ParamExpr);
2350 if (!NTTP)
2352
2353 if (ACM) {
2354 llvm::APSInt ArgConst(
2356 ArgConst = (ACM->*GetArgDimension)();
2358 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
2359 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
2360 Deduced, HasDeducedAnyParam);
2361 }
2362
2364 S, TemplateParams, NTTP, (ADM->*GetArgDimensionExpr)(), Info,
2365 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2366 };
2367
2368 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
2372 return Result;
2373
2374 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2377 }
2378
2379 // (clang extension)
2380 //
2381 // T __attribute__(((address_space(N))))
2382 case Type::DependentAddressSpace: {
2383 const auto *ASP = P->castAs<DependentAddressSpaceType>();
2384
2385 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
2386 // Perform deduction on the pointer type.
2388 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2389 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2390 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2392 return Result;
2393
2394 // Perform deduction on the address space, if we can.
2395 const NonTypeTemplateParmDecl *NTTP =
2396 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2397 if (!NTTP)
2399
2401 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info,
2402 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2403 }
2404
2406 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2407 false);
2408 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
2409
2410 // Perform deduction on the pointer types.
2412 S, TemplateParams, ASP->getPointeeType(),
2413 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF,
2415 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2417 return Result;
2418
2419 // Perform deduction on the address space, if we can.
2420 const NonTypeTemplateParmDecl *NTTP =
2421 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2422 if (!NTTP)
2424
2426 S, TemplateParams, NTTP, ArgAddressSpace, S.Context.IntTy, true,
2427 Info, POK != PartialOrderingKind::None, Deduced,
2428 HasDeducedAnyParam);
2429 }
2430
2432 }
2433 case Type::DependentBitInt: {
2434 const auto *IP = P->castAs<DependentBitIntType>();
2435
2436 if (const auto *IA = A->getAs<BitIntType>()) {
2437 if (IP->isUnsigned() != IA->isUnsigned())
2439
2440 const NonTypeTemplateParmDecl *NTTP =
2441 getDeducedParameterFromExpr(Info, IP->getNumBitsExpr());
2442 if (!NTTP)
2444
2445 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2446 ArgSize = IA->getNumBits();
2447
2449 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2450 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2451 }
2452
2453 if (const auto *IA = A->getAs<DependentBitIntType>()) {
2454 if (IP->isUnsigned() != IA->isUnsigned())
2457 }
2458
2460 }
2461
2462 case Type::TypeOfExpr:
2463 case Type::TypeOf:
2464 case Type::DependentName:
2465 case Type::UnresolvedUsing:
2466 case Type::Decltype:
2467 case Type::UnaryTransform:
2468 case Type::DeducedTemplateSpecialization:
2469 case Type::DependentTemplateSpecialization:
2470 case Type::PackExpansion:
2471 case Type::Pipe:
2472 case Type::ArrayParameter:
2473 case Type::HLSLAttributedResource:
2474 // No template argument deduction for these types
2476
2477 case Type::PackIndexing: {
2478 const PackIndexingType *PIT = P->getAs<PackIndexingType>();
2479 if (PIT->hasSelectedType()) {
2481 S, TemplateParams, PIT->getSelectedType(), A, Info, Deduced, TDF,
2483 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2484 }
2486 }
2487 }
2488
2489 llvm_unreachable("Invalid Type Class!");
2490}
2491
2497 bool *HasDeducedAnyParam) {
2498 // If the template argument is a pack expansion, perform template argument
2499 // deduction against the pattern of that expansion. This only occurs during
2500 // partial ordering.
2501 if (A.isPackExpansion())
2503
2504 switch (P.getKind()) {
2506 llvm_unreachable("Null template argument in parameter list");
2507
2511 S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0,
2512 PartialOrdering ? PartialOrderingKind::NonCall
2513 : PartialOrderingKind::None,
2514 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2515 Info.FirstArg = P;
2516 Info.SecondArg = A;
2518
2520 // PartialOrdering does not matter here, since template specializations are
2521 // not being deduced.
2524 S, TemplateParams, P.getAsTemplate(), A.getAsTemplate(), Info,
2525 /*DefaultArguments=*/{}, /*PartialOrdering=*/false, Deduced,
2526 HasDeducedAnyParam);
2527 Info.FirstArg = P;
2528 Info.SecondArg = A;
2530
2532 llvm_unreachable("caller should handle pack expansions");
2533
2536 isSameDeclaration(P.getAsDecl(), A.getAsDecl()))
2538
2539 Info.FirstArg = P;
2540 Info.SecondArg = A;
2542
2545 S.Context.hasSameType(P.getNullPtrType(), A.getNullPtrType()))
2547
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
2565
2566 Info.FirstArg = P;
2567 Info.SecondArg = A;
2569
2571 if (const NonTypeTemplateParmDecl *NTTP =
2572 getDeducedParameterFromExpr(Info, P.getAsExpr())) {
2573 switch (A.getKind()) {
2575 const Expr *E = A.getAsExpr();
2576 // When checking NTTP, if either the parameter or the argument is
2577 // dependent, as there would be otherwise nothing to deduce, we force
2578 // the argument to the parameter type using this dependent implicit
2579 // cast, in order to maintain invariants. Now we can deduce the
2580 // resulting type from the original type, and deduce the original type
2581 // against the parameter we are checking.
2582 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
2583 ICE && ICE->getCastKind() == clang::CK_Dependent) {
2584 E = ICE->getSubExpr();
2586 S, TemplateParams, ICE->getType(), E->getType(), Info,
2587 Deduced, TDF_SkipNonDependent,
2588 PartialOrdering ? PartialOrderingKind::NonCall
2589 : PartialOrderingKind::None,
2590 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2592 return Result;
2593 }
2595 S, TemplateParams, NTTP, DeducedTemplateArgument(A), E->getType(),
2596 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
2597 }
2601 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2603 HasDeducedAnyParam);
2604
2607 S, TemplateParams, NTTP, A.getNullPtrType(), Info, PartialOrdering,
2608 Deduced, HasDeducedAnyParam);
2609
2612 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
2613 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
2614
2620 Info.FirstArg = P;
2621 Info.SecondArg = A;
2623 }
2624 llvm_unreachable("Unknown template argument kind");
2625 }
2626
2627 // Can't deduce anything, but that's okay.
2630 llvm_unreachable("Argument packs should be expanded by the caller!");
2631 }
2632
2633 llvm_unreachable("Invalid TemplateArgument Kind!");
2634}
2635
2636/// Determine whether there is a template argument to be used for
2637/// deduction.
2638///
2639/// This routine "expands" argument packs in-place, overriding its input
2640/// parameters so that \c Args[ArgIdx] will be the available template argument.
2641///
2642/// \returns true if there is another template argument (which will be at
2643/// \c Args[ArgIdx]), false otherwise.
2645 unsigned &ArgIdx) {
2646 if (ArgIdx == Args.size())
2647 return false;
2648
2649 const TemplateArgument &Arg = Args[ArgIdx];
2650 if (Arg.getKind() != TemplateArgument::Pack)
2651 return true;
2652
2653 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2654 Args = Arg.pack_elements();
2655 ArgIdx = 0;
2656 return ArgIdx < Args.size();
2657}
2658
2659/// Determine whether the given set of template arguments has a pack
2660/// expansion that is not the last template argument.
2662 bool FoundPackExpansion = false;
2663 for (const auto &A : Args) {
2664 if (FoundPackExpansion)
2665 return true;
2666
2667 if (A.getKind() == TemplateArgument::Pack)
2668 return hasPackExpansionBeforeEnd(A.pack_elements());
2669
2670 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2671 // templates, it should not be treated as a pack expansion.
2672 if (A.isPackExpansion())
2673 FoundPackExpansion = true;
2674 }
2675
2676 return false;
2677}
2678
2685 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
2686 PackFold PackFold, bool *HasDeducedAnyParam) {
2687 bool FoldPackParameter = PackFold == PackFold::ParameterToArgument ||
2688 PackFold == PackFold::Both,
2689 FoldPackArgument = PackFold == PackFold::ArgumentToParameter ||
2690 PackFold == PackFold::Both;
2691
2692 // C++0x [temp.deduct.type]p9:
2693 // If the template argument list of P contains a pack expansion that is not
2694 // the last template argument, the entire template argument list is a
2695 // non-deduced context.
2696 if (FoldPackParameter && hasPackExpansionBeforeEnd(Ps))
2698
2699 // C++0x [temp.deduct.type]p9:
2700 // If P has a form that contains <T> or <i>, then each argument Pi of the
2701 // respective template argument list P is compared with the corresponding
2702 // argument Ai of the corresponding template argument list of A.
2703 for (unsigned ArgIdx = 0, ParamIdx = 0; /**/; /**/) {
2705 return !FoldPackParameter && hasTemplateArgumentForDeduction(As, ArgIdx)
2708
2709 if (!Ps[ParamIdx].isPackExpansion()) {
2710 // The simple case: deduce template arguments by matching Pi and Ai.
2711
2712 // Check whether we have enough arguments.
2713 if (!hasTemplateArgumentForDeduction(As, ArgIdx))
2714 return !FoldPackArgument && NumberOfArgumentsMustMatch
2717
2718 if (As[ArgIdx].isPackExpansion()) {
2719 // C++1z [temp.deduct.type]p9:
2720 // During partial ordering, if Ai was originally a pack expansion
2721 // [and] Pi is not a pack expansion, template argument deduction
2722 // fails.
2723 if (!FoldPackArgument)
2725
2726 TemplateArgument Pattern = As[ArgIdx].getPackExpansionPattern();
2727 for (;;) {
2728 // Deduce template parameters from the pattern.
2730 S, TemplateParams, Ps[ParamIdx], Pattern, Info,
2731 PartialOrdering, Deduced, HasDeducedAnyParam);
2733 return Result;
2734
2735 ++ParamIdx;
2738 if (Ps[ParamIdx].isPackExpansion())
2739 break;
2740 }
2741 } else {
2742 // Perform deduction for this Pi/Ai pair.
2744 S, TemplateParams, Ps[ParamIdx], As[ArgIdx], Info,
2745 PartialOrdering, Deduced, HasDeducedAnyParam);
2747 return Result;
2748
2749 ++ArgIdx;
2750 ++ParamIdx;
2751 continue;
2752 }
2753 }
2754
2755 // The parameter is a pack expansion.
2756
2757 // C++0x [temp.deduct.type]p9:
2758 // If Pi is a pack expansion, then the pattern of Pi is compared with
2759 // each remaining argument in the template argument list of A. Each
2760 // comparison deduces template arguments for subsequent positions in the
2761 // template parameter packs expanded by Pi.
2762 TemplateArgument Pattern = Ps[ParamIdx].getPackExpansionPattern();
2763
2764 // Prepare to deduce the packs within the pattern.
2765 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2766
2767 // Keep track of the deduced template arguments for each parameter pack
2768 // expanded by this pack expansion (the outer index) and for each
2769 // template argument (the inner SmallVectors).
2770 for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
2771 PackScope.hasNextElement();
2772 ++ArgIdx) {
2773 if (!As[ArgIdx].isPackExpansion()) {
2774 if (!FoldPackParameter)
2776 if (FoldPackArgument)
2778 }
2779 // Deduce template arguments from the pattern.
2781 S, TemplateParams, Pattern, As[ArgIdx], Info, PartialOrdering,
2782 Deduced, HasDeducedAnyParam);
2784 return Result;
2785
2786 PackScope.nextPackElement();
2787 }
2788
2789 // Build argument packs for each of the parameter packs expanded by this
2790 // pack expansion.
2791 return PackScope.finish();
2792 }
2793}
2794
2799 bool NumberOfArgumentsMustMatch) {
2800 return ::DeduceTemplateArguments(
2801 *this, TemplateParams, Ps, As, Info, Deduced, NumberOfArgumentsMustMatch,
2802 /*PartialOrdering=*/false, PackFold::ParameterToArgument,
2803 /*HasDeducedAnyParam=*/nullptr);
2804}
2805
2806/// Determine whether two template arguments are the same.
2807static bool isSameTemplateArg(ASTContext &Context,
2809 const TemplateArgument &Y,
2810 bool PartialOrdering,
2811 bool PackExpansionMatchesPack = false) {
2812 // If we're checking deduced arguments (X) against original arguments (Y),
2813 // we will have flattened packs to non-expansions in X.
2814 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2815 X = X.getPackExpansionPattern();
2816
2817 if (X.getKind() != Y.getKind())
2818 return false;
2819
2820 switch (X.getKind()) {
2822 llvm_unreachable("Comparing NULL template argument");
2823
2825 return Context.getCanonicalType(X.getAsType()) ==
2826 Context.getCanonicalType(Y.getAsType());
2827
2829 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
2830
2832 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2833
2836 return Context.getCanonicalTemplateName(
2837 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2840
2842 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2843
2845 return X.structurallyEquals(Y);
2846
2848 llvm::FoldingSetNodeID XID, YID;
2849 X.getAsExpr()->Profile(XID, Context, true);
2850 Y.getAsExpr()->Profile(YID, Context, true);
2851 return XID == YID;
2852 }
2853
2855 unsigned PackIterationSize = X.pack_size();
2856 if (X.pack_size() != Y.pack_size()) {
2857 if (!PartialOrdering)
2858 return false;
2859
2860 // C++0x [temp.deduct.type]p9:
2861 // During partial ordering, if Ai was originally a pack expansion:
2862 // - if P does not contain a template argument corresponding to Ai
2863 // then Ai is ignored;
2864 bool XHasMoreArg = X.pack_size() > Y.pack_size();
2865 if (!(XHasMoreArg && X.pack_elements().back().isPackExpansion()) &&
2866 !(!XHasMoreArg && Y.pack_elements().back().isPackExpansion()))
2867 return false;
2868
2869 if (XHasMoreArg)
2870 PackIterationSize = Y.pack_size();
2871 }
2872
2873 ArrayRef<TemplateArgument> XP = X.pack_elements();
2875 for (unsigned i = 0; i < PackIterationSize; ++i)
2876 if (!isSameTemplateArg(Context, XP[i], YP[i], PartialOrdering,
2877 PackExpansionMatchesPack))
2878 return false;
2879 return true;
2880 }
2881 }
2882
2883 llvm_unreachable("Invalid TemplateArgument Kind!");
2884}
2885
2888 QualType NTTPType, SourceLocation Loc,
2890 switch (Arg.getKind()) {
2892 llvm_unreachable("Can't get a NULL template argument here");
2893
2895 return TemplateArgumentLoc(
2897
2899 if (NTTPType.isNull())
2900 NTTPType = Arg.getParamTypeForDecl();
2903 .getAs<Expr>();
2905 }
2906
2908 if (NTTPType.isNull())
2909 NTTPType = Arg.getNullPtrType();
2911 .getAs<Expr>();
2912 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2913 E);
2914 }
2915
2920 }
2921
2927 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2928 else if (QualifiedTemplateName *QTN =
2929 Template.getAsQualifiedTemplateName())
2930 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2931
2933 return TemplateArgumentLoc(Context, Arg,
2934 Builder.getWithLocInContext(Context), Loc);
2935
2936 return TemplateArgumentLoc(
2937 Context, Arg, Builder.getWithLocInContext(Context), Loc, Loc);
2938 }
2939
2941 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2942
2945 }
2946
2947 llvm_unreachable("Invalid TemplateArgument Kind!");
2948}
2949
2952 SourceLocation Location) {
2954 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2955}
2956
2957/// Convert the given deduced template argument and add it to the set of
2958/// fully-converted template arguments.
2960 Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template,
2961 TemplateDeductionInfo &Info, bool IsDeduced, bool PartialOrdering,
2962 SmallVectorImpl<TemplateArgument> &SugaredOutput,
2963 SmallVectorImpl<TemplateArgument> &CanonicalOutput) {
2964 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2965 unsigned ArgumentPackIndex) {
2966 // Convert the deduced template argument into a template
2967 // argument that we can check, almost as if the user had written
2968 // the template argument explicitly.
2970 Arg, QualType(), Info.getLocation(), Param);
2971
2972 bool MatchedPackOnParmToNonPackOnArg = false;
2973 // Check the template argument, converting it as necessary.
2974 auto Res = S.CheckTemplateArgument(
2975 Param, ArgLoc, Template, Template->getLocation(),
2976 Template->getSourceRange().getEnd(), ArgumentPackIndex, SugaredOutput,
2977 CanonicalOutput,
2978 IsDeduced
2982 PartialOrdering, &MatchedPackOnParmToNonPackOnArg);
2983 if (MatchedPackOnParmToNonPackOnArg)
2985 return Res;
2986 };
2987
2988 if (Arg.getKind() == TemplateArgument::Pack) {
2989 // This is a template argument pack, so check each of its arguments against
2990 // the template parameter.
2991 SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
2992 CanonicalPackedArgsBuilder;
2993 for (const auto &P : Arg.pack_elements()) {
2994 // When converting the deduced template argument, append it to the
2995 // general output list. We need to do this so that the template argument
2996 // checking logic has all of the prior template arguments available.
2997 DeducedTemplateArgument InnerArg(P);
2999 assert(InnerArg.getKind() != TemplateArgument::Pack &&
3000 "deduced nested pack");
3001 if (P.isNull()) {
3002 // We deduced arguments for some elements of this pack, but not for
3003 // all of them. This happens if we get a conditionally-non-deduced
3004 // context in a pack expansion (such as an overload set in one of the
3005 // arguments).
3006 S.Diag(Param->getLocation(),
3007 diag::err_template_arg_deduced_incomplete_pack)
3008 << Arg << Param;
3009 return true;
3010 }
3011 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
3012 return true;
3013
3014 // Move the converted template argument into our argument pack.
3015 SugaredPackedArgsBuilder.push_back(SugaredOutput.pop_back_val());
3016 CanonicalPackedArgsBuilder.push_back(CanonicalOutput.pop_back_val());
3017 }
3018
3019 // If the pack is empty, we still need to substitute into the parameter
3020 // itself, in case that substitution fails.
3021 if (SugaredPackedArgsBuilder.empty()) {
3023 MultiLevelTemplateArgumentList Args(Template, SugaredOutput,
3024 /*Final=*/true);
3025
3026 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3027 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
3028 NTTP, SugaredOutput,
3029 Template->getSourceRange());
3030 if (Inst.isInvalid() ||
3031 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
3032 NTTP->getDeclName()).isNull())
3033 return true;
3034 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3035 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
3036 TTP, SugaredOutput,
3037 Template->getSourceRange());
3038 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
3039 return true;
3040 }
3041 // For type parameters, no substitution is ever required.
3042 }
3043
3044 // Create the resulting argument pack.
3045 SugaredOutput.push_back(
3046 TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
3047 CanonicalOutput.push_back(TemplateArgument::CreatePackCopy(
3048 S.Context, CanonicalPackedArgsBuilder));
3049 return false;
3050 }
3051
3052 return ConvertArg(Arg, 0);
3053}
3054
3055// FIXME: This should not be a template, but
3056// ClassTemplatePartialSpecializationDecl sadly does not derive from
3057// TemplateDecl.
3058/// \param IsIncomplete When used, we only consider template parameters that
3059/// were deduced, disregarding any default arguments. After the function
3060/// finishes, the object pointed at will contain a value indicating if the
3061/// conversion was actually incomplete.
3062template <typename TemplateDeclT>
3064 Sema &S, TemplateDeclT *Template, bool IsDeduced,
3067 SmallVectorImpl<TemplateArgument> &SugaredBuilder,
3068 SmallVectorImpl<TemplateArgument> &CanonicalBuilder, bool PartialOrdering,
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 SugaredBuilder.push_back(Deduced[I]);
3104 CanonicalBuilder.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, PartialOrdering,
3114 SugaredBuilder, CanonicalBuilder)) {
3115 Info.Param = makeTemplateParameter(Param);
3116 // FIXME: These template arguments are temporary. Free them!
3117 Info.reset(
3118 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3119 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
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 SugaredBuilder.push_back({});
3134 CanonicalBuilder.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 SugaredBuilder, CanonicalBuilder, 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(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3171 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3172
3175 }
3176
3177 // Check whether we can actually use the default argument.
3179 Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
3180 /*ArgumentPackIndex=*/0, SugaredBuilder, CanonicalBuilder,
3181 Sema::CTAK_Specified, /*PartialOrdering=*/false,
3182 /*MatchedPackOnParmToNonPackOnArg=*/nullptr)) {
3184 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
3185 // FIXME: These template arguments are temporary. Free them!
3186 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3187 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3189 }
3190
3191 // If we get here, we successfully used the default template argument.
3192 }
3193
3195}
3196
3198 if (auto *DC = dyn_cast<DeclContext>(D))
3199 return DC;
3200 return D->getDeclContext();
3201}
3202
3203template<typename T> struct IsPartialSpecialization {
3204 static constexpr bool value = false;
3205};
3206template<>
3208 static constexpr bool value = true;
3209};
3210template<>
3212 static constexpr bool value = true;
3213};
3214template <typename TemplateDeclT>
3215static bool DeducedArgsNeedReplacement(TemplateDeclT *Template) {
3216 return false;
3217}
3218template <>
3221 return !Spec->isClassScopeExplicitSpecialization();
3222}
3223template <>
3226 return !Spec->isClassScopeExplicitSpecialization();
3227}
3228
3229template <typename TemplateDeclT>
3231CheckDeducedArgumentConstraints(Sema &S, TemplateDeclT *Template,
3232 ArrayRef<TemplateArgument> SugaredDeducedArgs,
3233 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
3234 TemplateDeductionInfo &Info) {
3235 llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
3236 Template->getAssociatedConstraints(AssociatedConstraints);
3237
3238 std::optional<ArrayRef<TemplateArgument>> Innermost;
3239 // If we don't need to replace the deduced template arguments,
3240 // we can add them immediately as the inner-most argument list.
3241 if (!DeducedArgsNeedReplacement(Template))
3242 Innermost = CanonicalDeducedArgs;
3243
3245 Template, Template->getDeclContext(), /*Final=*/false, Innermost,
3246 /*RelativeToPrimary=*/true, /*Pattern=*/
3247 nullptr, /*ForConstraintInstantiation=*/true);
3248
3249 // getTemplateInstantiationArgs picks up the non-deduced version of the
3250 // template args when this is a variable template partial specialization and
3251 // not class-scope explicit specialization, so replace with Deduced Args
3252 // instead of adding to inner-most.
3253 if (!Innermost)
3254 MLTAL.replaceInnermostTemplateArguments(Template, CanonicalDeducedArgs);
3255
3256 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
3257 Info.getLocation(),
3260 Info.reset(
3261 TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
3262 TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
3264 }
3266}
3267
3268/// Complete template argument deduction for a partial specialization.
3269template <typename T>
3270static std::enable_if_t<IsPartialSpecialization<T>::value,
3273 Sema &S, T *Partial, bool IsPartialOrdering,
3274 ArrayRef<TemplateArgument> TemplateArgs,
3276 TemplateDeductionInfo &Info) {
3277 // Unevaluated SFINAE context.
3280 Sema::SFINAETrap Trap(S);
3281
3282 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
3283
3284 // C++ [temp.deduct.type]p2:
3285 // [...] or if any template argument remains neither deduced nor
3286 // explicitly specified, template argument deduction fails.
3287 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3289 S, Partial, IsPartialOrdering, Deduced, Info, SugaredBuilder,
3290 CanonicalBuilder, IsPartialOrdering,
3291 /*CurrentInstantiationScope=*/nullptr, /*NumAlreadyConverted=*/0,
3292 /*IsIncomplete=*/nullptr);
3294 return Result;
3295
3296 // Form the template argument list from the deduced template arguments.
3297 TemplateArgumentList *SugaredDeducedArgumentList =
3298 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
3299 TemplateArgumentList *CanonicalDeducedArgumentList =
3300 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
3301
3302 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3303
3304 // Substitute the deduced template arguments into the template
3305 // arguments of the class template partial specialization, and
3306 // verify that the instantiated template arguments are both valid
3307 // and are equivalent to the template arguments originally provided
3308 // to the class template.
3309 LocalInstantiationScope InstScope(S);
3310 auto *Template = Partial->getSpecializedTemplate();
3311 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
3312 Partial->getTemplateArgsAsWritten();
3313
3314 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
3315 PartialTemplArgInfo->RAngleLoc);
3316
3317 if (S.SubstTemplateArguments(PartialTemplArgInfo->arguments(),
3319 SugaredBuilder,
3320 /*Final=*/true),
3321 InstArgs)) {
3322 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
3323 if (ParamIdx >= Partial->getTemplateParameters()->size())
3324 ParamIdx = Partial->getTemplateParameters()->size() - 1;
3325
3326 Decl *Param = const_cast<NamedDecl *>(
3327 Partial->getTemplateParameters()->getParam(ParamIdx));
3328 Info.Param = makeTemplateParameter(Param);
3329 Info.FirstArg = (*PartialTemplArgInfo)[ArgIdx].getArgument();
3331 }
3332
3333 bool MatchedPackOnParmToNonPackOnArg = false;
3335 SmallVector<TemplateArgument, 4> SugaredConvertedInstArgs,
3336 CanonicalConvertedInstArgs;
3338 Template, Partial->getLocation(), InstArgs, /*DefaultArgs=*/{}, false,
3339 SugaredConvertedInstArgs, CanonicalConvertedInstArgs,
3340 /*UpdateArgsWithConversions=*/true, &ConstraintsNotSatisfied,
3341 /*PartialOrderingTTP=*/false, &MatchedPackOnParmToNonPackOnArg))
3345 if (MatchedPackOnParmToNonPackOnArg)
3347
3348 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3349 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3350 TemplateArgument InstArg = SugaredConvertedInstArgs.data()[I];
3351 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
3352 IsPartialOrdering)) {
3353 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3354 Info.FirstArg = TemplateArgs[I];
3355 Info.SecondArg = InstArg;
3357 }
3358 }
3359
3360 if (Trap.hasErrorOccurred())
3362
3363 if (!IsPartialOrdering) {
3365 S, Partial, SugaredBuilder, CanonicalBuilder, Info);
3367 return Result;
3368 }
3369
3371}
3372
3373/// Complete template argument deduction for a class or variable template,
3374/// when partial ordering against a partial specialization.
3375// FIXME: Factor out duplication with partial specialization version above.
3377 Sema &S, TemplateDecl *Template, bool PartialOrdering,
3378 ArrayRef<TemplateArgument> TemplateArgs,
3380 TemplateDeductionInfo &Info) {
3381 // Unevaluated SFINAE context.
3384
3385 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
3386
3387 // C++ [temp.deduct.type]p2:
3388 // [...] or if any template argument remains neither deduced nor
3389 // explicitly specified, template argument deduction fails.
3390 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3392 S, Template, /*IsDeduced=*/PartialOrdering, Deduced, Info,
3393 SugaredBuilder, CanonicalBuilder, PartialOrdering,
3394 /*CurrentInstantiationScope=*/nullptr,
3395 /*NumAlreadyConverted=*/0U, /*IsIncomplete=*/nullptr);
3397 return Result;
3398
3399 // Check that we produced the correct argument list.
3400 SmallVector<ArrayRef<TemplateArgument>, 4> PsStack{TemplateArgs},
3401 AsStack{CanonicalBuilder};
3402 for (;;) {
3403 auto take = [](SmallVectorImpl<ArrayRef<TemplateArgument>> &Stack)
3405 while (!Stack.empty()) {
3406 auto &Xs = Stack.back();
3407 if (Xs.empty()) {
3408 Stack.pop_back();
3409 continue;
3410 }
3411 auto &X = Xs.front();
3412 if (X.getKind() == TemplateArgument::Pack) {
3413 Stack.emplace_back(X.getPackAsArray());
3414 Xs = Xs.drop_front();
3415 continue;
3416 }
3417 assert(!X.isNull());
3418 return {Xs, X};
3419 }
3420 static constexpr ArrayRef<TemplateArgument> None;
3421 return {const_cast<ArrayRef<TemplateArgument> &>(None),
3423 };
3424 auto [Ps, P] = take(PsStack);
3425 auto [As, A] = take(AsStack);
3426 if (P.isNull() && A.isNull())
3427 break;
3428 TemplateArgument PP = P.isPackExpansion() ? P.getPackExpansionPattern() : P,
3429 PA = A.isPackExpansion() ? A.getPackExpansionPattern() : A;
3430 if (!isSameTemplateArg(S.Context, PP, PA, /*PartialOrdering=*/false)) {
3431 if (!P.isPackExpansion() && !A.isPackExpansion()) {
3432 Info.Param =
3434 (PsStack.empty() ? TemplateArgs.end()
3435 : PsStack.front().begin()) -
3436 TemplateArgs.begin()));
3437 Info.FirstArg = P;
3438 Info.SecondArg = A;
3440 }
3441 if (P.isPackExpansion()) {
3442 Ps = Ps.drop_front();
3443 continue;
3444 }
3445 if (A.isPackExpansion()) {
3446 As = As.drop_front();
3447 continue;
3448 }
3449 }
3450 Ps = Ps.drop_front(P.isPackExpansion() ? 0 : 1);
3451 As = As.drop_front(A.isPackExpansion() && !P.isPackExpansion() ? 0 : 1);
3452 }
3453 assert(PsStack.empty());
3454 assert(AsStack.empty());
3455
3456 if (!PartialOrdering) {
3458 S, Template, SugaredBuilder, CanonicalBuilder, Info);
3460 return Result;
3461 }
3462
3464}
3465
3466/// Complete template argument deduction for DeduceTemplateArgumentsFromType.
3467/// FIXME: this is mostly duplicated with the above two versions. Deduplicate
3468/// the three implementations.
3470 Sema &S, TemplateDecl *TD,
3472 TemplateDeductionInfo &Info) {
3473 // Unevaluated SFINAE context.
3476
3478
3479 // C++ [temp.deduct.type]p2:
3480 // [...] or if any template argument remains neither deduced nor
3481 // explicitly specified, template argument deduction fails.
3482 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3484 S, TD, /*IsDeduced=*/false, Deduced, Info, SugaredBuilder,
3485 CanonicalBuilder, /*PartialOrdering=*/false,
3486 /*CurrentInstantiationScope=*/nullptr, /*NumAlreadyConverted=*/0,
3487 /*IsIncomplete=*/nullptr);
3489 return Result;
3490
3491 return ::CheckDeducedArgumentConstraints(S, TD, SugaredBuilder,
3492 CanonicalBuilder, Info);
3493}
3494
3495/// Perform template argument deduction to determine whether the given template
3496/// arguments match the given class or variable template partial specialization
3497/// per C++ [temp.class.spec.match].
3498template <typename T>
3499static std::enable_if_t<IsPartialSpecialization<T>::value,
3502 ArrayRef<TemplateArgument> TemplateArgs,
3503 TemplateDeductionInfo &Info) {
3504 if (Partial->isInvalidDecl())
3506
3507 // C++ [temp.class.spec.match]p2:
3508 // A partial specialization matches a given actual template
3509 // argument list if the template arguments of the partial
3510 // specialization can be deduced from the actual template argument
3511 // list (14.8.2).
3512
3513 // Unevaluated SFINAE context.
3516 Sema::SFINAETrap Trap(S);
3517
3518 // This deduction has no relation to any outer instantiation we might be
3519 // performing.
3520 LocalInstantiationScope InstantiationScope(S);
3521
3523 Deduced.resize(Partial->getTemplateParameters()->size());
3525 S, Partial->getTemplateParameters(),
3526 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3527 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/false,
3528 PackFold::ParameterToArgument,
3529 /*HasDeducedAnyParam=*/nullptr);
3531 return Result;
3532
3533 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3534 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs,
3535 Info);
3536 if (Inst.isInvalid())
3538
3541 Result = ::FinishTemplateArgumentDeduction(S, Partial,
3542 /*IsPartialOrdering=*/false,
3543 TemplateArgs, Deduced, Info);
3544 });
3545
3547 return Result;
3548
3549 if (Trap.hasErrorOccurred())
3551
3553}
3554
3557 ArrayRef<TemplateArgument> TemplateArgs,
3558 TemplateDeductionInfo &Info) {
3559 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3560}
3563 ArrayRef<TemplateArgument> TemplateArgs,
3564 TemplateDeductionInfo &Info) {
3565 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3566}
3567
3571 if (TD->isInvalidDecl())
3573
3574 QualType PType;
3575 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
3576 // Use the InjectedClassNameType.
3577 PType = Context.getTypeDeclType(CTD->getTemplatedDecl());
3578 } else if (const auto *AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(TD)) {
3579 PType = AliasTemplate->getTemplatedDecl()->getUnderlyingType();
3580 } else {
3581 assert(false && "Expected a class or alias template");
3582 }
3583
3584 // Unevaluated SFINAE context.
3587 SFINAETrap Trap(*this);
3588
3589 // This deduction has no relation to any outer instantiation we might be
3590 // performing.
3591 LocalInstantiationScope InstantiationScope(*this);
3592
3594 TD->getTemplateParameters()->size());
3597 if (auto DeducedResult = DeduceTemplateArguments(
3598 TD->getTemplateParameters(), PArgs, AArgs, Info, Deduced, false);
3599 DeducedResult != TemplateDeductionResult::Success) {
3600 return DeducedResult;
3601 }
3602
3603 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3604 InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs, Info);
3605 if (Inst.isInvalid())
3607
3610 Result = ::FinishTemplateArgumentDeduction(*this, TD, Deduced, Info);
3611 });
3612
3614 return Result;
3615
3616 if (Trap.hasErrorOccurred())
3618
3620}
3621
3622/// Determine whether the given type T is a simple-template-id type.
3624 if (const TemplateSpecializationType *Spec
3626 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
3627
3628 // C++17 [temp.local]p2:
3629 // the injected-class-name [...] is equivalent to the template-name followed
3630 // by the template-arguments of the class template specialization or partial
3631 // specialization enclosed in <>
3632 // ... which means it's equivalent to a simple-template-id.
3633 //
3634 // This only arises during class template argument deduction for a copy
3635 // deduction candidate, where it permits slicing.
3637 return true;
3638
3639 return false;
3640}
3641
3643 FunctionTemplateDecl *FunctionTemplate,
3644 TemplateArgumentListInfo &ExplicitTemplateArgs,
3647 TemplateDeductionInfo &Info) {
3648 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3649 TemplateParameterList *TemplateParams
3650 = FunctionTemplate->getTemplateParameters();
3651
3652 if (ExplicitTemplateArgs.size() == 0) {
3653 // No arguments to substitute; just copy over the parameter types and
3654 // fill in the function type.
3655 for (auto *P : Function->parameters())
3656 ParamTypes.push_back(P->getType());
3657
3658 if (FunctionType)
3659 *FunctionType = Function->getType();
3661 }
3662
3663 // Unevaluated SFINAE context.
3666 SFINAETrap Trap(*this);
3667
3668 // C++ [temp.arg.explicit]p3:
3669 // Template arguments that are present shall be specified in the
3670 // declaration order of their corresponding template-parameters. The
3671 // template argument list shall not specify more template-arguments than
3672 // there are corresponding template-parameters.
3673 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3674
3675 // Enter a new template instantiation context where we check the
3676 // explicitly-specified template arguments against this function template,
3677 // and then substitute them into the function parameter types.
3680 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3682 if (Inst.isInvalid())
3684
3686 ExplicitTemplateArgs, /*DefaultArgs=*/{}, true,
3687 SugaredBuilder, CanonicalBuilder,
3688 /*UpdateArgsWithConversions=*/false) ||
3689 Trap.hasErrorOccurred()) {
3690 unsigned Index = SugaredBuilder.size();
3691 if (Index >= TemplateParams->size())
3693 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3695 }
3696
3697 // Form the template argument list from the explicitly-specified
3698 // template arguments.
3699 TemplateArgumentList *SugaredExplicitArgumentList =
3701 TemplateArgumentList *CanonicalExplicitArgumentList =
3702 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3703 Info.setExplicitArgs(SugaredExplicitArgumentList,
3704 CanonicalExplicitArgumentList);
3705
3706 // Template argument deduction and the final substitution should be
3707 // done in the context of the templated declaration. Explicit
3708 // argument substitution, on the other hand, needs to happen in the
3709 // calling context.
3710 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3711
3712 // If we deduced template arguments for a template parameter pack,
3713 // note that the template argument pack is partially substituted and record
3714 // the explicit template arguments. They'll be used as part of deduction
3715 // for this template parameter pack.
3716 unsigned PartiallySubstitutedPackIndex = -1u;
3717 if (!SugaredBuilder.empty()) {
3718 const TemplateArgument &Arg = SugaredBuilder.back();
3719 if (Arg.getKind() == TemplateArgument::Pack) {
3720 auto *Param = TemplateParams->getParam(SugaredBuilder.size() - 1);
3721 // If this is a fully-saturated fixed-size pack, it should be
3722 // fully-substituted, not partially-substituted.
3723 std::optional<unsigned> Expansions = getExpandedPackSize(Param);
3724 if (!Expansions || Arg.pack_size() < *Expansions) {
3725 PartiallySubstitutedPackIndex = SugaredBuilder.size() - 1;
3727 Param, Arg.pack_begin(), Arg.pack_size());
3728 }
3729 }
3730 }
3731
3732 const FunctionProtoType *Proto
3733 = Function->getType()->getAs<FunctionProtoType>();
3734 assert(Proto && "Function template does not have a prototype?");
3735
3736 // Isolate our substituted parameters from our caller.
3737 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3738
3739 ExtParameterInfoBuilder ExtParamInfos;
3740
3742 SugaredExplicitArgumentList->asArray(),
3743 /*Final=*/true);
3744
3745 // Instantiate the types of each of the function parameters given the
3746 // explicitly-specified template arguments. If the function has a trailing
3747 // return type, substitute it after the arguments to ensure we substitute
3748 // in lexical order.
3749 if (Proto->hasTrailingReturn()) {
3750 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3751 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3752 /*params=*/nullptr, ExtParamInfos))
3754 }
3755
3756 // Instantiate the return type.
3757 QualType ResultType;
3758 {
3759 // C++11 [expr.prim.general]p3:
3760 // If a declaration declares a member function or member function
3761 // template of a class X, the expression this is a prvalue of type
3762 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3763 // and the end of the function-definition, member-declarator, or
3764 // declarator.
3765 Qualifiers ThisTypeQuals;
3766 CXXRecordDecl *ThisContext = nullptr;
3767 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3768 ThisContext = Method->getParent();
3769 ThisTypeQuals = Method->getMethodQualifiers();
3770 }
3771
3772 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3774
3775 ResultType =
3776 SubstType(Proto->getReturnType(), MLTAL,
3777 Function->getTypeSpecStartLoc(), Function->getDeclName());
3778 if (ResultType.isNull() || Trap.hasErrorOccurred())
3780 // CUDA: Kernel function must have 'void' return type.
3781 if (getLangOpts().CUDA)
3782 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3783 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3784 << Function->getType() << Function->getSourceRange();
3786 }
3787 }
3788
3789 // Instantiate the types of each of the function parameters given the
3790 // explicitly-specified template arguments if we didn't do so earlier.
3791 if (!Proto->hasTrailingReturn() &&
3792 SubstParmTypes(Function->getLocation(), Function->parameters(),
3793 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3794 /*params*/ nullptr, ExtParamInfos))
3796
3797 if (FunctionType) {
3798 auto EPI = Proto->getExtProtoInfo();
3799 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3800 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3801 Function->getLocation(),
3802 Function->getDeclName(),
3803 EPI);
3804 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3806 }
3807
3808 // C++ [temp.arg.explicit]p2:
3809 // Trailing template arguments that can be deduced (14.8.2) may be
3810 // omitted from the list of explicit template-arguments. If all of the
3811 // template arguments can be deduced, they may all be omitted; in this
3812 // case, the empty template argument list <> itself may also be omitted.
3813 //
3814 // Take all of the explicitly-specified arguments and put them into
3815 // the set of deduced template arguments. The partially-substituted
3816 // parameter pack, however, will be set to NULL since the deduction
3817 // mechanism handles the partially-substituted argument pack directly.
3818 Deduced.reserve(TemplateParams->size());
3819 for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3820 const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
3821 if (I == PartiallySubstitutedPackIndex)
3822 Deduced.push_back(DeducedTemplateArgument());
3823 else
3824 Deduced.push_back(Arg);
3825 }
3826
3828}
3829
3830/// Check whether the deduced argument type for a call to a function
3831/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3834 Sema::OriginalCallArg OriginalArg,
3835 QualType DeducedA) {
3836 ASTContext &Context = S.Context;
3837
3838 auto Failed = [&]() -> TemplateDeductionResult {
3839 Info.FirstArg = TemplateArgument(DeducedA);
3840 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3841 Info.CallArgIndex = OriginalArg.ArgIdx;
3842 return OriginalArg.DecomposedParam
3845 };
3846
3847 QualType A = OriginalArg.OriginalArgType;
3848 QualType OriginalParamType = OriginalArg.OriginalParamType;
3849
3850 // Check for type equality (top-level cv-qualifiers are ignored).
3851 if (Context.hasSameUnqualifiedType(A, DeducedA))
3853
3854 // Strip off references on the argument types; they aren't needed for
3855 // the following checks.
3856 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3857 DeducedA = DeducedARef->getPointeeType();
3858 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3859 A = ARef->getPointeeType();
3860
3861 // C++ [temp.deduct.call]p4:
3862 // [...] However, there are three cases that allow a difference:
3863 // - If the original P is a reference type, the deduced A (i.e., the
3864 // type referred to by the reference) can be more cv-qualified than
3865 // the transformed A.
3866 if (const ReferenceType *OriginalParamRef
3867 = OriginalParamType->getAs<ReferenceType>()) {
3868 // We don't want to keep the reference around any more.
3869 OriginalParamType = OriginalParamRef->getPointeeType();
3870
3871 // FIXME: Resolve core issue (no number yet): if the original P is a
3872 // reference type and the transformed A is function type "noexcept F",
3873 // the deduced A can be F.
3874 QualType Tmp;
3875 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
3877
3878 Qualifiers AQuals = A.getQualifiers();
3879 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3880
3881 // Under Objective-C++ ARC, the deduced type may have implicitly
3882 // been given strong or (when dealing with a const reference)
3883 // unsafe_unretained lifetime. If so, update the original
3884 // qualifiers to include this lifetime.
3885 if (S.getLangOpts().ObjCAutoRefCount &&
3886 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3888 (DeducedAQuals.hasConst() &&
3889 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3890 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3891 }
3892
3893 if (AQuals == DeducedAQuals) {
3894 // Qualifiers match; there's nothing to do.
3895 } else if (!DeducedAQuals.compatiblyIncludes(AQuals, S.getASTContext())) {
3896 return Failed();
3897 } else {
3898 // Qualifiers are compatible, so have the argument type adopt the
3899 // deduced argument type's qualifiers as if we had performed the
3900 // qualification conversion.
3901 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3902 }
3903 }
3904
3905 // - The transformed A can be another pointer or pointer to member
3906 // type that can be converted to the deduced A via a function pointer
3907 // conversion and/or a qualification conversion.
3908 //
3909 // Also allow conversions which merely strip __attribute__((noreturn)) from
3910 // function types (recursively).
3911 bool ObjCLifetimeConversion = false;
3912 QualType ResultTy;
3913 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3914 (S.IsQualificationConversion(A, DeducedA, false,
3915 ObjCLifetimeConversion) ||
3916 S.IsFunctionConversion(A, DeducedA, ResultTy)))
3918
3919 // - If P is a class and P has the form simple-template-id, then the
3920 // transformed A can be a derived class of the deduced A. [...]
3921 // [...] Likewise, if P is a pointer to a class of the form
3922 // simple-template-id, the transformed A can be a pointer to a
3923 // derived class pointed to by the deduced A.
3924 if (const PointerType *OriginalParamPtr
3925 = OriginalParamType->getAs<PointerType>()) {
3926 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3927 if (const PointerType *APtr = A->getAs<PointerType>()) {
3928 if (A->getPointeeType()->isRecordType()) {
3929 OriginalParamType = OriginalParamPtr->getPointeeType();
3930 DeducedA = DeducedAPtr->getPointeeType();
3931 A = APtr->getPointeeType();
3932 }
3933 }
3934 }
3935 }
3936
3937 if (Context.hasSameUnqualifiedType(A, DeducedA))
3939
3940 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3941 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3943
3944 return Failed();
3945}
3946
3947/// Find the pack index for a particular parameter index in an instantiation of
3948/// a function template with specific arguments.
3949///
3950/// \return The pack index for whichever pack produced this parameter, or -1
3951/// if this was not produced by a parameter. Intended to be used as the
3952/// ArgumentPackSubstitutionIndex for further substitutions.
3953// FIXME: We should track this in OriginalCallArgs so we don't need to
3954// reconstruct it here.
3955static unsigned getPackIndexForParam(Sema &S,
3956 FunctionTemplateDecl *FunctionTemplate,
3958 unsigned ParamIdx) {
3959 unsigned Idx = 0;
3960 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3961 if (PD->isParameterPack()) {
3962 unsigned NumExpansions =
3963 S.getNumArgumentsInExpansion(PD->getType(), Args).value_or(1);
3964 if (Idx + NumExpansions > ParamIdx)
3965 return ParamIdx - Idx;
3966 Idx += NumExpansions;
3967 } else {
3968 if (Idx == ParamIdx)
3969 return -1; // Not a pack expansion
3970 ++Idx;
3971 }
3972 }
3973
3974 llvm_unreachable("parameter index would not be produced from template");
3975}
3976
3977// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`,
3978// we'll try to instantiate and update its explicit specifier after constraint
3979// checking.
3982 const MultiLevelTemplateArgumentList &SubstArgs,
3983 TemplateDeductionInfo &Info, FunctionTemplateDecl *FunctionTemplate,
3984 ArrayRef<TemplateArgument> DeducedArgs) {
3985 auto GetExplicitSpecifier = [](FunctionDecl *D) {
3986 return isa<CXXConstructorDecl>(D)
3987 ? cast<CXXConstructorDecl>(D)->getExplicitSpecifier()
3988 : cast<CXXConversionDecl>(D)->getExplicitSpecifier();
3989 };
3990 auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) {
3991 isa<CXXConstructorDecl>(D)
3992 ? cast<CXXConstructorDecl>(D)->setExplicitSpecifier(ES)
3993 : cast<CXXConversionDecl>(D)->setExplicitSpecifier(ES);
3994 };
3995
3996 ExplicitSpecifier ES = GetExplicitSpecifier(Specialization);
3997 Expr *ExplicitExpr = ES.getExpr();
3998 if (!ExplicitExpr)
4000 if (!ExplicitExpr->isValueDependent())
4002
4004 S, Info.getLocation(), FunctionTemplate, DeducedArgs,
4006 if (Inst.isInvalid())
4008 Sema::SFINAETrap Trap(S);
4009 const ExplicitSpecifier InstantiatedES =
4010 S.instantiateExplicitSpecifier(SubstArgs, ES);
4011 if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) {
4012 Specialization->setInvalidDecl(true);
4014 }
4015 SetExplicitSpecifier(Specialization, InstantiatedES);
4017}
4018
4020 FunctionTemplateDecl *FunctionTemplate,
4022 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
4024 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
4025 bool PartialOverloading, bool PartialOrdering,
4026 llvm::function_ref<bool()> CheckNonDependent) {
4027 // Unevaluated SFINAE context.
4030 SFINAETrap Trap(*this);
4031
4032 // Enter a new template instantiation context while we instantiate the
4033 // actual function declaration.
4034 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
4036 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
4038 if (Inst.isInvalid())
4040
4041 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
4042
4043 // C++ [temp.deduct.type]p2:
4044 // [...] or if any template argument remains neither deduced nor
4045 // explicitly specified, template argument deduction fails.
4046 bool IsIncomplete = false;
4047 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
4049 *this, FunctionTemplate, /*IsDeduced=*/true, Deduced, Info,
4050 SugaredBuilder, CanonicalBuilder, PartialOrdering,
4051 CurrentInstantiationScope, NumExplicitlySpecified,
4052 PartialOverloading ? &IsIncomplete : nullptr);
4054 return Result;
4055
4056 // C++ [temp.deduct.call]p10: [DR1391]
4057 // If deduction succeeds for all parameters that contain
4058 // template-parameters that participate in template argument deduction,
4059 // and all template arguments are explicitly specified, deduced, or
4060 // obtained from default template arguments, remaining parameters are then
4061 // compared with the corresponding arguments. For each remaining parameter
4062 // P with a type that was non-dependent before substitution of any
4063 // explicitly-specified template arguments, if the corresponding argument
4064 // A cannot be implicitly converted to P, deduction fails.
4065 if (CheckNonDependent())
4067
4068 // Form the template argument list from the deduced template arguments.
4069 TemplateArgumentList *SugaredDeducedArgumentList =
4071 TemplateArgumentList *CanonicalDeducedArgumentList =
4072 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
4073 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
4074
4075 // Substitute the deduced template arguments into the function template
4076 // declaration to produce the function template specialization.
4077 DeclContext *Owner = FunctionTemplate->getDeclContext();
4078 if (FunctionTemplate->getFriendObjectKind())
4079 Owner = FunctionTemplate->getLexicalDeclContext();
4080 FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
4081 // additional check for inline friend,
4082 // ```
4083 // template <class F1> int foo(F1 X);
4084 // template <int A1> struct A {
4085 // template <class F1> friend int foo(F1 X) { return A1; }
4086 // };
4087 // template struct A<1>;
4088 // int a = foo(1.0);
4089 // ```
4090 const FunctionDecl *FDFriend;
4092 FD->isDefined(FDFriend, /*CheckForPendingFriendDefinition*/ true) &&
4094 FD = const_cast<FunctionDecl *>(FDFriend);
4095 Owner = FD->getLexicalDeclContext();
4096 }
4098 FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
4099 /*Final=*/false);
4100 Specialization = cast_or_null<FunctionDecl>(
4101 SubstDecl(FD, Owner, SubstArgs));
4102 if (!Specialization || Specialization->isInvalidDecl())
4104
4105 assert(isSameDeclaration(Specialization->getPrimaryTemplate(),
4107
4108 // If the template argument list is owned by the function template
4109 // specialization, release it.
4110 if (Specialization->getTemplateSpecializationArgs() ==
4111 CanonicalDeducedArgumentList &&
4112 !Trap.hasErrorOccurred())
4113 Info.takeCanonical();
4114
4115 // There may have been an error that did not prevent us from constructing a
4116 // declaration. Mark the declaration invalid and return with a substitution
4117 // failure.
4118 if (Trap.hasErrorOccurred()) {
4119 Specialization->setInvalidDecl(true);
4121 }
4122
4123 // C++2a [temp.deduct]p5
4124 // [...] When all template arguments have been deduced [...] all uses of
4125 // template parameters [...] are replaced with the corresponding deduced
4126 // or default argument values.
4127 // [...] If the function template has associated constraints
4128 // ([temp.constr.decl]), those constraints are checked for satisfaction
4129 // ([temp.constr.constr]). If the constraints are not satisfied, type
4130 // deduction fails.
4131 if (!IsIncomplete) {
4133 Info.getLocation(), Specialization, CanonicalBuilder,
4136
4138 Info.reset(Info.takeSugared(),
4139 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder));
4141 }
4142 }
4143
4144 // We skipped the instantiation of the explicit-specifier during the
4145 // substitution of `FD` before. So, we try to instantiate it back if
4146 // `Specialization` is either a constructor or a conversion function.
4147 if (isa<CXXConstructorDecl, CXXConversionDecl>(Specialization)) {
4150 Info, FunctionTemplate,
4151 DeducedArgs)) {
4153 }
4154 }
4155
4156 if (OriginalCallArgs) {
4157 // C++ [temp.deduct.call]p4:
4158 // In general, the deduction process attempts to find template argument
4159 // values that will make the deduced A identical to A (after the type A
4160 // is transformed as described above). [...]
4161 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
4162 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
4163 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
4164
4165 auto ParamIdx = OriginalArg.ArgIdx;
4166 unsigned ExplicitOffset =
4167 Specialization->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
4168 if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset)
4169 // FIXME: This presumably means a pack ended up smaller than we
4170 // expected while deducing. Should this not result in deduction
4171 // failure? Can it even happen?
4172 continue;
4173
4174 QualType DeducedA;
4175 if (!OriginalArg.DecomposedParam) {
4176 // P is one of the function parameters, just look up its substituted
4177 // type.
4178 DeducedA =
4179 Specialization->getParamDecl(ParamIdx + ExplicitOffset)->getType();
4180 } else {
4181 // P is a decomposed element of a parameter corresponding to a
4182 // braced-init-list argument. Substitute back into P to find the
4183 // deduced A.
4184 QualType &CacheEntry =
4185 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
4186 if (CacheEntry.isNull()) {
4188 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
4189 ParamIdx));
4190 CacheEntry =
4191 SubstType(OriginalArg.OriginalParamType, SubstArgs,
4192 Specialization->getTypeSpecStartLoc(),
4193 Specialization->getDeclName());
4194 }
4195 DeducedA = CacheEntry;
4196 }
4197
4198 if (auto TDK =
4199 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
4201 return TDK;
4202 }
4203 }
4204
4205 // If we suppressed any diagnostics while performing template argument
4206 // deduction, and if we haven't already instantiated this declaration,
4207 // keep track of these diagnostics. They'll be emitted if this specialization
4208 // is actually used.
4209 if (Info.diag_begin() != Info.diag_end()) {
4210 auto [Pos, Inserted] =
4211 SuppressedDiagnostics.try_emplace(Specialization->getCanonicalDecl());
4212 if (Inserted)
4213 Pos->second.append(Info.diag_begin(), Info.diag_end());
4214 }
4215
4217}
4218
4219/// Gets the type of a function for template-argument-deducton
4220/// purposes when it's considered as part of an overload set.
4222 FunctionDecl *Fn) {
4223 // We may need to deduce the return type of the function now.
4224 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
4225 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
4226 return {};
4227
4228 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
4229 if (Method->isImplicitObjectMemberFunction()) {
4230 // An instance method that's referenced in a form that doesn't
4231 // look like a member pointer is just invalid.
4233 return {};
4234
4235 return S.Context.getMemberPointerType(Fn->getType(),
4236 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
4237 }
4238
4239 if (!R.IsAddressOfOperand) return Fn->getType();
4240 return S.Context.getPointerType(Fn->getType());
4241}
4242
4243/// Apply the deduction rules for overload sets.
4244///
4245/// \return the null type if this argument should be treated as an
4246/// undeduced context
4247static QualType
4249 Expr *Arg, QualType ParamType,
4250 bool ParamWasReference,
4251 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4252
4254
4255 OverloadExpr *Ovl = R.Expression;
4256
4257 // C++0x [temp.deduct.call]p4
4258 unsigned TDF = 0;
4259 if (ParamWasReference)
4261 if (R.IsAddressOfOperand)
4262 TDF |= TDF_IgnoreQualifiers;
4263
4264 // C++0x [temp.deduct.call]p6:
4265 // When P is a function type, pointer to function type, or pointer
4266 // to member function type:
4267
4268 if (!ParamType->isFunctionType() &&
4269 !ParamType->isFunctionPointerType() &&
4270 !ParamType->isMemberFunctionPointerType()) {
4271 if (Ovl->hasExplicitTemplateArgs()) {
4272 // But we can still look for an explicit specialization.
4273 if (FunctionDecl *ExplicitSpec =
4275 Ovl, /*Complain=*/false,
4276 /*FoundDeclAccessPair=*/nullptr, FailedTSC))
4277 return GetTypeOfFunction(S, R, ExplicitSpec);
4278 }
4279
4280 DeclAccessPair DAP;
4281 if (FunctionDecl *Viable =
4283 return GetTypeOfFunction(S, R, Viable);
4284
4285 return {};
4286 }
4287
4288 // Gather the explicit template arguments, if any.
4289 TemplateArgumentListInfo ExplicitTemplateArgs;
4290 if (Ovl->hasExplicitTemplateArgs())
4291 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4292 QualType Match;
4293 for (UnresolvedSetIterator I = Ovl->decls_begin(),
4294 E = Ovl->decls_end(); I != E; ++I) {
4295 NamedDecl *D = (*I)->getUnderlyingDecl();
4296
4297 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
4298 // - If the argument is an overload set containing one or more
4299 // function templates, the parameter is treated as a
4300 // non-deduced context.
4301 if (!Ovl->hasExplicitTemplateArgs())
4302 return {};
4303
4304 // Otherwise, see if we can resolve a function type
4305 FunctionDecl *Specialization = nullptr;
4306 TemplateDeductionInfo Info(Ovl->getNameLoc());
4307 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
4310 continue;
4311
4312 D = Specialization;
4313 }
4314
4315 FunctionDecl *Fn = cast<FunctionDecl>(D);
4316 QualType ArgType = GetTypeOfFunction(S, R, Fn);
4317 if (ArgType.isNull()) continue;
4318
4319 // Function-to-pointer conversion.
4320 if (!ParamWasReference && ParamType->isPointerType() &&
4321 ArgType->isFunctionType())
4322 ArgType = S.Context.getPointerType(ArgType);
4323
4324 // - If the argument is an overload set (not containing function
4325 // templates), trial argument deduction is attempted using each
4326 // of the members of the set. If deduction succeeds for only one
4327 // of the overload set members, that member is used as the
4328 // argument value for the deduction. If deduction succeeds for
4329 // more than one member of the overload set the parameter is
4330 // treated as a non-deduced context.
4331
4332 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
4333 // Type deduction is done independently for each P/A pair, and
4334 // the deduced template argument values are then combined.
4335 // So we do not reject deductions which were made elsewhere.
4337 Deduced(TemplateParams->size());
4338 TemplateDeductionInfo Info(Ovl->getNameLoc());
4340 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4341 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4342 /*HasDeducedAnyParam=*/nullptr);
4344 continue;
4345 if (!Match.isNull())
4346 return {};
4347 Match = ArgType;
4348 }
4349
4350 return Match;
4351}
4352
4353/// Perform the adjustments to the parameter and argument types
4354/// described in C++ [temp.deduct.call].
4355///
4356/// \returns true if the caller should not attempt to perform any template
4357/// argument deduction based on this P/A pair because the argument is an
4358/// overloaded function set that could not be resolved.
4360 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4361 QualType &ParamType, QualType &ArgType,
4362 Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
4363 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4364 // C++0x [temp.deduct.call]p3:
4365 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
4366 // are ignored for type deduction.
4367 if (ParamType.hasQualifiers())
4368 ParamType = ParamType.getUnqualifiedType();
4369
4370 // [...] If P is a reference type, the type referred to by P is
4371 // used for type deduction.
4372 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
4373 if (ParamRefType)
4374 ParamType = ParamRefType->getPointeeType();
4375
4376 // Overload sets usually make this parameter an undeduced context,
4377 // but there are sometimes special circumstances. Typically
4378 // involving a template-id-expr.
4379 if (ArgType == S.Context.OverloadTy) {
4380 assert(Arg && "expected a non-null arg expression");
4381 ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType,
4382 ParamRefType != nullptr, FailedTSC);
4383 if (ArgType.isNull())
4384 return true;
4385 }
4386
4387 if (ParamRefType) {
4388 // If the argument has incomplete array type, try to complete its type.
4389 if (ArgType->isIncompleteArrayType()) {
4390 assert(Arg && "expected a non-null arg expression");
4391 ArgType = S.getCompletedType(Arg);
4392 }
4393
4394 // C++1z [temp.deduct.call]p3:
4395 // If P is a forwarding reference and the argument is an lvalue, the type
4396 // "lvalue reference to A" is used in place of A for type deduction.
4397 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
4398 ArgClassification.isLValue()) {
4399 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
4400 ArgType = S.Context.getAddrSpaceQualType(
4402 ArgType = S.Context.getLValueReferenceType(ArgType);
4403 }
4404 } else {
4405 // C++ [temp.deduct.call]p2:
4406 // If P is not a reference type:
4407 // - If A is an array type, the pointer type produced by the
4408 // array-to-pointer standard conversion (4.2) is used in place of
4409 // A for type deduction; otherwise,
4410 // - If A is a function type, the pointer type produced by the
4411 // function-to-pointer standard conversion (4.3) is used in place
4412 // of A for type deduction; otherwise,
4413 if (ArgType->canDecayToPointerType())
4414 ArgType = S.Context.getDecayedType(ArgType);
4415 else {
4416 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
4417 // type are ignored for type deduction.
4418 ArgType = ArgType.getUnqualifiedType();
4419 }
4420 }
4421
4422 // C++0x [temp.deduct.call]p4:
4423 // In general, the deduction process attempts to find template argument
4424 // values that will make the deduced A identical to A (after the type A
4425 // is transformed as described above). [...]
4427
4428 // - If the original P is a reference type, the deduced A (i.e., the
4429 // type referred to by the reference) can be more cv-qualified than
4430 // the transformed A.
4431 if (ParamRefType)
4433 // - The transformed A can be another pointer or pointer to member
4434 // type that can be converted to the deduced A via a qualification
4435 // conversion (4.4).
4436 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
4437 ArgType->isObjCObjectPointerType())
4438 TDF |= TDF_IgnoreQualifiers;
4439 // - If P is a class and P has the form simple-template-id, then the
4440 // transformed A can be a derived class of the deduced A. Likewise,
4441 // if P is a pointer to a class of the form simple-template-id, the
4442 // transformed A can be a pointer to a derived class pointed to by
4443 // the deduced A.
4444 if (isSimpleTemplateIdType(ParamType) ||
4445 (isa<PointerType>(ParamType) &&
4447 ParamType->castAs<PointerType>()->getPointeeType())))
4448 TDF |= TDF_DerivedClass;
4449
4450 return false;
4451}
4452
4453static bool
4455 QualType T);
4456
4458 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4459 QualType ParamType, QualType ArgType,
4460 Expr::Classification ArgClassification, Expr *Arg,
4464 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4465 TemplateSpecCandidateSet *FailedTSC = nullptr);
4466
4467/// Attempt template argument deduction from an initializer list
4468/// deemed to be an argument in a function call.
4470 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
4473 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
4474 unsigned TDF) {
4475 // C++ [temp.deduct.call]p1: (CWG 1591)
4476 // If removing references and cv-qualifiers from P gives
4477 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
4478 // a non-empty initializer list, then deduction is performed instead for
4479 // each element of the initializer list, taking P0 as a function template
4480 // parameter type and the initializer element as its argument
4481 //
4482 // We've already removed references and cv-qualifiers here.
4483 if (!ILE->getNumInits())
4485
4486 QualType ElTy;
4487 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
4488 if (ArrTy)
4489 ElTy = ArrTy->getElementType();
4490 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
4491 // Otherwise, an initializer list argument causes the parameter to be
4492 // considered a non-deduced context
4494 }
4495
4496 // Resolving a core issue: a braced-init-list containing any designators is
4497 // a non-deduced context.
4498 for (Expr *E : ILE->inits())
4499 if (isa<DesignatedInitExpr>(E))
4501
4502 // Deduction only needs to be done for dependent types.
4503 if (ElTy->isDependentType()) {
4504 for (Expr *E : ILE->inits()) {
4506 S, TemplateParams, 0, ElTy, E->getType(),
4507 E->Classify(S.getASTContext()), E, Info, Deduced,
4508 OriginalCallArgs, true, ArgIdx, TDF);
4510 return Result;
4511 }
4512 }
4513
4514 // in the P0[N] case, if N is a non-type template parameter, N is deduced
4515 // from the length of the initializer list.
4516 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
4517 // Determine the array bound is something we can deduce.
4518 if (const NonTypeTemplateParmDecl *NTTP =
4519 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
4520 // We can perform template argument deduction for the given non-type
4521 // template parameter.
4522 // C++ [temp.deduct.type]p13:
4523 // The type of N in the type T[N] is std::size_t.
4525 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
4527 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
4528 /*ArrayBound=*/true, Info, /*PartialOrdering=*/false, Deduced,
4529 /*HasDeducedAnyParam=*/nullptr);
4531 return Result;
4532 }
4533 }
4534
4536}
4537
4538/// Perform template argument deduction per [temp.deduct.call] for a
4539/// single parameter / argument pair.
4541 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4542 QualType ParamType, QualType ArgType,
4543 Expr::Classification ArgClassification, Expr *Arg,
4547 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4548 TemplateSpecCandidateSet *FailedTSC) {
4549
4550 QualType OrigParamType = ParamType;
4551
4552 // If P is a reference type [...]
4553 // If P is a cv-qualified type [...]
4555 S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
4556 ArgClassification, Arg, TDF, FailedTSC))
4558
4559 // If [...] the argument is a non-empty initializer list [...]
4560 if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
4561 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
4562 Deduced, OriginalCallArgs, ArgIdx, TDF);
4563
4564 // [...] the deduction process attempts to find template argument values
4565 // that will make the deduced A identical to A
4566 //
4567 // Keep track of the argument type and corresponding parameter index,
4568 // so we can check for compatibility between the deduced A and A.
4569 if (Arg)
4570 OriginalCallArgs.push_back(
4571 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
4573 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4574 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4575 /*HasDeducedAnyParam=*/nullptr);
4576}
4577
4579 FunctionTemplateDecl *FunctionTemplate,
4580 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4582 bool PartialOverloading, bool AggregateDeductionCandidate,
4583 bool PartialOrdering, QualType ObjectType,
4584 Expr::Classification ObjectClassification,
4585 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
4586 if (FunctionTemplate->isInvalidDecl())
4588
4589 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4590 unsigned NumParams = Function->getNumParams();
4591 bool HasExplicitObject = false;
4592 int ExplicitObjectOffset = 0;
4593 if (Function->hasCXXExplicitFunctionObjectParameter()) {
4594 HasExplicitObject = true;
4595 ExplicitObjectOffset = 1;
4596 }
4597
4598 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
4599
4600 // C++ [temp.deduct.call]p1:
4601 // Template argument deduction is done by comparing each function template
4602 // parameter type (call it P) with the type of the corresponding argument
4603 // of the call (call it A) as described below.
4604 if (Args.size() < Function->getMinRequiredExplicitArguments() &&
4605 !PartialOverloading)
4607 else if (TooManyArguments(NumParams, Args.size() + ExplicitObjectOffset,
4608 PartialOverloading)) {
4609 const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
4610 if (Proto->isTemplateVariadic())
4611 /* Do nothing */;
4612 else if (!Proto->isVariadic())
4614 }
4615
4616 // The types of the parameters from which we will perform template argument
4617 // deduction.
4618 LocalInstantiationScope InstScope(*this);
4619 TemplateParameterList *TemplateParams
4620 = FunctionTemplate->getTemplateParameters();
4622 SmallVector<QualType, 8> ParamTypes;
4623 unsigned NumExplicitlySpecified = 0;
4624 if (ExplicitTemplateArgs) {
4627 Result = SubstituteExplicitTemplateArguments(
4628 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4629 Info);
4630 });
4632 return Result;
4633
4634 NumExplicitlySpecified = Deduced.size();
4635 } else {
4636 // Just fill in the parameter types from the function declaration.
4637 for (unsigned I = 0; I != NumParams; ++I)
4638 ParamTypes.push_back(Function->getParamDecl(I)->getType());
4639 }
4640
4641 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
4642
4643 // Deduce an argument of type ParamType from an expression with index ArgIdx.
4644 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx,
4645 bool ExplicitObjectArgument) {
4646 // C++ [demp.deduct.call]p1: (DR1391)
4647 // Template argument deduction is done by comparing each function template
4648 // parameter that contains template-parameters that participate in
4649 // template argument deduction ...
4650 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4652
4653 if (ExplicitObjectArgument) {
4654 // ... with the type of the corresponding argument
4656 *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
4657 ObjectClassification,
4658 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4659 /*Decomposed*/ false, ArgIdx, /*TDF*/ 0);
4660 }
4661
4662 // ... with the type of the corresponding argument
4664 *this, TemplateParams, FirstInnerIndex, ParamType,
4665 Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()),
4666 Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false,
4667 ArgIdx, /*TDF*/ 0);
4668 };
4669
4670 // Deduce template arguments from the function parameters.
4671 Deduced.resize(TemplateParams->size());
4672 SmallVector<QualType, 8> ParamTypesForArgChecking;
4673 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4674 ParamIdx != NumParamTypes; ++ParamIdx) {
4675 QualType ParamType = ParamTypes[ParamIdx];
4676
4677 const PackExpansionType *ParamExpansion =
4678 dyn_cast<PackExpansionType>(ParamType);
4679 if (!ParamExpansion) {
4680 // Simple case: matching a function parameter to a function argument.
4681 if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0))
4682 break;
4683
4684 ParamTypesForArgChecking.push_back(ParamType);
4685
4686 if (ParamIdx == 0 && HasExplicitObject) {
4687 if (ObjectType.isNull())
4689
4690 if (auto Result = DeduceCallArgument(ParamType, 0,
4691 /*ExplicitObjectArgument=*/true);
4693 return Result;
4694 continue;
4695 }
4696
4697 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4698 /*ExplicitObjectArgument=*/false);
4700 return Result;
4701
4702 continue;
4703 }
4704
4705 bool IsTrailingPack = ParamIdx + 1 == NumParamTypes;
4706
4707 QualType ParamPattern = ParamExpansion->getPattern();
4708 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
4709 ParamPattern,
4710 AggregateDeductionCandidate && IsTrailingPack);
4711
4712 // C++0x [temp.deduct.call]p1:
4713 // For a function parameter pack that occurs at the end of the
4714 // parameter-declaration-list, the type A of each remaining argument of
4715 // the call is compared with the type P of the declarator-id of the
4716 // function parameter pack. Each comparison deduces template arguments
4717 // for subsequent positions in the template parameter packs expanded by
4718 // the function parameter pack. When a function parameter pack appears
4719 // in a non-deduced context [not at the end of the list], the type of
4720 // that parameter pack is never deduced.
4721 //
4722 // FIXME: The above rule allows the size of the parameter pack to change
4723 // after we skip it (in the non-deduced case). That makes no sense, so
4724 // we instead notionally deduce the pack against N arguments, where N is
4725 // the length of the explicitly-specified pack if it's expanded by the
4726 // parameter pack and 0 otherwise, and we treat each deduction as a
4727 // non-deduced context.
4728 if (IsTrailingPack || PackScope.hasFixedArity()) {
4729 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4730 PackScope.nextPackElement(), ++ArgIdx) {
4731 ParamTypesForArgChecking.push_back(ParamPattern);
4732 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4733 /*ExplicitObjectArgument=*/false);
4735 return Result;
4736 }
4737 } else {
4738 // If the parameter type contains an explicitly-specified pack that we
4739 // could not expand, skip the number of parameters notionally created
4740 // by the expansion.
4741 std::optional<unsigned> NumExpansions =
4742 ParamExpansion->getNumExpansions();
4743 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4744 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4745 ++I, ++ArgIdx) {
4746 ParamTypesForArgChecking.push_back(ParamPattern);
4747 // FIXME: Should we add OriginalCallArgs for these? What if the
4748 // corresponding argument is a list?
4749 PackScope.nextPackElement();
4750 }
4751 } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4752 PackScope.isDeducedFromEarlierParameter()) {
4753 // [temp.deduct.general#3]
4754 // When all template arguments have been deduced
4755 // or obtained from default template arguments, all uses of template
4756 // parameters in the template parameter list of the template are
4757 // replaced with the corresponding deduced or default argument values
4758 //
4759 // If we have a trailing parameter pack, that has been deduced
4760 // previously we substitute the pack here in a similar fashion as
4761 // above with the trailing parameter packs. The main difference here is
4762 // that, in this case we are not processing all of the remaining
4763 // arguments. We are only process as many arguments as we have in
4764 // the already deduced parameter.
4765 std::optional<unsigned> ArgPosAfterSubstitution =
4766 PackScope.getSavedPackSizeIfAllEqual();
4767 if (!ArgPosAfterSubstitution)
4768 continue;
4769
4770 unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4771 for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4772 ParamTypesForArgChecking.push_back(ParamPattern);
4773 if (auto Result =
4774 DeduceCallArgument(ParamPattern, ArgIdx,
4775 /*ExplicitObjectArgument=*/false);
4777 return Result;
4778
4779 PackScope.nextPackElement();
4780 }
4781 }
4782 }
4783
4784 // Build argument packs for each of the parameter packs expanded by this
4785 // pack expansion.
4786 if (auto Result = PackScope.finish();
4788 return Result;
4789 }
4790
4791 // Capture the context in which the function call is made. This is the context
4792 // that is needed when the accessibility of template arguments is checked.
4793 DeclContext *CallingCtx = CurContext;
4794
4797 Result = FinishTemplateArgumentDeduction(
4798 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4799 &OriginalCallArgs, PartialOverloading, PartialOrdering,
4800 [&, CallingCtx]() {
4801 ContextRAII SavedContext(*this, CallingCtx);
4802 return CheckNonDependent(ParamTypesForArgChecking);
4803 });
4804 });
4805 return Result;
4806}
4807
4810 bool AdjustExceptionSpec) {
4811 if (ArgFunctionType.isNull())
4812 return ArgFunctionType;
4813
4814 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4815 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4816 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4817 bool Rebuild = false;
4818
4819 CallingConv CC = FunctionTypeP->getCallConv();
4820 if (EPI.ExtInfo.getCC() != CC) {
4821 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4822 Rebuild = true;
4823 }
4824
4825 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4826 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4827 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4828 Rebuild = true;
4829 }
4830
4831 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4832 ArgFunctionTypeP->hasExceptionSpec())) {
4833 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4834 Rebuild = true;
4835 }
4836
4837 if (!Rebuild)
4838 return ArgFunctionType;
4839
4840 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4841 ArgFunctionTypeP->getParamTypes(), EPI);
4842}
4843
4845 FunctionTemplateDecl *FunctionTemplate,
4846 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4848 bool IsAddressOfFunction) {
4849 if (FunctionTemplate->isInvalidDecl())
4851
4852 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4853 TemplateParameterList *TemplateParams
4854 = FunctionTemplate->getTemplateParameters();
4855 QualType FunctionType = Function->getType();
4856
4857 // Substitute any explicit template arguments.
4858 LocalInstantiationScope InstScope(*this);
4860 unsigned NumExplicitlySpecified = 0;
4861 SmallVector<QualType, 4> ParamTypes;
4862 if (ExplicitTemplateArgs) {
4865 Result = SubstituteExplicitTemplateArguments(
4866 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4867 &FunctionType, Info);
4868 });
4870 return Result;
4871
4872 NumExplicitlySpecified = Deduced.size();
4873 }
4874
4875 // When taking the address of a function, we require convertibility of
4876 // the resulting function type. Otherwise, we allow arbitrary mismatches
4877 // of calling convention and noreturn.
4878 if (!IsAddressOfFunction)
4879 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4880 /*AdjustExceptionSpec*/false);
4881
4882 // Unevaluated SFINAE context.
4885 SFINAETrap Trap(*this);
4886
4887 Deduced.resize(TemplateParams->size());
4888
4889 // If the function has a deduced return type, substitute it for a dependent
4890 // type so that we treat it as a non-deduced context in what follows.
4891 bool HasDeducedReturnType = false;
4892 if (getLangOpts().CPlusPlus14 &&
4893 Function->getReturnType()->getContainedAutoType()) {
4895 HasDeducedReturnType = true;
4896 }
4897
4898 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
4899 unsigned TDF =
4901 // Deduce template arguments from the function type.
4903 *this, TemplateParams, FunctionType, ArgFunctionType, Info, Deduced,
4904 TDF, PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4905 /*HasDeducedAnyParam=*/nullptr);
4907 return Result;
4908 }
4909
4912 Result = FinishTemplateArgumentDeduction(
4913 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4914 /*OriginalCallArgs=*/nullptr, /*PartialOverloading=*/false,
4915 /*PartialOrdering=*/true);
4916 });
4918 return Result;
4919
4920 // If the function has a deduced return type, deduce it now, so we can check
4921 // that the deduced function type matches the requested type.
4922 if (HasDeducedReturnType && IsAddressOfFunction &&
4923 Specialization->getReturnType()->isUndeducedType() &&
4926
4927 // [C++26][expr.const]/p17
4928 // An expression or conversion is immediate-escalating if it is not initially
4929 // in an immediate function context and it is [...]
4930 // a potentially-evaluated id-expression that denotes an immediate function.
4931 if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
4932 Specialization->isImmediateEscalating() &&
4933 parentEvaluationContext().isPotentiallyEvaluated() &&
4935 Info.getLocation()))
4937
4938 // Adjust the exception specification of the argument to match the
4939 // substituted and resolved type we just formed. (Calling convention and
4940 // noreturn can't be dependent, so we don't actually need this for them
4941 // right now.)
4942 QualType SpecializationType = Specialization->getType();
4943 if (!IsAddressOfFunction) {
4944 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4945 /*AdjustExceptionSpec*/true);
4946
4947 // Revert placeholder types in the return type back to undeduced types so
4948 // that the comparison below compares the declared return types.
4949 if (HasDeducedReturnType) {
4950 SpecializationType = SubstAutoType(SpecializationType, QualType());
4951 ArgFunctionType = SubstAutoType(ArgFunctionType, QualType());
4952 }
4953 }
4954
4955 // If the requested function type does not match the actual type of the
4956 // specialization with respect to arguments of compatible pointer to function
4957 // types, template argument deduction fails.
4958 if (!ArgFunctionType.isNull()) {
4959 if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
4960 SpecializationType, ArgFunctionType)
4962 SpecializationType, ArgFunctionType)) {
4963 Info.FirstArg = TemplateArgument(SpecializationType);
4964 Info.SecondArg = TemplateArgument(ArgFunctionType);
4966 }
4967 }
4968
4970}
4971
4973 FunctionTemplateDecl *ConversionTemplate, QualType ObjectType,
4974 Expr::Classification ObjectClassification, QualType A,
4976 if (ConversionTemplate->isInvalidDecl())
4978
4979 CXXConversionDecl *ConversionGeneric
4980 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4981
4982 QualType P = ConversionGeneric->getConversionType();
4983 bool IsReferenceP = P->isReferenceType();
4984 bool IsReferenceA = A->isReferenceType();
4985
4986 // C++0x [temp.deduct.conv]p2:
4987 // If P is a reference type, the type referred to by P is used for
4988 // type deduction.
4989 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4990 P = PRef->getPointeeType();
4991
4992 // C++0x [temp.deduct.conv]p4:
4993 // [...] If A is a reference type, the type referred to by A is used
4994 // for type deduction.
4995 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4996 A = ARef->getPointeeType();
4997 // We work around a defect in the standard here: cv-qualifiers are also
4998 // removed from P and A in this case, unless P was a reference type. This
4999 // seems to mostly match what other compilers are doing.
5000 if (!IsReferenceP) {
5001 A = A.getUnqualifiedType();
5002 P = P.getUnqualifiedType();
5003 }
5004
5005 // C++ [temp.deduct.conv]p3:
5006 //
5007 // If A is not a reference type:
5008 } else {
5009 assert(!A->isReferenceType() && "Reference types were handled above");
5010
5011 // - If P is an array type, the pointer type produced by the
5012 // array-to-pointer standard conversion (4.2) is used in place
5013 // of P for type deduction; otherwise,
5014 if (P->isArrayType())
5016 // - If P is a function type, the pointer type produced by the
5017 // function-to-pointer standard conversion (4.3) is used in
5018 // place of P for type deduction; otherwise,
5019 else if (P->isFunctionType())
5021 // - If P is a cv-qualified type, the top level cv-qualifiers of
5022 // P's type are ignored for type deduction.
5023 else
5024 P = P.getUnqualifiedType();
5025
5026 // C++0x [temp.deduct.conv]p4:
5027 // If A is a cv-qualified type, the top level cv-qualifiers of A's
5028 // type are ignored for type deduction. If A is a reference type, the type
5029 // referred to by A is used for type deduction.
5030 A = A.getUnqualifiedType();
5031 }
5032
5033 // Unevaluated SFINAE context.
5036 SFINAETrap Trap(*this);
5037
5038 // C++ [temp.deduct.conv]p1:
5039 // Template argument deduction is done by comparing the return
5040 // type of the template conversion function (call it P) with the
5041 // type that is required as the result of the conversion (call it
5042 // A) as described in 14.8.2.4.
5043 TemplateParameterList *TemplateParams
5044 = ConversionTemplate->getTemplateParameters();
5046 Deduced.resize(TemplateParams->size());
5047
5048 // C++0x [temp.deduct.conv]p4:
5049 // In general, the deduction process attempts to find template
5050 // argument values that will make the deduced A identical to
5051 // A. However, there are two cases that allow a difference:
5052 unsigned TDF = 0;
5053 // - If the original A is a reference type, A can be more
5054 // cv-qualified than the deduced A (i.e., the type referred to
5055 // by the reference)
5056 if (IsReferenceA)
5058 // - The deduced A can be another pointer or pointer to member
5059 // type that can be converted to A via a qualification
5060 // conversion.
5061 //
5062 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
5063 // both P and A are pointers or member pointers. In this case, we
5064 // just ignore cv-qualifiers completely).
5065 if ((P->isPointerType() && A->isPointerType()) ||
5066 (P->isMemberPointerType() && A->isMemberPointerType()))
5067 TDF |= TDF_IgnoreQualifiers;
5068
5070 if (ConversionGeneric->isExplicitObjectMemberFunction()) {
5071 QualType ParamType = ConversionGeneric->getParamDecl(0)->getType();
5074 *this, TemplateParams, getFirstInnerIndex(ConversionTemplate),
5075 ParamType, ObjectType, ObjectClassification,
5076 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
5077 /*Decomposed*/ false, 0, /*TDF*/ 0);
5079 return Result;
5080 }
5081
5083 *this, TemplateParams, P, A, Info, Deduced, TDF,
5084 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
5085 /*HasDeducedAnyParam=*/nullptr);
5087 return Result;
5088
5089 // Create an Instantiation Scope for finalizing the operator.
5090 LocalInstantiationScope InstScope(*this);
5091 // Finish template argument deduction.
5092 FunctionDecl *ConversionSpecialized = nullptr;
5095 Result = FinishTemplateArgumentDeduction(
5096 ConversionTemplate, Deduced, 0, ConversionSpecialized, Info,
5097 &OriginalCallArgs, /*PartialOverloading=*/false,
5098 /*PartialOrdering=*/false);
5099 });
5100 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
5101 return Result;
5102}
5103
5106 TemplateArgumentListInfo *ExplicitTemplateArgs,
5109 bool IsAddressOfFunction) {
5110 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
5111 QualType(), Specialization, Info,
5112 IsAddressOfFunction);
5113}
5114
5115namespace {
5116 struct DependentAuto { bool IsPack; };
5117
5118 /// Substitute the 'auto' specifier or deduced template specialization type
5119 /// specifier within a type for a given replacement type.
5120 class SubstituteDeducedTypeTransform :
5121 public TreeTransform<SubstituteDeducedTypeTransform> {
5122 QualType Replacement;
5123 bool ReplacementIsPack;
5124 bool UseTypeSugar;
5126
5127 public:
5128 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
5129 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5130 ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
5131
5132 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
5133 bool UseTypeSugar = true)
5134 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5135 Replacement(Replacement), ReplacementIsPack(false),
5136 UseTypeSugar(UseTypeSugar) {}
5137
5138 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
5139 assert(isa<TemplateTypeParmType>(Replacement) &&
5140 "unexpected unsugared replacement kind");
5141 QualType Result = Replacement;
5143 NewTL.setNameLoc(TL.getNameLoc());
5144 return Result;
5145 }
5146
5147 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
5148 // If we're building the type pattern to deduce against, don't wrap the
5149 // substituted type in an AutoType. Certain template deduction rules
5150 // apply only when a template type parameter appears directly (and not if
5151 // the parameter is found through desugaring). For instance:
5152 // auto &&lref = lvalue;
5153 // must transform into "rvalue reference to T" not "rvalue reference to
5154 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
5155 //
5156 // FIXME: Is this still necessary?
5157 if (!UseTypeSugar)
5158 return TransformDesugared(TLB, TL);
5159
5160 QualType Result = SemaRef.Context.getAutoType(
5161 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
5162 ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(),
5164 auto NewTL = TLB.push<AutoTypeLoc>(Result);
5165 NewTL.copy(TL);
5166 return Result;
5167 }
5168
5169 QualType TransformDeducedTemplateSpecializationType(
5171 if (!UseTypeSugar)
5172 return TransformDesugared(TLB, TL);
5173
5174 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
5176 Replacement, Replacement.isNull());
5177 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5178 NewTL.setNameLoc(TL.getNameLoc());
5179 return Result;
5180 }
5181
5182 ExprResult TransformLambdaExpr(LambdaExpr *E) {
5183 // Lambdas never need to be transformed.
5184 return E;
5185 }
5186 bool TransformExceptionSpec(SourceLocation Loc,
5188 SmallVectorImpl<QualType> &Exceptions,
5189 bool &Changed) {
5190 if (ESI.Type == EST_Uninstantiated) {
5191 ESI.instantiate();
5192 Changed = true;
5193 }
5194 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
5195 }
5196
5197 QualType Apply(TypeLoc TL) {
5198 // Create some scratch storage for the transformed type locations.
5199 // FIXME: We're just going to throw this information away. Don't build it.
5200 TypeLocBuilder TLB;
5201 TLB.reserve(TL.getFullDataSize());
5202 return TransformType(TLB, TL);
5203 }
5204 };
5205
5206} // namespace
5207
5210 QualType Deduced) {
5211 ConstraintSatisfaction Satisfaction;
5212 ConceptDecl *Concept = Type.getTypeConstraintConcept();
5213 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
5214 TypeLoc.getRAngleLoc());
5215 TemplateArgs.addArgument(
5218 Deduced, TypeLoc.getNameLoc())));
5219 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
5220 TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
5221
5222 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
5224 Concept, SourceLocation(), TemplateArgs, /*DefaultArgs=*/{},
5225 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
5226 return true;
5227 MultiLevelTemplateArgumentList MLTAL(Concept, CanonicalConverted,
5228 /*Final=*/false);
5229 // Build up an EvaluationContext with an ImplicitConceptSpecializationDecl so
5230 // that the template arguments of the constraint can be preserved. For
5231 // example:
5232 //
5233 // template <class T>
5234 // concept C = []<D U = void>() { return true; }();
5235 //
5236 // We need the argument for T while evaluating type constraint D in
5237 // building the CallExpr to the lambda.
5241 S.getASTContext(), Concept->getDeclContext(), Concept->getLocation(),
5242 CanonicalConverted));
5243 if (S.CheckConstraintSatisfaction(Concept, {Concept->getConstraintExpr()},
5245 Satisfaction))
5246 return true;
5247 if (!Satisfaction.IsSatisfied) {
5248 std::string Buf;
5249 llvm::raw_string_ostream OS(Buf);
5250 OS << "'" << Concept->getName();
5251 if (TypeLoc.hasExplicitTemplateArgs()) {
5253 OS, Type.getTypeConstraintArguments(), S.getPrintingPolicy(),
5254 Type.getTypeConstraintConcept()->getTemplateParameters());
5255 }
5256 OS << "'";
5257 S.Diag(TypeLoc.getConceptNameLoc(),
5258 diag::err_placeholder_constraints_not_satisfied)
5259 << Deduced << Buf << TypeLoc.getLocalSourceRange();
5260 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
5261 return true;
5262 }
5263 return false;
5264}
5265
5268 TemplateDeductionInfo &Info, bool DependentDeduction,
5269 bool IgnoreConstraints,
5270 TemplateSpecCandidateSet *FailedTSC) {
5271 assert(DependentDeduction || Info.getDeducedDepth() == 0);
5272 if (Init->containsErrors())
5274
5275 const AutoType *AT = Type.getType()->getContainedAutoType();
5276 assert(AT);
5277
5278 if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
5279 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
5280 if (NonPlaceholder.isInvalid())
5282 Init = NonPlaceholder.get();
5283 }
5284
5285 DependentAuto DependentResult = {
5286 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
5287
5288 if (!DependentDeduction &&
5289 (Type.getType()->isDependentType() || Init->isTypeDependent() ||
5290 Init->containsUnexpandedParameterPack())) {
5291 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5292 assert(!Result.isNull() && "substituting DependentTy can't fail");
5294 }
5295
5296 // Make sure that we treat 'char[]' equaly as 'char*' in C23 mode.
5297 auto *String = dyn_cast<StringLiteral>(Init);
5298 if (getLangOpts().C23 && String && Type.getType()->isArrayType()) {
5299 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5300 TypeLoc TL = TypeLoc(Init->getType(), Type.getOpaqueData());
5301 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(TL);
5302 assert(!Result.isNull() && "substituting DependentTy can't fail");
5304 }
5305
5306 // Emit a warning if 'auto*' is used in pedantic and in C23 mode.
5307 if (getLangOpts().C23 && Type.getType()->isPointerType()) {
5308 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5309 }
5310
5311 auto *InitList = dyn_cast<InitListExpr>(Init);
5312 if (!getLangOpts().CPlusPlus && InitList) {
5313 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c)
5314 << (int)AT->getKeyword() << getLangOpts().C23;
5316 }
5317
5318 // Deduce type of TemplParam in Func(Init)
5320 Deduced.resize(1);
5321
5322 // If deduction failed, don't diagnose if the initializer is dependent; it
5323 // might acquire a matching type in the instantiation.
5324 auto DeductionFailed = [&](TemplateDeductionResult TDK) {
5325 if (Init->isTypeDependent()) {
5326 Result =
5327 SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5328 assert(!Result.isNull() && "substituting DependentTy can't fail");
5330 }
5331 return TDK;
5332 };
5333
5334 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
5335
5337 // If this is a 'decltype(auto)' specifier, do the decltype dance.
5338 if (AT->isDecltypeAuto()) {
5339 if (InitList) {
5340 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
5342 }
5343
5345 assert(!DeducedType.isNull());
5346 } else {
5347 LocalInstantiationScope InstScope(*this);
5348
5349 // Build template<class TemplParam> void Func(FuncParam);
5350 SourceLocation Loc = Init->getExprLoc();
5352 Context, nullptr, SourceLocation(), Loc, Info.getDeducedDepth(), 0,
5353 nullptr, false, false, false);
5354 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
5355 NamedDecl *TemplParamPtr = TemplParam;
5357 Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
5358
5359 if (InitList) {
5360 // Notionally, we substitute std::initializer_list<T> for 'auto' and
5361 // deduce against that. Such deduction only succeeds if removing
5362 // cv-qualifiers and references results in std::initializer_list<T>.
5363 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
5365
5366 SourceRange DeducedFromInitRange;
5367 for (Expr *Init : InitList->inits()) {
5368 // Resolving a core issue: a braced-init-list containing any designators
5369 // is a non-deduced context.
5370 if (isa<DesignatedInitExpr>(Init))
5373 *this, TemplateParamsSt.get(), 0, TemplArg, Init->getType(),
5374 Init->Classify(getASTContext()), Init, Info, Deduced,
5375 OriginalCallArgs,
5376 /*Decomposed=*/true,
5377 /*ArgIdx=*/0, /*TDF=*/0);
5380 Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction)
5381 << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
5382 << Init->getSourceRange();
5383 return DeductionFailed(TemplateDeductionResult::AlreadyDiagnosed);
5384 }
5385 return DeductionFailed(TDK);
5386 }
5387
5388 if (DeducedFromInitRange.isInvalid() &&
5389 Deduced[0].getKind() != TemplateArgument::Null)
5390 DeducedFromInitRange = Init->getSourceRange();
5391 }
5392 } else {
5393 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
5394 Diag(Loc, diag::err_auto_bitfield);
5396 }
5397 QualType FuncParam =
5398 SubstituteDeducedTypeTransform(*this, TemplArg).Apply(Type);
5399 assert(!FuncParam.isNull() &&
5400 "substituting template parameter for 'auto' failed");
5402 *this, TemplateParamsSt.get(), 0, FuncParam, Init->getType(),
5403 Init->Classify(getASTContext()), Init, Info, Deduced,
5404 OriginalCallArgs,
5405 /*Decomposed=*/false, /*ArgIdx=*/0, /*TDF=*/0, FailedTSC);
5407 return DeductionFailed(TDK);
5408 }
5409
5410 // Could be null if somehow 'auto' appears in a non-deduced context.
5411 if (Deduced[0].getKind() != TemplateArgument::Type)
5412 return DeductionFailed(TemplateDeductionResult::Incomplete);
5413 DeducedType = Deduced[0].getAsType();
5414
5415 if (InitList) {
5417 if (DeducedType.isNull())
5419 }
5420 }
5421
5422 if (!Result.isNull()) {
5424 Info.FirstArg = Result;
5425 Info.SecondArg = DeducedType;
5426 return DeductionFailed(TemplateDeductionResult::Inconsistent);
5427 }
5429 }
5430
5431 if (AT->isConstrained() && !IgnoreConstraints &&
5433 *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType))
5435
5436 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
5437 if (Result.isNull())
5439
5440 // Check that the deduced argument type is compatible with the original
5441 // argument type per C++ [temp.deduct.call]p4.
5442 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
5443 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
5444 assert((bool)InitList == OriginalArg.DecomposedParam &&
5445 "decomposed non-init-list in auto deduction?");
5446 if (auto TDK =
5447 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
5449 Result = QualType();
5450 return DeductionFailed(TDK);
5451 }
5452 }
5453
5455}
5456
5458 QualType TypeToReplaceAuto) {
5459 assert(TypeToReplaceAuto != Context.DependentTy);
5460 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5461 .TransformType(TypeWithAuto);
5462}
5463
5465 QualType TypeToReplaceAuto) {
5466 assert(TypeToReplaceAuto != Context.DependentTy);
5467 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5468 .TransformType(TypeWithAuto);
5469}
5470
5472 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5473 .TransformType(TypeWithAuto);
5474}
5475
5478 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5479 .TransformType(TypeWithAuto);
5480}
5481
5483 QualType TypeToReplaceAuto) {
5484 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5485 /*UseTypeSugar*/ false)
5486 .TransformType(TypeWithAuto);
5487}
5488
5490 QualType TypeToReplaceAuto) {
5491 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5492 /*UseTypeSugar*/ false)
5493 .TransformType(TypeWithAuto);
5494}
5495
5497 const Expr *Init) {
5498 if (isa<InitListExpr>(Init))
5499 Diag(VDecl->getLocation(),
5500 VDecl->isInitCapture()
5501 ? diag::err_init_capture_deduction_failure_from_init_list
5502 : diag::err_auto_var_deduction_failure_from_init_list)
5503 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
5504 else
5505 Diag(VDecl->getLocation(),
5506 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
5507 : diag::err_auto_var_deduction_failure)
5508 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5509 << Init->getSourceRange();
5510}
5511
5513 bool Diagnose) {
5514 assert(FD->getReturnType()->isUndeducedType());
5515
5516 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
5517 // within the return type from the call operator's type.
5519 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5520 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5521
5522 // For a generic lambda, instantiate the call operator if needed.
5523 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5525 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5526 if (!CallOp || CallOp->isInvalidDecl())
5527 return true;
5528
5529 // We might need to deduce the return type by instantiating the definition
5530 // of the operator() function.
5531 if (CallOp->getReturnType()->isUndeducedType()) {
5534 });
5535 }
5536 }
5537
5538 if (CallOp->isInvalidDecl())
5539 return true;
5540 assert(!CallOp->getReturnType()->isUndeducedType() &&
5541 "failed to deduce lambda return type");
5542
5543 // Build the new return type from scratch.
5544 CallingConv RetTyCC = FD->getReturnType()
5545 ->getPointeeType()
5546 ->castAs<FunctionType>()
5547 ->getCallConv();
5549 CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
5550 if (FD->getReturnType()->getAs<PointerType>())
5551 RetType = Context.getPointerType(RetType);
5552 else {
5553 assert(FD->getReturnType()->getAs<BlockPointerType>());
5554 RetType = Context.getBlockPointerType(RetType);
5555 }
5557 return false;
5558 }
5559
5563 });
5564 }
5565
5566 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
5567 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
5568 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
5569 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
5570 }
5571
5572 return StillUndeduced;
5573}
5574
5577 assert(FD->isImmediateEscalating());
5578
5580 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5581 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5582
5583 // For a generic lambda, instantiate the call operator if needed.
5584 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5586 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5587 if (!CallOp || CallOp->isInvalidDecl())
5588 return true;
5590 Loc, [&] { InstantiateFunctionDefinition(Loc, CallOp); });
5591 }
5592 return CallOp->isInvalidDecl();
5593 }
5594
5597 Loc, [&] { InstantiateFunctionDefinition(Loc, FD); });
5598 }
5599 return false;
5600}
5601
5603 const CXXMethodDecl *Method,
5604 QualType RawType,
5605 bool IsOtherRvr) {
5606 // C++20 [temp.func.order]p3.1, p3.2:
5607 // - The type X(M) is "rvalue reference to cv A" if the optional
5608 // ref-qualifier of M is && or if M has no ref-qualifier and the
5609 // positionally-corresponding parameter of the other transformed template
5610 // has rvalue reference type; if this determination depends recursively
5611 // upon whether X(M) is an rvalue reference type, it is not considered to
5612 // have rvalue reference type.
5613 //
5614 // - Otherwise, X(M) is "lvalue reference to cv A".
5615 assert(Method && !Method->isExplicitObjectMemberFunction() &&
5616 "expected a member function with no explicit object parameter");
5617
5618 RawType = Context.getQualifiedType(RawType, Method->getMethodQualifiers());
5619 if (Method->getRefQualifier() == RQ_RValue ||
5620 (IsOtherRvr && Method->getRefQualifier() == RQ_None))
5621 return Context.getRValueReferenceType(RawType);
5622 return Context.getLValueReferenceType(RawType);
5623}
5624
5626 Sema &S, FunctionTemplateDecl *FTD, int ArgIdx, QualType P, QualType A,
5627 ArrayRef<TemplateArgument> DeducedArgs, bool CheckConsistency) {
5628 MultiLevelTemplateArgumentList MLTAL(FTD, DeducedArgs,
5629 /*Final=*/true);
5631 S, ArgIdx != -1 ? ::getPackIndexForParam(S, FTD, MLTAL, ArgIdx) : -1);
5632 bool IsIncompleteSubstitution = false;
5633 // FIXME: A substitution can be incomplete on a non-structural part of the
5634 // type. Use the canonical type for now, until the TemplateInstantiator can
5635 // deal with that.
5636 QualType InstP = S.SubstType(P.getCanonicalType(), MLTAL, FTD->getLocation(),
5637 FTD->getDeclName(), &IsIncompleteSubstitution);
5638 if (InstP.isNull() && !IsIncompleteSubstitution)
5640 if (!CheckConsistency)
5642 if (IsIncompleteSubstitution)
5644
5645 // [temp.deduct.call]/4 - Check we produced a consistent deduction.
5646 // This handles just the cases that can appear when partial ordering.
5647 if (auto *PA = dyn_cast<PackExpansionType>(A);
5648 PA && !isa<PackExpansionType>(InstP))
5649 A = PA->getPattern();
5650 if (!S.Context.hasSameType(
5655}
5656
5657template <class T>
5659 Sema &S, FunctionTemplateDecl *FTD,
5664 Sema::SFINAETrap Trap(S);
5665
5666 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(FTD));
5667
5668 // C++26 [temp.deduct.type]p2:
5669 // [...] or if any template argument remains neither deduced nor
5670 // explicitly specified, template argument deduction fails.
5671 bool IsIncomplete = false;
5672 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
5674 S, FTD, /*IsDeduced=*/true, Deduced, Info, SugaredBuilder,
5675 CanonicalBuilder, /*PartialOrdering=*/true,
5676 /*CurrentInstantiationScope=*/nullptr,
5677 /*NumAlreadyConverted=*/0, &IsIncomplete);
5679 return Result;
5680
5681 // Form the template argument list from the deduced template arguments.
5682 TemplateArgumentList *SugaredDeducedArgumentList =
5683 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
5684 TemplateArgumentList *CanonicalDeducedArgumentList =
5685 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
5686
5687 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
5688
5689 // Substitute the deduced template arguments into the argument
5690 // and verify that the instantiated argument is both valid
5691 // and equivalent to the parameter.
5692 LocalInstantiationScope InstScope(S);
5693
5694 if (auto TDR = CheckDeductionConsistency(S, FTD, SugaredBuilder);
5696 return TDR;
5697
5700}
5701
5702/// Determine whether the function template \p FT1 is at least as
5703/// specialized as \p FT2.
5707 ArrayRef<QualType> Args1, ArrayRef<QualType> Args2, bool Args1Offset) {
5708 FunctionDecl *FD1 = FT1->getTemplatedDecl();
5709 FunctionDecl *FD2 = FT2->getTemplatedDecl();
5710 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
5711 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
5712 assert(Proto1 && Proto2 && "Function templates must have prototypes");
5713
5714 // C++26 [temp.deduct.partial]p3:
5715 // The types used to determine the ordering depend on the context in which
5716 // the partial ordering is done:
5717 // - In the context of a function call, the types used are those function
5718 // parameter types for which the function call has arguments.
5719 // - In the context of a call to a conversion operator, the return types
5720 // of the conversion function templates are used.
5721 // - In other contexts (14.6.6.2) the function template's function type
5722 // is used.
5723
5724 if (TPOC == TPOC_Other) {
5725 // We wouldn't be partial ordering these candidates if these didn't match.
5726 assert(Proto1->getMethodQuals() == Proto2->getMethodQuals() &&
5727 Proto1->getRefQualifier() == Proto2->getRefQualifier() &&
5728 Proto1->isVariadic() == Proto2->isVariadic() &&
5729 "shouldn't partial order functions with different qualifiers in a "
5730 "context where the function type is used");
5731
5732 assert(Args1.empty() && Args2.empty() &&
5733 "Only call context should have arguments");
5734 Args1 = Proto1->getParamTypes();
5735 Args2 = Proto2->getParamTypes();
5736 }
5737
5738 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
5739 SmallVector<DeducedTemplateArgument, 4> Deduced(TemplateParams->size());
5741
5742 bool HasDeducedAnyParamFromReturnType = false;
5743 if (TPOC != TPOC_Call) {
5745 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
5746 Info, Deduced, TDF_None, PartialOrderingKind::Call,
5747 /*DeducedFromArrayBound=*/false,
5748 &HasDeducedAnyParamFromReturnType) !=
5750 return false;
5751 }
5752
5753 llvm::SmallBitVector HasDeducedParam;
5754 if (TPOC != TPOC_Conversion) {
5755 HasDeducedParam.resize(Args2.size());
5756 if (DeduceTemplateArguments(S, TemplateParams, Args2, Args1, Info, Deduced,
5757 TDF_None, PartialOrderingKind::Call,
5758 /*HasDeducedAnyParam=*/nullptr,
5759 &HasDeducedParam) !=
5761 return false;
5762 }
5763
5764 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
5766 S, Info.getLocation(), FT2, DeducedArgs,
5768 if (Inst.isInvalid())
5769 return false;
5770
5771 bool AtLeastAsSpecialized;
5773 AtLeastAsSpecialized =
5774 ::FinishTemplateArgumentDeduction(
5775 S, FT2, Deduced, Info,
5776 [&](Sema &S, FunctionTemplateDecl *FTD,
5777 ArrayRef<TemplateArgument> DeducedArgs) {
5778 // As a provisional fix for a core issue that does not
5779 // exist yet, which may be related to CWG2160, only check the
5780 // consistency of parameters and return types which participated
5781 // in deduction. We will still try to substitute them though.
5782 if (TPOC != TPOC_Call) {
5783 if (auto TDR = ::CheckDeductionConsistency(
5784 S, FTD, /*ArgIdx=*/-1, Proto2->getReturnType(),
5785 Proto1->getReturnType(), DeducedArgs,
5786 /*CheckConsistency=*/HasDeducedAnyParamFromReturnType);
5787 TDR != TemplateDeductionResult::Success)
5788 return TDR;
5789 }
5790
5791 if (TPOC == TPOC_Conversion)
5792 return TemplateDeductionResult::Success;
5793
5794 return ::DeduceForEachType(
5795 S, TemplateParams, Args2, Args1, Info, Deduced,
5796 PartialOrderingKind::Call, /*FinishingDeduction=*/true,
5797 [&](Sema &S, TemplateParameterList *, int ParamIdx,
5798 int ArgIdx, QualType P, QualType A,
5799 TemplateDeductionInfo &Info,
5800 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5801 PartialOrderingKind) {
5802 if (ArgIdx != -1)
5803 ArgIdx -= Args1Offset;
5804 return ::CheckDeductionConsistency(
5805 S, FTD, ArgIdx, P, A, DeducedArgs,
5806 /*CheckConsistency=*/HasDeducedParam[ParamIdx]);
5807 });
5809 });
5810 if (!AtLeastAsSpecialized)
5811 return false;
5812
5813 // C++0x [temp.deduct.partial]p11:
5814 // In most cases, all template parameters must have values in order for
5815 // deduction to succeed, but for partial ordering purposes a template
5816 // parameter may remain without a value provided it is not used in the
5817 // types being used for partial ordering. [ Note: a template parameter used
5818 // in a non-deduced context is considered used. -end note]
5819 unsigned ArgIdx = 0, NumArgs = Deduced.size();
5820 for (; ArgIdx != NumArgs; ++ArgIdx)
5821 if (Deduced[ArgIdx].isNull())
5822 break;
5823
5824 if (ArgIdx == NumArgs) {
5825 // All template arguments were deduced. FT1 is at least as specialized
5826 // as FT2.
5827 return true;
5828 }
5829
5830 // Figure out which template parameters were used.
5831 llvm::SmallBitVector UsedParameters(TemplateParams->size());
5832 switch (TPOC) {
5833 case TPOC_Call:
5834 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
5835 ::MarkUsedTemplateParameters(S.Context, Args2[I], /*OnlyDeduced=*/false,
5836 TemplateParams->getDepth(), UsedParameters);
5837 break;
5838
5839 case TPOC_Conversion:
5840 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(),
5841 /*OnlyDeduced=*/false,
5842 TemplateParams->getDepth(), UsedParameters);
5843 break;
5844
5845 case TPOC_Other:
5846 // We do not deduce template arguments from the exception specification
5847 // when determining the primary template of a function template
5848 // specialization or when taking the address of a function template.
5849 // Therefore, we do not mark template parameters in the exception
5850 // specification as used during partial ordering to prevent the following
5851 // from being ambiguous:
5852 //
5853 // template<typename T, typename U>
5854 // void f(U) noexcept(noexcept(T())); // #1
5855 //
5856 // template<typename T>
5857 // void f(T*) noexcept; // #2
5858 //
5859 // template<>
5860 // void f<int>(int*) noexcept; // explicit specialization of #2
5861 //
5862 // Although there is no corresponding wording in the standard, this seems
5863 // to be the intended behavior given the definition of
5864 // 'deduction substitution loci' in [temp.deduct].
5866 S.Context,
5868 /*OnlyDeduced=*/false, TemplateParams->getDepth(), UsedParameters);
5869 break;
5870 }
5871
5872 for (; ArgIdx != NumArgs; ++ArgIdx)
5873 // If this argument had no value deduced but was used in one of the types
5874 // used for partial ordering, then deduction fails.
5875 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
5876 return false;
5877
5878 return true;
5879}
5880
5883 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
5884 QualType RawObj1Ty, QualType RawObj2Ty, bool Reversed) {
5887 const FunctionDecl *FD1 = FT1->getTemplatedDecl();
5888 const FunctionDecl *FD2 = FT2->getTemplatedDecl();
5889 bool ShouldConvert1 = false;
5890 bool ShouldConvert2 = false;
5891 bool Args1Offset = false;
5892 bool Args2Offset = false;
5893 QualType Obj1Ty;
5894 QualType Obj2Ty;
5895 if (TPOC == TPOC_Call) {
5896 const FunctionProtoType *Proto1 =
5897 FD1->getType()->castAs<FunctionProtoType>();
5898 const FunctionProtoType *Proto2 =
5899 FD2->getType()->castAs<FunctionProtoType>();
5900
5901 // - In the context of a function call, the function parameter types are
5902 // used.
5903 const CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
5904 const CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
5905 // C++20 [temp.func.order]p3
5906 // [...] Each function template M that is a member function is
5907 // considered to have a new first parameter of type
5908 // X(M), described below, inserted in its function parameter list.
5909 //
5910 // Note that we interpret "that is a member function" as
5911 // "that is a member function with no expicit object argument".
5912 // Otherwise the ordering rules for methods with expicit objet arguments
5913 // against anything else make no sense.
5914
5915 bool NonStaticMethod1 = Method1 && !Method1->isStatic(),
5916 NonStaticMethod2 = Method2 && !Method2->isStatic();
5917
5918 auto Params1Begin = Proto1->param_type_begin(),
5919 Params2Begin = Proto2->param_type_begin();
5920
5921 size_t NumComparedArguments = NumCallArguments1;
5922
5923 if (auto OO = FD1->getOverloadedOperator();
5924 (NonStaticMethod1 && NonStaticMethod2) ||
5925 (OO != OO_None && OO != OO_Call && OO != OO_Subscript)) {
5926 ShouldConvert1 =
5927 NonStaticMethod1 && !Method1->hasCXXExplicitFunctionObjectParameter();
5928 ShouldConvert2 =
5929 NonStaticMethod2 && !Method2->hasCXXExplicitFunctionObjectParameter();
5930 NumComparedArguments += 1;
5931
5932 if (ShouldConvert1) {
5933 bool IsRValRef2 =
5934 ShouldConvert2
5935 ? Method2->getRefQualifier() == RQ_RValue
5936 : Proto2->param_type_begin()[0]->isRValueReferenceType();
5937 // Compare 'this' from Method1 against first parameter from Method2.
5938 Obj1Ty = GetImplicitObjectParameterType(this->Context, Method1,
5939 RawObj1Ty, IsRValRef2);
5940 Args1.push_back(Obj1Ty);
5941 Args1Offset = true;
5942 }
5943 if (ShouldConvert2) {
5944 bool IsRValRef1 =
5945 ShouldConvert1
5946 ? Method1->getRefQualifier() == RQ_RValue
5947 : Proto1->param_type_begin()[0]->isRValueReferenceType();
5948 // Compare 'this' from Method2 against first parameter from Method1.
5949 Obj2Ty = GetImplicitObjectParameterType(this->Context, Method2,
5950 RawObj2Ty, IsRValRef1);
5951 Args2.push_back(Obj2Ty);
5952 Args2Offset = true;
5953 }
5954 } else {
5955 if (NonStaticMethod1 && Method1->hasCXXExplicitFunctionObjectParameter())
5956 Params1Begin += 1;
5957 if (NonStaticMethod2 && Method2->hasCXXExplicitFunctionObjectParameter())
5958 Params2Begin += 1;
5959 }
5960 Args1.insert(Args1.end(), Params1Begin, Proto1->param_type_end());
5961 Args2.insert(Args2.end(), Params2Begin, Proto2->param_type_end());
5962
5963 // C++ [temp.func.order]p5:
5964 // The presence of unused ellipsis and default arguments has no effect on
5965 // the partial ordering of function templates.
5966 Args1.resize(std::min(Args1.size(), NumComparedArguments));
5967 Args2.resize(std::min(Args2.size(), NumComparedArguments));
5968
5969 if (Reversed)
5970 std::reverse(Args2.begin(), Args2.end());
5971 } else {
5972 assert(!Reversed && "Only call context could have reversed arguments");
5973 }
5974 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, Args1,
5975 Args2, Args2Offset);
5976 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, Args2,
5977 Args1, Args1Offset);
5978 // C++ [temp.deduct.partial]p10:
5979 // F is more specialized than G if F is at least as specialized as G and G
5980 // is not at least as specialized as F.
5981 if (Better1 != Better2) // We have a clear winner
5982 return Better1 ? FT1 : FT2;
5983
5984 if (!Better1 && !Better2) // Neither is better than the other
5985 return nullptr;
5986
5987 // C++ [temp.deduct.partial]p11:
5988 // ... and if G has a trailing function parameter pack for which F does not
5989 // have a corresponding parameter, and if F does not have a trailing
5990 // function parameter pack, then F is more specialized than G.
5991
5992 SmallVector<QualType> Param1;
5993 Param1.reserve(FD1->param_size() + ShouldConvert1);
5994 if (ShouldConvert1)
5995 Param1.push_back(Obj1Ty);
5996 for (const auto &P : FD1->parameters())
5997 Param1.push_back(P->getType());
5998
5999 SmallVector<QualType> Param2;
6000 Param2.reserve(FD2->param_size() + ShouldConvert2);
6001 if (ShouldConvert2)
6002 Param2.push_back(Obj2Ty);
6003 for (const auto &P : FD2->parameters())
6004 Param2.push_back(P->getType());
6005
6006 unsigned NumParams1 = Param1.size();
6007 unsigned NumParams2 = Param2.size();
6008
6009 bool Variadic1 =
6010 FD1->param_size() && FD1->parameters().back()->isParameterPack();
6011 bool Variadic2 =
6012 FD2->param_size() && FD2->parameters().back()->isParameterPack();
6013 if (Variadic1 != Variadic2) {
6014 if (Variadic1 && NumParams1 > NumParams2)
6015 return FT2;
6016 if (Variadic2 && NumParams2 > NumParams1)
6017 return FT1;
6018 }
6019
6020 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
6021 // there is no wording or even resolution for this issue.
6022 for (int i = 0, e = std::min(NumParams1, NumParams2); i < e; ++i) {
6023 QualType T1 = Param1[i].getCanonicalType();
6024 QualType T2 = Param2[i].getCanonicalType();
6025 auto *TST1 = dyn_cast<TemplateSpecializationType>(T1);
6026 auto *TST2 = dyn_cast<TemplateSpecializationType>(T2);
6027 if (!TST1 || !TST2)
6028 continue;
6029 const TemplateArgument &TA1 = TST1->template_arguments().back();
6030 if (TA1.getKind() == TemplateArgument::Pack) {
6031 assert(TST1->template_arguments().size() ==
6032 TST2->template_arguments().size());
6033 const TemplateArgument &TA2 = TST2->template_arguments().back();
6034 assert(TA2.getKind() == TemplateArgument::Pack);
6035 unsigned PackSize1 = TA1.pack_size();
6036 unsigned PackSize2 = TA2.pack_size();
6037 bool IsPackExpansion1 =
6038 PackSize1 && TA1.pack_elements().back().isPackExpansion();
6039 bool IsPackExpansion2 =
6040 PackSize2 && TA2.pack_elements().back().isPackExpansion();
6041 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
6042 if (PackSize1 > PackSize2 && IsPackExpansion1)
6043 return FT2;
6044 if (PackSize1 < PackSize2 && IsPackExpansion2)
6045 return FT1;
6046 }
6047 }
6048 }
6049
6050 if (!Context.getLangOpts().CPlusPlus20)
6051 return nullptr;
6052
6053 // Match GCC on not implementing [temp.func.order]p6.2.1.
6054
6055 // C++20 [temp.func.order]p6:
6056 // If deduction against the other template succeeds for both transformed
6057 // templates, constraints can be considered as follows:
6058
6059 // C++20 [temp.func.order]p6.1:
6060 // If their template-parameter-lists (possibly including template-parameters
6061 // invented for an abbreviated function template ([dcl.fct])) or function
6062 // parameter lists differ in length, neither template is more specialized
6063 // than the other.
6066 if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
6067 return nullptr;
6068
6069 // C++20 [temp.func.order]p6.2.2:
6070 // Otherwise, if the corresponding template-parameters of the
6071 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6072 // function parameters that positionally correspond between the two
6073 // templates are not of the same type, neither template is more specialized
6074 // than the other.
6075 if (!TemplateParameterListsAreEqual(TPL1, TPL2, false,
6077 return nullptr;
6078
6079 // [dcl.fct]p5:
6080 // Any top-level cv-qualifiers modifying a parameter type are deleted when
6081 // forming the function type.
6082 for (unsigned i = 0; i < NumParams1; ++i)
6083 if (!Context.hasSameUnqualifiedType(Param1[i], Param2[i]))
6084 return nullptr;
6085
6086 // C++20 [temp.func.order]p6.3:
6087 // Otherwise, if the context in which the partial ordering is done is
6088 // that of a call to a conversion function and the return types of the
6089 // templates are not the same, then neither template is more specialized
6090 // than the other.
6091 if (TPOC == TPOC_Conversion &&
6093 return nullptr;
6094
6096 FT1->getAssociatedConstraints(AC1);
6097 FT2->getAssociatedConstraints(AC2);
6098 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6099 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
6100 return nullptr;
6101 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
6102 return nullptr;
6103 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6104 return nullptr;
6105 return AtLeastAsConstrained1 ? FT1 : FT2;
6106}
6107
6110 TemplateSpecCandidateSet &FailedCandidates,
6111 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
6112 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
6113 bool Complain, QualType TargetType) {
6114 if (SpecBegin == SpecEnd) {
6115 if (Complain) {
6116 Diag(Loc, NoneDiag);
6117 FailedCandidates.NoteCandidates(*this, Loc);
6118 }
6119 return SpecEnd;
6120 }
6121
6122 if (SpecBegin + 1 == SpecEnd)
6123 return SpecBegin;
6124
6125 // Find the function template that is better than all of the templates it
6126 // has been compared to.
6127 UnresolvedSetIterator Best = SpecBegin;
6128 FunctionTemplateDecl *BestTemplate
6129 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
6130 assert(BestTemplate && "Not a function template specialization?");
6131 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
6132 FunctionTemplateDecl *Challenger
6133 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6134 assert(Challenger && "Not a function template specialization?");
6135 if (declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6136 Loc, TPOC_Other, 0),
6137 Challenger)) {
6138 Best = I;
6139 BestTemplate = Challenger;
6140 }
6141 }
6142
6143 // Make sure that the "best" function template is more specialized than all
6144 // of the others.
6145 bool Ambiguous = false;
6146 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6147 FunctionTemplateDecl *Challenger
6148 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6149 if (I != Best &&
6150 !declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6151 Loc, TPOC_Other, 0),
6152 BestTemplate)) {
6153 Ambiguous = true;
6154 break;
6155 }
6156 }
6157
6158 if (!Ambiguous) {
6159 // We found an answer. Return it.
6160 return Best;
6161 }
6162
6163 // Diagnose the ambiguity.
6164 if (Complain) {
6165 Diag(Loc, AmbigDiag);
6166
6167 // FIXME: Can we order the candidates in some sane way?
6168 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6169 PartialDiagnostic PD = CandidateDiag;
6170 const auto *FD = cast<FunctionDecl>(*I);
6172 FD->getPrimaryTemplate()->getTemplateParameters(),
6173 *FD->getTemplateSpecializationArgs());
6174 if (!TargetType.isNull())
6175 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
6176 Diag((*I)->getLocation(), PD);
6177 }
6178 }
6179
6180 return SpecEnd;
6181}
6182
6184 FunctionDecl *FD2) {
6185 assert(!FD1->getDescribedTemplate() && !FD2->getDescribedTemplate() &&
6186 "not for function templates");
6187 assert(!FD1->isFunctionTemplateSpecialization() ||
6188 isa<CXXConversionDecl>(FD1));
6189 assert(!FD2->isFunctionTemplateSpecialization() ||
6190 isa<CXXConversionDecl>(FD2));
6191
6192 FunctionDecl *F1 = FD1;
6194 F1 = P;
6195
6196 FunctionDecl *F2 = FD2;
6198 F2 = P;
6199
6201 F1->getAssociatedConstraints(AC1);
6202 F2->getAssociatedConstraints(AC2);
6203 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6204 if (IsAtLeastAsConstrained(F1, AC1, F2, AC2, AtLeastAsConstrained1))
6205 return nullptr;
6206 if (IsAtLeastAsConstrained(F2, AC2, F1, AC1, AtLeastAsConstrained2))
6207 return nullptr;
6208 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6209 return nullptr;
6210 return AtLeastAsConstrained1 ? FD1 : FD2;
6211}
6212
6213/// Determine whether one partial specialization, P1, is at least as
6214/// specialized than another, P2.
6215///
6216/// \tparam TemplateLikeDecl The kind of P2, which must be a
6217/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
6218/// \param T1 The injected-class-name of P1 (faked for a variable template).
6219/// \param T2 The injected-class-name of P2 (faked for a variable template).
6220template<typename TemplateLikeDecl>
6222 TemplateLikeDecl *P2,
6223 TemplateDeductionInfo &Info) {
6224 // C++ [temp.class.order]p1:
6225 // For two class template partial specializations, the first is at least as
6226 // specialized as the second if, given the following rewrite to two
6227 // function templates, the first function template is at least as
6228 // specialized as the second according to the ordering rules for function
6229 // templates (14.6.6.2):
6230 // - the first function template has the same template parameters as the
6231 // first partial specialization and has a single function parameter
6232 // whose type is a class template specialization with the template
6233 // arguments of the first partial specialization, and
6234 // - the second function template has the same template parameters as the
6235 // second partial specialization and has a single function parameter
6236 // whose type is a class template specialization with the template
6237 // arguments of the second partial specialization.
6238 //
6239 // Rather than synthesize function templates, we merely perform the
6240 // equivalent partial ordering by performing deduction directly on
6241 // the template arguments of the class template partial
6242 // specializations. This computation is slightly simpler than the
6243 // general problem of function template partial ordering, because
6244 // class template partial specializations are more constrained. We
6245 // know that every template parameter is deducible from the class
6246 // template partial specialization's template arguments, for
6247 // example.
6249
6250 // Determine whether P1 is at least as specialized as P2.
6251 Deduced.resize(P2->getTemplateParameters()->size());
6253 S, P2->getTemplateParameters(), T2, T1, Info, Deduced, TDF_None,
6254 PartialOrderingKind::Call, /*DeducedFromArrayBound=*/false,
6255 /*HasDeducedAnyParam=*/nullptr) != TemplateDeductionResult::Success)
6256 return false;
6257
6258 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
6259 Deduced.end());
6260 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
6261 Info);
6262 if (Inst.isInvalid())
6263 return false;
6264
6265 const auto *TST1 = cast<TemplateSpecializationType>(T1);
6266
6267 Sema::SFINAETrap Trap(S);
6268
6271 Result = ::FinishTemplateArgumentDeduction(
6272 S, P2, /*IsPartialOrdering=*/true, TST1->template_arguments(), Deduced,
6273 Info);
6274 });
6275
6277 return false;
6278
6279 if (Trap.hasErrorOccurred())
6280 return false;
6281
6282 return true;
6283}
6284
6285namespace {
6286// A dummy class to return nullptr instead of P2 when performing "more
6287// specialized than primary" check.
6288struct GetP2 {
6289 template <typename T1, typename T2,
6290 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6291 T2 *operator()(T1 *, T2 *P2) {
6292 return P2;
6293 }
6294 template <typename T1, typename T2,
6295 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6296 T1 *operator()(T1 *, T2 *) {
6297 return nullptr;
6298 }
6299};
6300
6301// The assumption is that two template argument lists have the same size.
6302struct TemplateArgumentListAreEqual {
6303 ASTContext &Ctx;
6304 TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
6305
6306 template <typename T1, typename T2,
6307 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6308 bool operator()(T1 *PS1, T2 *PS2) {
6309 ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
6310 Args2 = PS2->getTemplateArgs().asArray();
6311
6312 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6313 // We use profile, instead of structural comparison of the arguments,
6314 // because canonicalization can't do the right thing for dependent
6315 // expressions.
6316 llvm::FoldingSetNodeID IDA, IDB;
6317 Args1[I].Profile(IDA, Ctx);
6318 Args2[I].Profile(IDB, Ctx);
6319 if (IDA != IDB)
6320 return false;
6321 }
6322 return true;
6323 }
6324
6325 template <typename T1, typename T2,
6326 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6327 bool operator()(T1 *Spec, T2 *Primary) {
6328 ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
6329 Args2 = Primary->getInjectedTemplateArgs(Ctx);
6330
6331 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6332 // We use profile, instead of structural comparison of the arguments,
6333 // because canonicalization can't do the right thing for dependent
6334 // expressions.
6335 llvm::FoldingSetNodeID IDA, IDB;
6336 Args1[I].Profile(IDA, Ctx);
6337 // Unlike the specialization arguments, the injected arguments are not
6338 // always canonical.
6339 Ctx.getCanonicalTemplateArgument(Args2[I]).Profile(IDB, Ctx);
6340 if (IDA != IDB)
6341 return false;
6342 }
6343 return true;
6344 }
6345};
6346} // namespace
6347
6348/// Returns the more specialized template specialization between T1/P1 and
6349/// T2/P2.
6350/// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
6351/// specialization and T2/P2 is the primary template.
6352/// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
6353///
6354/// \param T1 the type of the first template partial specialization
6355///
6356/// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
6357/// template partial specialization; otherwise, the type of the
6358/// primary template.
6359///
6360/// \param P1 the first template partial specialization
6361///
6362/// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
6363/// partial specialization; otherwise, the primary template.
6364///
6365/// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
6366/// more specialized, returns nullptr if P1 is not more specialized.
6367/// - otherwise, returns the more specialized template partial
6368/// specialization. If neither partial specialization is more
6369/// specialized, returns NULL.
6370template <typename TemplateLikeDecl, typename PrimaryDel>
6371static TemplateLikeDecl *
6372getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
6373 PrimaryDel *P2, TemplateDeductionInfo &Info) {
6374 constexpr bool IsMoreSpecialThanPrimaryCheck =
6375 !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
6376
6377 bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, Info);
6378 if (IsMoreSpecialThanPrimaryCheck && !Better1)
6379 return nullptr;
6380
6381 bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1, Info);
6382 if (IsMoreSpecialThanPrimaryCheck && !Better2)
6383 return P1;
6384
6385 // C++ [temp.deduct.partial]p10:
6386 // F is more specialized than G if F is at least as specialized as G and G
6387 // is not at least as specialized as F.
6388 if (Better1 != Better2) // We have a clear winner
6389 return Better1 ? P1 : GetP2()(P1, P2);
6390
6391 if (!Better1 && !Better2)
6392 return nullptr;
6393
6394 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
6395 // there is no wording or even resolution for this issue.
6396 auto *TST1 = cast<TemplateSpecializationType>(T1);
6397 auto *TST2 = cast<TemplateSpecializationType>(T2);
6398 const TemplateArgument &TA1 = TST1->template_arguments().back();
6399 if (TA1.getKind() == TemplateArgument::Pack) {
6400 assert(TST1->template_arguments().size() ==
6401 TST2->template_arguments().size());
6402 const TemplateArgument &TA2 = TST2->template_arguments().back();
6403 assert(TA2.getKind() == TemplateArgument::Pack);
6404 unsigned PackSize1 = TA1.pack_size();
6405 unsigned PackSize2 = TA2.pack_size();
6406 bool IsPackExpansion1 =
6407 PackSize1 && TA1.pack_elements().back().isPackExpansion();
6408 bool IsPackExpansion2 =
6409 PackSize2 && TA2.pack_elements().back().isPackExpansion();
6410 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
6411 if (PackSize1 > PackSize2 && IsPackExpansion1)
6412 return GetP2()(P1, P2);
6413 if (PackSize1 < PackSize2 && IsPackExpansion2)
6414 return P1;
6415 }
6416 }
6417
6418 if (!S.Context.getLangOpts().CPlusPlus20)
6419 return nullptr;
6420
6421 // Match GCC on not implementing [temp.func.order]p6.2.1.
6422
6423 // C++20 [temp.func.order]p6:
6424 // If deduction against the other template succeeds for both transformed
6425 // templates, constraints can be considered as follows:
6426
6427 TemplateParameterList *TPL1 = P1->getTemplateParameters();
6428 TemplateParameterList *TPL2 = P2->getTemplateParameters();
6429 if (TPL1->size() != TPL2->size())
6430 return nullptr;
6431
6432 // C++20 [temp.func.order]p6.2.2:
6433 // Otherwise, if the corresponding template-parameters of the
6434 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6435 // function parameters that positionally correspond between the two
6436 // templates are not of the same type, neither template is more specialized
6437 // than the other.
6438 if (!S.TemplateParameterListsAreEqual(TPL1, TPL2, false,
6440 return nullptr;
6441
6442 if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
6443 return nullptr;
6444
6446 P1->getAssociatedConstraints(AC1);
6447 P2->getAssociatedConstraints(AC2);
6448 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6449 if (S.IsAtLeastAsConstrained(P1, AC1, P2, AC2, AtLeastAsConstrained1) ||
6450 (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
6451 return nullptr;
6452 if (S.IsAtLeastAsConstrained(P2, AC2, P1, AC1, AtLeastAsConstrained2))
6453 return nullptr;
6454 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6455 return nullptr;
6456 return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
6457}
6458
6466
6468 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6469}
6470
6473 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
6474 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
6475 QualType PartialT = Spec->getInjectedSpecializationType();
6476
6478 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6479 if (MaybeSpec)
6480 Info.clearSFINAEDiagnostic();
6481 return MaybeSpec;
6482}
6483
6488 // Pretend the variable template specializations are class template
6489 // specializations and form a fake injected class name type for comparison.
6490 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
6491 "the partial specializations being compared should specialize"
6492 " the same template.");
6495 Name, PS1->getTemplateArgs().asArray());
6497 Name, PS2->getTemplateArgs().asArray());
6498
6500 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6501}
6502
6505 VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
6506 TemplateName Name(Primary);
6508 Name, Primary->getInjectedTemplateArgs(Context));
6510 Name, Spec->getTemplateArgs().asArray());
6511
6513 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6514 if (MaybeSpec)
6515 Info.clearSFINAEDiagnostic();
6516 return MaybeSpec;
6517}
6518
6521 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
6522 bool PartialOrdering, bool *MatchedPackOnParmToNonPackOnArg) {
6523 // C++1z [temp.arg.template]p4: (DR 150)
6524 // A template template-parameter P is at least as specialized as a
6525 // template template-argument A if, given the following rewrite to two
6526 // function templates...
6527
6528 // Rather than synthesize function templates, we merely perform the
6529 // equivalent partial ordering by performing deduction directly on
6530 // the template parameter lists of the template template parameters.
6531 //
6533
6536 SourceRange(P->getTemplateLoc(), P->getRAngleLoc()));
6537 if (Inst.isInvalid())
6538 return false;
6539
6540 // Given an invented class template X with the template parameter list of
6541 // A (including default arguments):
6542 // - Each function template has a single function parameter whose type is
6543 // a specialization of X with template arguments corresponding to the
6544 // template parameters from the respective function template
6546
6547 // Check P's arguments against A's parameter list. This will fill in default
6548 // template arguments as needed. AArgs are already correct by construction.
6549 // We can't just use CheckTemplateIdType because that will expand alias
6550 // templates.
6551 SmallVector<TemplateArgument, 4> PArgs(P->getInjectedTemplateArgs(Context));
6552 {
6553 TemplateArgumentListInfo PArgList(P->getLAngleLoc(),
6554 P->getRAngleLoc());
6555 for (unsigned I = 0, N = P->size(); I != N; ++I) {
6556 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
6557 // expansions, to form an "as written" argument list.
6558 TemplateArgument Arg = PArgs[I];
6559 if (Arg.getKind() == TemplateArgument::Pack) {
6560 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
6561 Arg = *Arg.pack_begin();
6562 }
6564 Arg, QualType(), P->getParam(I)->getLocation()));
6565 }
6566 PArgs.clear();
6567
6568 // C++1z [temp.arg.template]p3:
6569 // If the rewrite produces an invalid type, then P is not at least as
6570 // specialized as A.
6571 SmallVector<TemplateArgument, 4> CanonicalPArgs;
6573 AArg, ArgLoc, PArgList, DefaultArgs, false, PArgs, CanonicalPArgs,
6574 /*UpdateArgsWithConversions=*/true,
6575 /*ConstraintsNotSatisfied=*/nullptr,
6576 /*PartialOrderingTTP=*/true, MatchedPackOnParmToNonPackOnArg))
6577 return false;
6578 }
6579
6580 // Determine whether P1 is at least as specialized as P2.
6581 TemplateDeductionInfo Info(ArgLoc, A->getDepth());
6583 Deduced.resize(A->size());
6584
6585 // ... the function template corresponding to P is at least as specialized
6586 // as the function template corresponding to A according to the partial
6587 // ordering rules for function templates.
6588
6589 // Provisional resolution for CWG2398: Regarding temp.arg.template]p4, when
6590 // applying the partial ordering rules for function templates on
6591 // the rewritten template template parameters:
6592 // - In a deduced context, the matching of packs versus fixed-size needs to
6593 // be inverted between Ps and As. On non-deduced context, matching needs to
6594 // happen both ways, according to [temp.arg.template]p3, but this is
6595 // currently implemented as a special case elsewhere.
6597 *this, A, AArgs, PArgs, Info, Deduced,
6598 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/true,
6599 PartialOrdering ? PackFold::ArgumentToParameter : PackFold::Both,
6600 /*HasDeducedAnyParam=*/nullptr)) {
6602 if (MatchedPackOnParmToNonPackOnArg &&
6604 *MatchedPackOnParmToNonPackOnArg = true;
6605 break;
6606
6608 Diag(AArg->getLocation(), diag::err_template_param_list_different_arity)
6609 << (A->size() > P->size()) << /*isTemplateTemplateParameter=*/true
6610 << SourceRange(A->getTemplateLoc(), P->getRAngleLoc());
6611 return false;
6613 Diag(AArg->getLocation(), diag::err_non_deduced_mismatch)
6614 << Info.FirstArg << Info.SecondArg;
6615 return false;
6618 diag::err_inconsistent_deduction)
6619 << Info.FirstArg << Info.SecondArg;
6620 return false;
6622 return false;
6623
6624 // None of these should happen for a plain deduction.
6639 llvm_unreachable("Unexpected Result");
6640 }
6641
6642 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
6643
6646 TDK = ::FinishTemplateArgumentDeduction(
6647 *this, AArg, /*IsPartialOrdering=*/true, PArgs, Deduced, Info);
6648 });
6649 switch (TDK) {
6651 return true;
6652
6653 // It doesn't seem possible to get a non-deduced mismatch when partial
6654 // ordering TTPs.
6656 llvm_unreachable("Unexpected NonDeducedMismatch");
6657
6658 // Substitution failures should have already been diagnosed.
6662 return false;
6663
6664 // None of these should happen when just converting deduced arguments.
6679 llvm_unreachable("Unexpected Result");
6680 }
6681 llvm_unreachable("Unexpected TDK");
6682}
6683
6684namespace {
6685struct MarkUsedTemplateParameterVisitor : DynamicRecursiveASTVisitor {
6686 llvm::SmallBitVector &Used;
6687 unsigned Depth;
6688
6689 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used,
6690 unsigned Depth)
6691 : Used(Used), Depth(Depth) { }
6692
6693 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
6694 if (T->getDepth() == Depth)
6695 Used[T->getIndex()] = true;
6696 return true;
6697 }
6698
6699 bool TraverseTemplateName(TemplateName Template) override {
6700 if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
6701 Template.getAsTemplateDecl()))
6702 if (TTP->getDepth() == Depth)
6703 Used[TTP->getIndex()] = true;
6705 return true;
6706 }
6707
6708 bool VisitDeclRefExpr(DeclRefExpr *E) override {
6709 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
6710 if (NTTP->getDepth() == Depth)
6711 Used[NTTP->getIndex()] = true;
6712 return true;
6713 }
6714};
6715}
6716
6717/// Mark the template parameters that are used by the given
6718/// expression.
6719static void
6721 const Expr *E,
6722 bool OnlyDeduced,
6723 unsigned Depth,
6724 llvm::SmallBitVector &Used) {
6725 if (!OnlyDeduced) {
6726 MarkUsedTemplateParameterVisitor(Used, Depth)
6727 .TraverseStmt(const_cast<Expr *>(E));
6728 return;
6729 }
6730
6731 // We can deduce from a pack expansion.
6732 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
6733 E = Expansion->getPattern();
6734
6736 if (!NTTP)
6737 return;
6738
6739 if (NTTP->getDepth() == Depth)
6740 Used[NTTP->getIndex()] = true;
6741
6742 // In C++17 mode, additional arguments may be deduced from the type of a
6743 // non-type argument.
6744 if (Ctx.getLangOpts().CPlusPlus17)
6745 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
6746}
6747
6748/// Mark the template parameters that are used by the given
6749/// nested name specifier.
6750static void
6753 bool OnlyDeduced,
6754 unsigned Depth,
6755 llvm::SmallBitVector &Used) {
6756 if (!NNS)
6757 return;
6758
6759 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
6760 Used);
6762 OnlyDeduced, Depth, Used);
6763}
6764
6765/// Mark the template parameters that are used by the given
6766/// template name.
6767static void
6769 TemplateName Name,
6770 bool OnlyDeduced,
6771 unsigned Depth,
6772 llvm::SmallBitVector &Used) {
6773 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
6775 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
6776 if (TTP->getDepth() == Depth)
6777 Used[TTP->getIndex()] = true;
6778 }
6779 return;
6780 }
6781
6782 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
6783 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
6784 Depth, Used);
6785 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
6786 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
6787 Depth, Used);
6788}
6789
6790/// Mark the template parameters that are used by the given
6791/// type.
6792static void
6794 bool OnlyDeduced,
6795 unsigned Depth,
6796 llvm::SmallBitVector &Used) {
6797 if (T.isNull())
6798 return;
6799
6800 // Non-dependent types have nothing deducible
6801 if (!T->isDependentType())
6802 return;
6803
6804 T = Ctx.getCanonicalType(T);
6805 switch (T->getTypeClass()) {
6806 case Type::Pointer:
6808 cast<PointerType>(T)->getPointeeType(),
6809 OnlyDeduced,
6810 Depth,
6811 Used);
6812 break;
6813
6814 case Type::BlockPointer:
6816 cast<BlockPointerType>(T)->getPointeeType(),
6817 OnlyDeduced,
6818 Depth,
6819 Used);
6820 break;
6821
6822 case Type::LValueReference:
6823 case Type::RValueReference:
6825 cast<ReferenceType>(T)->getPointeeType(),
6826 OnlyDeduced,
6827 Depth,
6828 Used);
6829 break;
6830
6831 case Type::MemberPointer: {
6832 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
6833 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
6834 Depth, Used);
6835 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
6836 OnlyDeduced, Depth, Used);
6837 break;
6838 }
6839
6840 case Type::DependentSizedArray:
6842 cast<DependentSizedArrayType>(T)->getSizeExpr(),
6843 OnlyDeduced, Depth, Used);
6844 // Fall through to check the element type
6845 [[fallthrough]];
6846
6847 case Type::ConstantArray:
6848 case Type::IncompleteArray:
6849 case Type::ArrayParameter:
6851 cast<ArrayType>(T)->getElementType(),
6852 OnlyDeduced, Depth, Used);
6853 break;
6854 case Type::Vector:
6855 case Type::ExtVector:
6857 cast<VectorType>(T)->getElementType(),
6858 OnlyDeduced, Depth, Used);
6859 break;
6860
6861 case Type::DependentVector: {
6862 const auto *VecType = cast<DependentVectorType>(T);
6863 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6864 Depth, Used);
6865 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
6866 Used);
6867 break;
6868 }
6869 case Type::DependentSizedExtVector: {
6870 const DependentSizedExtVectorType *VecType
6871 = cast<DependentSizedExtVectorType>(T);
6872 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6873 Depth, Used);
6874 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
6875 Depth, Used);
6876 break;
6877 }
6878
6879 case Type::DependentAddressSpace: {
6880 const DependentAddressSpaceType *DependentASType =
6881 cast<DependentAddressSpaceType>(T);
6882 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
6883 OnlyDeduced, Depth, Used);
6885 DependentASType->getAddrSpaceExpr(),
6886 OnlyDeduced, Depth, Used);
6887 break;
6888 }
6889
6890 case Type::ConstantMatrix: {
6891 const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T);
6892 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6893 Depth, Used);
6894 break;
6895 }
6896
6897 case Type::DependentSizedMatrix: {
6898 const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(T);
6899 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6900 Depth, Used);
6901 MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
6902 Used);
6903 MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
6904 Depth, Used);
6905 break;
6906 }
6907
6908 case Type::FunctionProto: {
6909 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
6910 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
6911 Used);
6912 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
6913 // C++17 [temp.deduct.type]p5:
6914 // The non-deduced contexts are: [...]
6915 // -- A function parameter pack that does not occur at the end of the
6916 // parameter-declaration-list.
6917 if (!OnlyDeduced || I + 1 == N ||
6918 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
6919 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
6920 Depth, Used);
6921 } else {
6922 // FIXME: C++17 [temp.deduct.call]p1:
6923 // When a function parameter pack appears in a non-deduced context,
6924 // the type of that pack is never deduced.
6925 //
6926 // We should also track a set of "never deduced" parameters, and
6927 // subtract that from the list of deduced parameters after marking.
6928 }
6929 }
6930 if (auto *E = Proto->getNoexceptExpr())
6931 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
6932 break;
6933 }
6934
6935 case Type::TemplateTypeParm: {
6936 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
6937 if (TTP->getDepth() == Depth)
6938 Used[TTP->getIndex()] = true;
6939 break;
6940 }
6941
6942 case Type::SubstTemplateTypeParmPack: {
6944 = cast<SubstTemplateTypeParmPackType>(T);
6945 if (Subst->getReplacedParameter()->getDepth() == Depth)
6946 Used[Subst->getIndex()] = true;
6948 OnlyDeduced, Depth, Used);
6949 break;
6950 }
6951
6952 case Type::InjectedClassName:
6953 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
6954 [[fallthrough]];
6955
6956 case Type::TemplateSpecialization: {
6957 const TemplateSpecializationType *Spec
6958 = cast<TemplateSpecializationType>(T);
6959 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
6960 Depth, Used);
6961
6962 // C++0x [temp.deduct.type]p9:
6963 // If the template argument list of P contains a pack expansion that is
6964 // not the last template argument, the entire template argument list is a
6965 // non-deduced context.
6966 if (OnlyDeduced &&
6968 break;
6969
6970 for (const auto &Arg : Spec->template_arguments())
6971 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6972 break;
6973 }
6974
6975 case Type::Complex:
6976 if (!OnlyDeduced)
6978 cast<ComplexType>(T)->getElementType(),
6979 OnlyDeduced, Depth, Used);
6980 break;
6981
6982 case Type::Atomic:
6983 if (!OnlyDeduced)
6985 cast<AtomicType>(T)->getValueType(),
6986 OnlyDeduced, Depth, Used);
6987 break;
6988
6989 case Type::DependentName:
6990 if (!OnlyDeduced)
6992 cast<DependentNameType>(T)->getQualifier(),
6993 OnlyDeduced, Depth, Used);
6994 break;
6995
6996 case Type::DependentTemplateSpecialization: {
6997 // C++14 [temp.deduct.type]p5:
6998 // The non-deduced contexts are:
6999 // -- The nested-name-specifier of a type that was specified using a
7000 // qualified-id
7001 //
7002 // C++14 [temp.deduct.type]p6:
7003 // When a type name is specified in a way that includes a non-deduced
7004 // context, all of the types that comprise that type name are also
7005 // non-deduced.
7006 if (OnlyDeduced)
7007 break;
7008
7010 = cast<DependentTemplateSpecializationType>(T);
7011
7013 OnlyDeduced, Depth, Used);
7014
7015 for (const auto &Arg : Spec->template_arguments())
7016 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
7017 break;
7018 }
7019
7020 case Type::TypeOf:
7021 if (!OnlyDeduced)
7022 MarkUsedTemplateParameters(Ctx, cast<TypeOfType>(T)->getUnmodifiedType(),
7023 OnlyDeduced, Depth, Used);
7024 break;
7025
7026 case Type::TypeOfExpr:
7027 if (!OnlyDeduced)
7029 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
7030 OnlyDeduced, Depth, Used);
7031 break;
7032
7033 case Type::Decltype:
7034 if (!OnlyDeduced)
7036 cast<DecltypeType>(T)->getUnderlyingExpr(),
7037 OnlyDeduced, Depth, Used);
7038 break;
7039
7040 case Type::PackIndexing:
7041 if (!OnlyDeduced) {
7042 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getPattern(),
7043 OnlyDeduced, Depth, Used);
7044 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getIndexExpr(),
7045 OnlyDeduced, Depth, Used);
7046 }
7047 break;
7048
7049 case Type::UnaryTransform:
7050 if (!OnlyDeduced)
7052 cast<UnaryTransformType>(T)->getUnderlyingType(),
7053 OnlyDeduced, Depth, Used);
7054 break;
7055
7056 case Type::PackExpansion:
7058 cast<PackExpansionType>(T)->getPattern(),
7059 OnlyDeduced, Depth, Used);
7060 break;
7061
7062 case Type::Auto:
7063 case Type::DeducedTemplateSpecialization:
7065 cast<DeducedType>(T)->getDeducedType(),
7066 OnlyDeduced, Depth, Used);
7067 break;
7068 case Type::DependentBitInt:
7070 cast<DependentBitIntType>(T)->getNumBitsExpr(),
7071 OnlyDeduced, Depth, Used);
7072 break;
7073
7074 case Type::HLSLAttributedResource:
7076 Ctx, cast<HLSLAttributedResourceType>(T)->getWrappedType(), OnlyDeduced,
7077 Depth, Used);
7078 if (cast<HLSLAttributedResourceType>(T)->hasContainedType())
7080 Ctx, cast<HLSLAttributedResourceType>(T)->getContainedType(),
7081 OnlyDeduced, Depth, Used);
7082 break;
7083
7084 // None of these types have any template parameters in them.
7085 case Type::Builtin:
7086 case Type::VariableArray:
7087 case Type::FunctionNoProto:
7088 case Type::Record:
7089 case Type::Enum:
7090 case Type::ObjCInterface:
7091 case Type::ObjCObject:
7092 case Type::ObjCObjectPointer:
7093 case Type::UnresolvedUsing:
7094 case Type::Pipe:
7095 case Type::BitInt:
7096#define TYPE(Class, Base)
7097#define ABSTRACT_TYPE(Class, Base)
7098#define DEPENDENT_TYPE(Class, Base)
7099#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7100#include "clang/AST/TypeNodes.inc"
7101 break;
7102 }
7103}
7104
7105/// Mark the template parameters that are used by this
7106/// template argument.
7107static void
7110 bool OnlyDeduced,
7111 unsigned Depth,
7112 llvm::SmallBitVector &Used) {
7113 switch (TemplateArg.getKind()) {
7119 break;
7120
7122 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
7123 Depth, Used);
7124 break;
7125
7129 TemplateArg.getAsTemplateOrTemplatePattern(),
7130 OnlyDeduced, Depth, Used);
7131 break;
7132
7134 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
7135 Depth, Used);
7136 break;
7137
7139 for (const auto &P : TemplateArg.pack_elements())
7140 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
7141 break;
7142 }
7143}
7144
7145void
7146Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
7147 unsigned Depth,
7148 llvm::SmallBitVector &Used) {
7149 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
7150}
7151
7152void
7154 bool OnlyDeduced, unsigned Depth,
7155 llvm::SmallBitVector &Used) {
7156 // C++0x [temp.deduct.type]p9:
7157 // If the template argument list of P contains a pack expansion that is not
7158 // the last template argument, the entire template argument list is a
7159 // non-deduced context.
7160 if (OnlyDeduced &&
7161 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
7162 return;
7163
7164 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7165 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
7166 Depth, Used);
7167}
7168
7170 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
7171 llvm::SmallBitVector &Deduced) {
7172 TemplateParameterList *TemplateParams
7173 = FunctionTemplate->getTemplateParameters();
7174 Deduced.clear();
7175 Deduced.resize(TemplateParams->size());
7176
7177 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
7178 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
7179 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
7180 true, TemplateParams->getDepth(), Deduced);
7181}
7182
7184 FunctionTemplateDecl *FunctionTemplate,
7185 QualType T) {
7186 if (!T->isDependentType())
7187 return false;
7188
7189 TemplateParameterList *TemplateParams
7190 = FunctionTemplate->getTemplateParameters();
7191 llvm::SmallBitVector Deduced(TemplateParams->size());
7192 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
7193 Deduced);
7194
7195 return Deduced.any();
7196}
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 TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
static bool isSameTemplateArg(ASTContext &Context, TemplateArgument X, const TemplateArgument &Y, bool PartialOrdering, bool PackExpansionMatchesPack=false)
Determine whether two template arguments are the same.
static TemplateDeductionResult DeduceTemplateSpecArguments(Sema &S, TemplateParameterList *TemplateParams, const QualType P, QualType A, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
static TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch(Sema &S, TemplateParameterList *TemplateParams, QualType Param, QualType Arg, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned TDF, PartialOrderingKind POK, bool DeducedFromArrayBound, bool *HasDeducedAnyParam)
Deduce the template arguments by comparing the parameter type and the argument type (C++ [temp....
static PartialOrderingKind degradeCallPartialOrderingKind(PartialOrderingKind POK)
When propagating a partial ordering kind into a NonCall context, this is used to downgrade a 'Call' i...
static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y)
Compare two APSInts, extending and switching the sign as necessary to compare their values regardless...
static TemplateLikeDecl * getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1, PrimaryDel *P2, TemplateDeductionInfo &Info)
Returns the more specialized template specialization between T1/P1 and T2/P2.
static DeducedTemplateArgument checkDeducedTemplateArguments(ASTContext &Context, const DeducedTemplateArgument &X, const DeducedTemplateArgument &Y, bool AggregateCandidateDeduction=false)
Verify that the given, deduced template arguments are compatible.
static bool isSameDeclaration(Decl *X, Decl *Y)
Determine whether two declaration pointers refer to the same declaration.
static TemplateDeductionResult DeduceForEachType(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< QualType > Params, ArrayRef< QualType > Args, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, PartialOrderingKind POK, bool FinishingDeduction, T &&DeductFunc)
static TemplateDeductionResult DeduceTemplateBases(Sema &S, const CXXRecordDecl *RD, TemplateParameterList *TemplateParams, QualType P, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
Attempt to deduce the template arguments by checking the base types according to (C++20 [temp....
static bool hasTemplateArgumentForDeduction(ArrayRef< TemplateArgument > &Args, unsigned &ArgIdx)
Determine whether there is a template argument to be used for deduction.
static DeclContext * getAsDeclContextOrEnclosing(Decl *D)
static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType, QualType ArgType)
Determine whether the parameter has qualifiers that the argument lacks.
static TemplateDeductionResult DeduceNullPtrTemplateArgument(Sema &S, TemplateParameterList *TemplateParams, const NonTypeTemplateParmDecl *NTTP, QualType NullPtrType, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
Deduce the value of the given non-type template parameter from the given null pointer template argume...
static void MarkUsedTemplateParameters(ASTContext &Ctx, const TemplateArgument &TemplateArg, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark the template parameters that are used by this template argument.
static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R, FunctionDecl *Fn)
Gets the type of a function for template-argument-deducton purposes when it's considered as part of a...
static TemplateDeductionResult CheckDeducedArgumentConstraints(Sema &S, TemplateDeclT *Template, ArrayRef< TemplateArgument > SugaredDeducedArgs, ArrayRef< TemplateArgument > CanonicalDeducedArgs, TemplateDeductionInfo &Info)
static const NonTypeTemplateParmDecl * getDeducedParameterFromExpr(const Expr *E, unsigned Depth)
If the given expression is of a form that permits the deduction of a non-type template parameter,...
static TemplateDeductionResult DeduceNonTypeTemplateArgument(Sema &S, TemplateParameterList *TemplateParams, const NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced, QualType ValueType, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
Deduce the value of the given non-type template parameter as the given deduced template argument.
static bool hasPackExpansionBeforeEnd(ArrayRef< TemplateArgument > Args)
Determine whether the given set of template arguments has a pack expansion that is not the last templ...
static bool isSimpleTemplateIdType(QualType T)
Determine whether the given type T is a simple-template-id type.
PartialOrderingKind
The kind of PartialOrdering we're performing template argument deduction for (C++11 [temp....
static 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 ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template, TemplateDeductionInfo &Info, bool IsDeduced, bool PartialOrdering, SmallVectorImpl< TemplateArgument > &SugaredOutput, SmallVectorImpl< TemplateArgument > &CanonicalOutput)
Convert the given deduced template argument and add it to the set of fully-converted template argumen...
static bool DeducedArgsNeedReplacement(TemplateDeclT *Template)
static TemplateDeductionResult CheckDeductionConsistency(Sema &S, FunctionTemplateDecl *FTD, int ArgIdx, QualType P, QualType A, ArrayRef< TemplateArgument > DeducedArgs, bool CheckConsistency)
static TemplateDeductionResult ConvertDeducedTemplateArguments(Sema &S, TemplateDeclT *Template, bool IsDeduced, SmallVectorImpl< DeducedTemplateArgument > &Deduced, TemplateDeductionInfo &Info, SmallVectorImpl< TemplateArgument > &SugaredBuilder, SmallVectorImpl< TemplateArgument > &CanonicalBuilder, bool PartialOrdering, LocalInstantiationScope *CurrentInstantiationScope, unsigned NumAlreadyConverted, bool *IsIncomplete)
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:2104
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
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1219
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:247
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1210
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
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:911
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:2672
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4079
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4067
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3756
QualType getReturnType() const
Definition: Decl.h:2720
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:4138
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4203
bool isImmediateEscalating() const
Definition: Decl.cpp:3275
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:4004
void getAssociatedConstraints(SmallVectorImpl< const Expr * > &AC) const
Get the associated-constraints of this function declaration.
Definition: Decl.h:2627
size_t param_size() const
Definition: Decl.h:2665
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3210
Represents a prototype with parameter type info, e.g.
Definition: Type.h: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:13221
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8049
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3011
A helper class for building up ExtParameterInfos.
Definition: Sema.h:12624
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:12643
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12094
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12124
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:465
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:12653
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.
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, CheckTemplateArgumentKind CTAK, bool PartialOrdering, bool *MatchedPackOnParmToNonPackOnArg)
Check that the given template argument corresponds to the given template parameter.
SemaCUDA & CUDA()
Definition: Sema.h:1072
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...
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr, bool PartialOrderingTTP=false, bool *MatchedPackOnParmToNonPackOnArg=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
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:6460
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:11650
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:11642
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition: Sema.h:11646
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition: Sema.h:910
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:533
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:818
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:11828
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:526
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:14404
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:1045
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:12157
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:20982
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:14967
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.
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:12497
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:3409
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void reserve(size_t Requested)
Ensures that this buffer has at least as much capacity as described.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:159
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:164
void copy(TypeLoc other)
Copies the other type loc into this one.
Definition: TypeLoc.cpp:168
A container of type source information.
Definition: Type.h: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:882
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1522
Declaration of a variable template.
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the variable template specialization.
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
Represents a GCC generic vector type.
Definition: Type.h: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.
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:366
@ 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
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition: Sema.h:12691
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:12698
A stack object to be created when performing template instantiation.
Definition: Sema.h:12858
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:13018
brief A function argument from which we performed template argument
Definition: Sema.h:12257
Location information for a TemplateArgument.
Definition: TemplateBase.h:472