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