clang 20.0.0git
SemaTemplateDeduction.cpp
Go to the documentation of this file.
1//===- SemaTemplateDeduction.cpp - Template Argument Deduction ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TreeTransform.h"
14#include "TypeLocBuilder.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
29#include "clang/AST/Type.h"
30#include "clang/AST/TypeLoc.h"
34#include "clang/Basic/LLVM.h"
41#include "clang/Sema/Sema.h"
42#include "clang/Sema/Template.h"
44#include "llvm/ADT/APInt.h"
45#include "llvm/ADT/APSInt.h"
46#include "llvm/ADT/ArrayRef.h"
47#include "llvm/ADT/DenseMap.h"
48#include "llvm/ADT/FoldingSet.h"
49#include "llvm/ADT/SmallBitVector.h"
50#include "llvm/ADT/SmallPtrSet.h"
51#include "llvm/ADT/SmallVector.h"
52#include "llvm/Support/Casting.h"
53#include "llvm/Support/Compiler.h"
54#include "llvm/Support/ErrorHandling.h"
55#include <algorithm>
56#include <cassert>
57#include <optional>
58#include <tuple>
59#include <type_traits>
60#include <utility>
61
62namespace clang {
63
64 /// Various flags that control template argument deduction.
65 ///
66 /// These flags can be bitwise-OR'd together.
68 /// No template argument deduction flags, which indicates the
69 /// strictest results for template argument deduction (as used for, e.g.,
70 /// matching class template partial specializations).
72
73 /// Within template argument deduction from a function call, we are
74 /// matching with a parameter type for which the original parameter was
75 /// a reference.
77
78 /// Within template argument deduction from a function call, we
79 /// are matching in a case where we ignore cv-qualifiers.
81
82 /// Within template argument deduction from a function call,
83 /// we are matching in a case where we can perform template argument
84 /// deduction from a template-id of a derived class of the argument type.
86
87 /// Allow non-dependent types to differ, e.g., when performing
88 /// template argument deduction from a function call where conversions
89 /// may apply.
91
92 /// Whether we are performing template argument deduction for
93 /// parameters and arguments in a top-level template argument
95
96 /// Within template argument deduction from overload resolution per
97 /// C++ [over.over] allow matching function types that are compatible in
98 /// terms of noreturn and default calling convention adjustments, or
99 /// similarly matching a declared template specialization against a
100 /// possible template, per C++ [temp.deduct.decl]. In either case, permit
101 /// deduction where the parameter is a function type that can be converted
102 /// to the argument type.
104
105 /// Within template argument deduction for a conversion function, we are
106 /// matching with an argument type for which the original argument was
107 /// a reference.
109 };
110}
111
112using namespace clang;
113using namespace sema;
114
115/// Compare two APSInts, extending and switching the sign as
116/// necessary to compare their values regardless of underlying type.
117static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
118 if (Y.getBitWidth() > X.getBitWidth())
119 X = X.extend(Y.getBitWidth());
120 else if (Y.getBitWidth() < X.getBitWidth())
121 Y = Y.extend(X.getBitWidth());
122
123 // If there is a signedness mismatch, correct it.
124 if (X.isSigned() != Y.isSigned()) {
125 // If the signed value is negative, then the values cannot be the same.
126 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
127 return false;
128
129 Y.setIsSigned(true);
130 X.setIsSigned(true);
131 }
132
133 return X == Y;
134}
135
137 Sema &S, TemplateParameterList *TemplateParams, QualType Param,
139 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
140 bool PartialOrdering = false, bool DeducedFromArrayBound = false);
141
149 bool NumberOfArgumentsMustMatch,
151
154 bool OnlyDeduced, unsigned Depth,
155 llvm::SmallBitVector &Used);
156
158 bool OnlyDeduced, unsigned Level,
159 llvm::SmallBitVector &Deduced);
160
161/// If the given expression is of a form that permits the deduction
162/// of a non-type template parameter, return the declaration of that
163/// non-type template parameter.
164static const NonTypeTemplateParmDecl *
165getDeducedParameterFromExpr(const Expr *E, unsigned Depth) {
166 // If we are within an alias template, the expression may have undergone
167 // any number of parameter substitutions already.
168 while (true) {
169 if (const auto *IC = dyn_cast<ImplicitCastExpr>(E))
170 E = IC->getSubExpr();
171 else if (const auto *CE = dyn_cast<ConstantExpr>(E))
172 E = CE->getSubExpr();
173 else if (const auto *Subst = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
174 E = Subst->getReplacement();
175 else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) {
176 // Look through implicit copy construction from an lvalue of the same type.
177 if (CCE->getParenOrBraceRange().isValid())
178 break;
179 // Note, there could be default arguments.
180 assert(CCE->getNumArgs() >= 1 && "implicit construct expr should have 1 arg");
181 E = CCE->getArg(0);
182 } else
183 break;
184 }
185
186 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
187 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
188 if (NTTP->getDepth() == Depth)
189 return NTTP;
190
191 return nullptr;
192}
193
194static const NonTypeTemplateParmDecl *
197}
198
199/// Determine whether two declaration pointers refer to the same
200/// declaration.
201static bool isSameDeclaration(Decl *X, Decl *Y) {
202 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
203 X = NX->getUnderlyingDecl();
204 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
205 Y = NY->getUnderlyingDecl();
206
207 return X->getCanonicalDecl() == Y->getCanonicalDecl();
208}
209
210/// Verify that the given, deduced template arguments are compatible.
211///
212/// \returns The deduced template argument, or a NULL template argument if
213/// the deduced template arguments were incompatible.
218 bool AggregateCandidateDeduction = false) {
219 // We have no deduction for one or both of the arguments; they're compatible.
220 if (X.isNull())
221 return Y;
222 if (Y.isNull())
223 return X;
224
225 // If we have two non-type template argument values deduced for the same
226 // parameter, they must both match the type of the parameter, and thus must
227 // match each other's type. As we're only keeping one of them, we must check
228 // for that now. The exception is that if either was deduced from an array
229 // bound, the type is permitted to differ.
230 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
231 QualType XType = X.getNonTypeTemplateArgumentType();
232 if (!XType.isNull()) {
234 if (YType.isNull() || !Context.hasSameType(XType, YType))
236 }
237 }
238
239 switch (X.getKind()) {
241 llvm_unreachable("Non-deduced template arguments handled above");
242
244 // If two template type arguments have the same type, they're compatible.
245 QualType TX = X.getAsType(), TY = Y.getAsType();
246 if (Y.getKind() == TemplateArgument::Type && Context.hasSameType(TX, TY))
247 return DeducedTemplateArgument(Context.getCommonSugaredType(TX, TY),
248 X.wasDeducedFromArrayBound() ||
250
251 // If one of the two arguments was deduced from an array bound, the other
252 // supersedes it.
253 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
254 return X.wasDeducedFromArrayBound() ? Y : X;
255
256 // The arguments are not compatible.
258 }
259
261 // If we deduced a constant in one case and either a dependent expression or
262 // declaration in another case, keep the integral constant.
263 // If both are integral constants with the same value, keep that value.
267 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
268 return X.wasDeducedFromArrayBound() ? Y : X;
269
270 // All other combinations are incompatible.
272
274 // If we deduced a value and a dependent expression, keep the value.
277 X.structurallyEquals(Y)))
278 return X;
279
280 // All other combinations are incompatible.
282
285 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
286 return X;
287
288 // All other combinations are incompatible.
290
293 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
295 return X;
296
297 // All other combinations are incompatible.
299
302 return checkDeducedTemplateArguments(Context, Y, X);
303
304 // Compare the expressions for equality
305 llvm::FoldingSetNodeID ID1, ID2;
306 X.getAsExpr()->Profile(ID1, Context, true);
307 Y.getAsExpr()->Profile(ID2, Context, true);
308 if (ID1 == ID2)
309 return X.wasDeducedFromArrayBound() ? Y : X;
310
311 // Differing dependent expressions are incompatible.
313 }
314
316 assert(!X.wasDeducedFromArrayBound());
317
318 // If we deduced a declaration and a dependent expression, keep the
319 // declaration.
321 return X;
322
323 // If we deduced a declaration and an integral constant, keep the
324 // integral constant and whichever type did not come from an array
325 // bound.
328 return TemplateArgument(Context, Y.getAsIntegral(),
329 X.getParamTypeForDecl());
330 return Y;
331 }
332
333 // If we deduced two declarations, make sure that they refer to the
334 // same declaration.
336 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
337 return X;
338
339 // All other combinations are incompatible.
341
343 // If we deduced a null pointer and a dependent expression, keep the
344 // null pointer.
347 X.getNullPtrType(), Y.getAsExpr()->getType()),
348 true);
349
350 // If we deduced a null pointer and an integral constant, keep the
351 // integral constant.
353 return Y;
354
355 // If we deduced two null pointers, they are the same.
357 return TemplateArgument(
358 Context.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
359 true);
360
361 // All other combinations are incompatible.
363
365 if (Y.getKind() != TemplateArgument::Pack ||
366 (!AggregateCandidateDeduction && X.pack_size() != Y.pack_size()))
368
371 XA = X.pack_begin(),
372 XAEnd = X.pack_end(), YA = Y.pack_begin(), YAEnd = Y.pack_end();
373 XA != XAEnd; ++XA, ++YA) {
374 if (YA != YAEnd) {
376 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
378 if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
380 NewPack.push_back(Merged);
381 } else {
382 NewPack.push_back(*XA);
383 }
384 }
385
387 TemplateArgument::CreatePackCopy(Context, NewPack),
388 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
389 }
390 }
391
392 llvm_unreachable("Invalid TemplateArgument Kind!");
393}
394
395/// Deduce the value of the given non-type template parameter
396/// as the given deduced template argument. All non-type template parameter
397/// deduction is funneled through here.
399 Sema &S, TemplateParameterList *TemplateParams,
400 const NonTypeTemplateParmDecl *NTTP,
401 const DeducedTemplateArgument &NewDeduced, QualType ValueType,
404 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
405 "deducing non-type template argument with wrong depth");
406
408 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
409 if (Result.isNull()) {
410 Info.Param = const_cast<NonTypeTemplateParmDecl*>(NTTP);
411 Info.FirstArg = Deduced[NTTP->getIndex()];
412 Info.SecondArg = NewDeduced;
413 return TemplateDeductionResult::Inconsistent;
414 }
415
416 Deduced[NTTP->getIndex()] = Result;
417 if (!S.getLangOpts().CPlusPlus17)
418 return TemplateDeductionResult::Success;
419
420 if (NTTP->isExpandedParameterPack())
421 // FIXME: We may still need to deduce parts of the type here! But we
422 // don't have any way to find which slice of the type to use, and the
423 // type stored on the NTTP itself is nonsense. Perhaps the type of an
424 // expanded NTTP should be a pack expansion type?
425 return TemplateDeductionResult::Success;
426
427 // Get the type of the parameter for deduction. If it's a (dependent) array
428 // or function type, we will not have decayed it yet, so do that now.
429 QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
430 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
431 ParamType = Expansion->getPattern();
432
433 // FIXME: It's not clear how deduction of a parameter of reference
434 // type from an argument (of non-reference type) should be performed.
435 // For now, we just remove reference types from both sides and let
436 // the final check for matching types sort out the mess.
437 ValueType = ValueType.getNonReferenceType();
438 if (ParamType->isReferenceType())
439 ParamType = ParamType.getNonReferenceType();
440 else
441 // Top-level cv-qualifiers are irrelevant for a non-reference type.
442 ValueType = ValueType.getUnqualifiedType();
443
445 S, TemplateParams, ParamType, ValueType, Info, Deduced,
446 TDF_SkipNonDependent, /*PartialOrdering=*/false,
447 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
448}
449
450/// Deduce the value of the given non-type template parameter
451/// from the given integral constant.
453 Sema &S, TemplateParameterList *TemplateParams,
454 const NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
455 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
458 S, TemplateParams, NTTP,
460 DeducedFromArrayBound),
461 ValueType, Info, Deduced);
462}
463
464/// Deduce the value of the given non-type template parameter
465/// from the given null pointer template argument type.
467 Sema &S, TemplateParameterList *TemplateParams,
468 const NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
473 NTTP->getLocation()),
474 NullPtrType,
475 NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer
476 : CK_NullToPointer)
477 .get();
478 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
480 Value->getType(), Info, Deduced);
481}
482
483/// Deduce the value of the given non-type template parameter
484/// from the given type- or value-dependent expression.
485///
486/// \returns true if deduction succeeded, false otherwise.
488 Sema &S, TemplateParameterList *TemplateParams,
489 const NonTypeTemplateParmDecl *NTTP, Expr *Value,
492 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
494 Value->getType(), Info, Deduced);
495}
496
497/// Deduce the value of the given non-type template parameter
498/// from the given declaration.
499///
500/// \returns true if deduction succeeded, false otherwise.
502 Sema &S, TemplateParameterList *TemplateParams,
506 TemplateArgument New(D, T);
508 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
509}
510
511/// Create a shallow copy of a given template parameter declaration, with
512/// empty source locations and using the given TemplateArgument as it's
513/// default argument.
514///
515/// \returns The new template parameter declaration.
518 switch (A->getKind()) {
519 case Decl::TemplateTypeParm: {
520 auto *T = cast<TemplateTypeParmDecl>(A);
523 T->getDepth(), T->getIndex(), T->getIdentifier(),
524 T->wasDeclaredWithTypename(), T->isParameterPack(),
525 T->hasTypeConstraint());
526 R->setDefaultArgument(
527 S.Context,
529 if (R->hasTypeConstraint()) {
530 auto *C = R->getTypeConstraint();
531 R->setTypeConstraint(C->getConceptReference(),
532 C->getImmediatelyDeclaredConstraint());
533 }
534 return R;
535 }
536 case Decl::NonTypeTemplateParm: {
537 auto *T = cast<NonTypeTemplateParmDecl>(A);
540 T->getDepth(), T->getIndex(), T->getIdentifier(), T->getType(),
541 T->isParameterPack(), T->getTypeSourceInfo());
542 R->setDefaultArgument(S.Context,
544 Default, Default.getNonTypeTemplateArgumentType(),
545 SourceLocation()));
546 if (auto *PTC = T->getPlaceholderTypeConstraint())
547 R->setPlaceholderTypeConstraint(PTC);
548 return R;
549 }
550 case Decl::TemplateTemplateParm: {
551 auto *T = cast<TemplateTemplateParmDecl>(A);
553 S.Context, A->getDeclContext(), SourceLocation(), T->getDepth(),
554 T->getIndex(), T->isParameterPack(), T->getIdentifier(),
555 T->wasDeclaredWithTypename(), T->getTemplateParameters());
556 R->setDefaultArgument(
557 S.Context,
559 return R;
560 }
561 default:
562 llvm_unreachable("Unexpected Decl Kind");
563 }
564}
565
568 TemplateName Param, TemplateName Arg,
570 ArrayRef<TemplateArgument> DefaultArguments,
572 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
573 if (!ParamDecl) {
574 // The parameter type is dependent and is not a template template parameter,
575 // so there is nothing that we can deduce.
576 return TemplateDeductionResult::Success;
577 }
578
579 if (auto *TempParam = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
580 // If we're not deducing at this depth, there's nothing to deduce.
581 if (TempParam->getDepth() != Info.getDeducedDepth())
582 return TemplateDeductionResult::Success;
583
584 auto NewDeduced = DeducedTemplateArgument(Arg);
585 // Provisional resolution for CWG2398: If Arg is also a template template
586 // param, and it names a template specialization, then we deduce a
587 // synthesized template template parameter based on A, but using the TS's
588 // arguments as defaults.
589 if (auto *TempArg = dyn_cast_or_null<TemplateTemplateParmDecl>(
590 Arg.getAsTemplateDecl())) {
591 assert(!TempArg->isExpandedParameterPack());
592
593 TemplateParameterList *As = TempArg->getTemplateParameters();
594 if (DefaultArguments.size() != 0) {
595 assert(DefaultArguments.size() <= As->size());
596 SmallVector<NamedDecl *, 4> Params(As->size());
597 for (unsigned I = 0; I < DefaultArguments.size(); ++I)
598 Params[I] = getTemplateParameterWithDefault(S, As->getParam(I),
599 DefaultArguments[I]);
600 for (unsigned I = DefaultArguments.size(); I < As->size(); ++I)
601 Params[I] = As->getParam(I);
602 // FIXME: We could unique these, and also the parameters, but we don't
603 // expect programs to contain a large enough amount of these deductions
604 // for that to be worthwhile.
605 auto *TPL = TemplateParameterList::Create(
606 S.Context, SourceLocation(), SourceLocation(), Params,
608 NewDeduced = DeducedTemplateArgument(
610 S.Context, TempArg->getDeclContext(), SourceLocation(),
611 TempArg->getDepth(), TempArg->getPosition(),
612 TempArg->isParameterPack(), TempArg->getIdentifier(),
613 TempArg->wasDeclaredWithTypename(), TPL)));
614 }
615 }
616
618 Deduced[TempParam->getIndex()],
619 NewDeduced);
620 if (Result.isNull()) {
621 Info.Param = TempParam;
622 Info.FirstArg = Deduced[TempParam->getIndex()];
623 Info.SecondArg = NewDeduced;
624 return TemplateDeductionResult::Inconsistent;
625 }
626
627 Deduced[TempParam->getIndex()] = Result;
628 return TemplateDeductionResult::Success;
629 }
630
631 // Verify that the two template names are equivalent.
632 if (S.Context.hasSameTemplateName(Param, Arg))
633 return TemplateDeductionResult::Success;
634
635 // Mismatch of non-dependent template parameter to argument.
636 Info.FirstArg = TemplateArgument(Param);
637 Info.SecondArg = TemplateArgument(Arg);
638 return TemplateDeductionResult::NonDeducedMismatch;
639}
640
641/// Deduce the template arguments by comparing the template parameter
642/// type (which is a template-id) with the template argument type.
643///
644/// \param S the Sema
645///
646/// \param TemplateParams the template parameters that we are deducing
647///
648/// \param P the parameter type
649///
650/// \param A the argument type
651///
652/// \param Info information about the template argument deduction itself
653///
654/// \param Deduced the deduced template arguments
655///
656/// \returns the result of template argument deduction so far. Note that a
657/// "success" result means that template argument deduction has not yet failed,
658/// but it may still fail, later, for other reasons.
659
661 for (const Type *T = QT.getTypePtr(); /**/; /**/) {
662 const TemplateSpecializationType *TST =
664 assert(TST && "Expected a TemplateSpecializationType");
665 if (!TST->isSugared())
666 return TST;
667 T = TST->desugar().getTypePtr();
668 }
669}
670
673 const QualType P, QualType A,
676 QualType UP = P;
677 if (const auto *IP = P->getAs<InjectedClassNameType>())
678 UP = IP->getInjectedSpecializationType();
679
680 assert(isa<TemplateSpecializationType>(UP.getCanonicalType()));
682 TemplateName TNP = TP->getTemplateName();
683
684 // If the parameter is an alias template, there is nothing to deduce.
685 if (const auto *TD = TNP.getAsTemplateDecl(); TD && TD->isTypeAlias())
686 return TemplateDeductionResult::Success;
687
688 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
689 // arguments.
693 ->template_arguments();
694
695 QualType UA = A;
696 std::optional<NestedNameSpecifier *> NNS;
697 // Treat an injected-class-name as its underlying template-id.
698 if (const auto *Elaborated = A->getAs<ElaboratedType>()) {
699 NNS = Elaborated->getQualifier();
700 } else if (const auto *Injected = A->getAs<InjectedClassNameType>()) {
701 UA = Injected->getInjectedSpecializationType();
702 NNS = nullptr;
703 }
704
705 // Check whether the template argument is a dependent template-id.
706 if (isa<TemplateSpecializationType>(UA.getCanonicalType())) {
708 TemplateName TNA = SA->getTemplateName();
709
710 // If the argument is an alias template, there is nothing to deduce.
711 if (const auto *TD = TNA.getAsTemplateDecl(); TD && TD->isTypeAlias())
712 return TemplateDeductionResult::Success;
713
714 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
715 // arguments.
719 ->template_arguments();
720
721 // Perform template argument deduction for the template name.
722 if (auto Result = DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
723 AResolved, Deduced);
724 Result != TemplateDeductionResult::Success)
725 return Result;
726
727 // Perform template argument deduction on each template
728 // argument. Ignore any missing/extra arguments, since they could be
729 // filled in by default arguments.
730 return DeduceTemplateArguments(S, TemplateParams, PResolved, AResolved,
731 Info, Deduced,
732 /*NumberOfArgumentsMustMatch=*/false);
733 }
734
735 // If the argument type is a class template specialization, we
736 // perform template argument deduction using its template
737 // arguments.
738 const auto *RA = UA->getAs<RecordType>();
739 const auto *SA =
740 RA ? dyn_cast<ClassTemplateSpecializationDecl>(RA->getDecl()) : nullptr;
741 if (!SA) {
743 Info.SecondArg = TemplateArgument(A);
744 return TemplateDeductionResult::NonDeducedMismatch;
745 }
746
747 TemplateName TNA = TemplateName(SA->getSpecializedTemplate());
748 if (NNS)
750 *NNS, false, TemplateName(SA->getSpecializedTemplate()));
751
752 // Perform template argument deduction for the template name.
753 if (auto Result =
754 DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
755 SA->getTemplateArgs().asArray(), Deduced);
756 Result != TemplateDeductionResult::Success)
757 return Result;
758
759 // Perform template argument deduction for the template arguments.
760 return DeduceTemplateArguments(S, TemplateParams, PResolved,
761 SA->getTemplateArgs().asArray(), Info, Deduced,
762 /*NumberOfArgumentsMustMatch=*/true);
763}
764
766 assert(T->isCanonicalUnqualified());
767
768 switch (T->getTypeClass()) {
769 case Type::TypeOfExpr:
770 case Type::TypeOf:
771 case Type::DependentName:
772 case Type::Decltype:
773 case Type::PackIndexing:
774 case Type::UnresolvedUsing:
775 case Type::TemplateTypeParm:
776 case Type::Auto:
777 return true;
778
779 case Type::ConstantArray:
780 case Type::IncompleteArray:
781 case Type::VariableArray:
782 case Type::DependentSizedArray:
784 cast<ArrayType>(T)->getElementType().getTypePtr());
785
786 default:
787 return false;
788 }
789}
790
791/// Determines whether the given type is an opaque type that
792/// might be more qualified when instantiated.
796}
797
798/// Helper function to build a TemplateParameter when we don't
799/// know its type statically.
801 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
802 return TemplateParameter(TTP);
803 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
804 return TemplateParameter(NTTP);
805
806 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
807}
808
809/// A pack that we're currently deducing.
811 // The index of the pack.
812 unsigned Index;
813
814 // The old value of the pack before we started deducing it.
816
817 // A deferred value of this pack from an inner deduction, that couldn't be
818 // deduced because this deduction hadn't happened yet.
820
821 // The new value of the pack.
823
824 // The outer deduction for this pack, if any.
825 DeducedPack *Outer = nullptr;
826
827 DeducedPack(unsigned Index) : Index(Index) {}
828};
829
830namespace {
831
832/// A scope in which we're performing pack deduction.
833class PackDeductionScope {
834public:
835 /// Prepare to deduce the packs named within Pattern.
836 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
839 bool DeducePackIfNotAlreadyDeduced = false)
840 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info),
841 DeducePackIfNotAlreadyDeduced(DeducePackIfNotAlreadyDeduced){
842 unsigned NumNamedPacks = addPacks(Pattern);
843 finishConstruction(NumNamedPacks);
844 }
845
846 /// Prepare to directly deduce arguments of the parameter with index \p Index.
847 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
849 TemplateDeductionInfo &Info, unsigned Index)
850 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
851 addPack(Index);
852 finishConstruction(1);
853 }
854
855private:
856 void addPack(unsigned Index) {
857 // Save the deduced template argument for the parameter pack expanded
858 // by this pack expansion, then clear out the deduction.
859 DeducedFromEarlierParameter = !Deduced[Index].isNull();
860 DeducedPack Pack(Index);
861 Pack.Saved = Deduced[Index];
862 Deduced[Index] = TemplateArgument();
863
864 // FIXME: What if we encounter multiple packs with different numbers of
865 // pre-expanded expansions? (This should already have been diagnosed
866 // during substitution.)
867 if (std::optional<unsigned> ExpandedPackExpansions =
868 getExpandedPackSize(TemplateParams->getParam(Index)))
869 FixedNumExpansions = ExpandedPackExpansions;
870
871 Packs.push_back(Pack);
872 }
873
874 unsigned addPacks(TemplateArgument Pattern) {
875 // Compute the set of template parameter indices that correspond to
876 // parameter packs expanded by the pack expansion.
877 llvm::SmallBitVector SawIndices(TemplateParams->size());
879
880 auto AddPack = [&](unsigned Index) {
881 if (SawIndices[Index])
882 return;
883 SawIndices[Index] = true;
884 addPack(Index);
885
886 // Deducing a parameter pack that is a pack expansion also constrains the
887 // packs appearing in that parameter to have the same deduced arity. Also,
888 // in C++17 onwards, deducing a non-type template parameter deduces its
889 // type, so we need to collect the pending deduced values for those packs.
890 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
891 TemplateParams->getParam(Index))) {
892 if (!NTTP->isExpandedParameterPack())
893 if (auto *Expansion = dyn_cast<PackExpansionType>(NTTP->getType()))
894 ExtraDeductions.push_back(Expansion->getPattern());
895 }
896 // FIXME: Also collect the unexpanded packs in any type and template
897 // parameter packs that are pack expansions.
898 };
899
900 auto Collect = [&](TemplateArgument Pattern) {
902 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
903 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
904 unsigned Depth, Index;
905 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
906 if (Depth == Info.getDeducedDepth())
907 AddPack(Index);
908 }
909 };
910
911 // Look for unexpanded packs in the pattern.
912 Collect(Pattern);
913 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
914
915 unsigned NumNamedPacks = Packs.size();
916
917 // Also look for unexpanded packs that are indirectly deduced by deducing
918 // the sizes of the packs in this pattern.
919 while (!ExtraDeductions.empty())
920 Collect(ExtraDeductions.pop_back_val());
921
922 return NumNamedPacks;
923 }
924
925 void finishConstruction(unsigned NumNamedPacks) {
926 // Dig out the partially-substituted pack, if there is one.
927 const TemplateArgument *PartialPackArgs = nullptr;
928 unsigned NumPartialPackArgs = 0;
929 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
930 if (auto *Scope = S.CurrentInstantiationScope)
931 if (auto *Partial = Scope->getPartiallySubstitutedPack(
932 &PartialPackArgs, &NumPartialPackArgs))
933 PartialPackDepthIndex = getDepthAndIndex(Partial);
934
935 // This pack expansion will have been partially or fully expanded if
936 // it only names explicitly-specified parameter packs (including the
937 // partially-substituted one, if any).
938 bool IsExpanded = true;
939 for (unsigned I = 0; I != NumNamedPacks; ++I) {
940 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
941 IsExpanded = false;
942 IsPartiallyExpanded = false;
943 break;
944 }
945 if (PartialPackDepthIndex ==
946 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
947 IsPartiallyExpanded = true;
948 }
949 }
950
951 // Skip over the pack elements that were expanded into separate arguments.
952 // If we partially expanded, this is the number of partial arguments.
953 // FIXME: `&& FixedNumExpansions` is a workaround for UB described in
954 // https://github.com/llvm/llvm-project/issues/100095
955 if (IsPartiallyExpanded)
956 PackElements += NumPartialPackArgs;
957 else if (IsExpanded && FixedNumExpansions)
958 PackElements += *FixedNumExpansions;
959
960 for (auto &Pack : Packs) {
961 if (Info.PendingDeducedPacks.size() > Pack.Index)
962 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
963 else
964 Info.PendingDeducedPacks.resize(Pack.Index + 1);
965 Info.PendingDeducedPacks[Pack.Index] = &Pack;
966
967 if (PartialPackDepthIndex ==
968 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
969 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
970 // We pre-populate the deduced value of the partially-substituted
971 // pack with the specified value. This is not entirely correct: the
972 // value is supposed to have been substituted, not deduced, but the
973 // cases where this is observable require an exact type match anyway.
974 //
975 // FIXME: If we could represent a "depth i, index j, pack elem k"
976 // parameter, we could substitute the partially-substituted pack
977 // everywhere and avoid this.
978 if (!IsPartiallyExpanded)
979 Deduced[Pack.Index] = Pack.New[PackElements];
980 }
981 }
982 }
983
984public:
985 ~PackDeductionScope() {
986 for (auto &Pack : Packs)
987 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
988 }
989
990 // Return the size of the saved packs if all of them has the same size.
991 std::optional<unsigned> getSavedPackSizeIfAllEqual() const {
992 unsigned PackSize = Packs[0].Saved.pack_size();
993
994 if (std::all_of(Packs.begin() + 1, Packs.end(), [&PackSize](const auto &P) {
995 return P.Saved.pack_size() == PackSize;
996 }))
997 return PackSize;
998 return {};
999 }
1000
1001 /// Determine whether this pack has already been deduced from a previous
1002 /// argument.
1003 bool isDeducedFromEarlierParameter() const {
1004 return DeducedFromEarlierParameter;
1005 }
1006
1007 /// Determine whether this pack has already been partially expanded into a
1008 /// sequence of (prior) function parameters / template arguments.
1009 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
1010
1011 /// Determine whether this pack expansion scope has a known, fixed arity.
1012 /// This happens if it involves a pack from an outer template that has
1013 /// (notionally) already been expanded.
1014 bool hasFixedArity() { return FixedNumExpansions.has_value(); }
1015
1016 /// Determine whether the next element of the argument is still part of this
1017 /// pack. This is the case unless the pack is already expanded to a fixed
1018 /// length.
1019 bool hasNextElement() {
1020 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
1021 }
1022
1023 /// Move to deducing the next element in each pack that is being deduced.
1024 void nextPackElement() {
1025 // Capture the deduced template arguments for each parameter pack expanded
1026 // by this pack expansion, add them to the list of arguments we've deduced
1027 // for that pack, then clear out the deduced argument.
1028 for (auto &Pack : Packs) {
1029 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
1030 if (!Pack.New.empty() || !DeducedArg.isNull()) {
1031 while (Pack.New.size() < PackElements)
1032 Pack.New.push_back(DeducedTemplateArgument());
1033 if (Pack.New.size() == PackElements)
1034 Pack.New.push_back(DeducedArg);
1035 else
1036 Pack.New[PackElements] = DeducedArg;
1037 DeducedArg = Pack.New.size() > PackElements + 1
1038 ? Pack.New[PackElements + 1]
1040 }
1041 }
1042 ++PackElements;
1043 }
1044
1045 /// Finish template argument deduction for a set of argument packs,
1046 /// producing the argument packs and checking for consistency with prior
1047 /// deductions.
1048 TemplateDeductionResult finish() {
1049 // Build argument packs for each of the parameter packs expanded by this
1050 // pack expansion.
1051 for (auto &Pack : Packs) {
1052 // Put back the old value for this pack.
1053 Deduced[Pack.Index] = Pack.Saved;
1054
1055 // Always make sure the size of this pack is correct, even if we didn't
1056 // deduce any values for it.
1057 //
1058 // FIXME: This isn't required by the normative wording, but substitution
1059 // and post-substitution checking will always fail if the arity of any
1060 // pack is not equal to the number of elements we processed. (Either that
1061 // or something else has gone *very* wrong.) We're permitted to skip any
1062 // hard errors from those follow-on steps by the intent (but not the
1063 // wording) of C++ [temp.inst]p8:
1064 //
1065 // If the function selected by overload resolution can be determined
1066 // without instantiating a class template definition, it is unspecified
1067 // whether that instantiation actually takes place
1068 Pack.New.resize(PackElements);
1069
1070 // Build or find a new value for this pack.
1072 if (Pack.New.empty()) {
1073 // If we deduced an empty argument pack, create it now.
1075 } else {
1076 TemplateArgument *ArgumentPack =
1077 new (S.Context) TemplateArgument[Pack.New.size()];
1078 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
1079 NewPack = DeducedTemplateArgument(
1080 TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())),
1081 // FIXME: This is wrong, it's possible that some pack elements are
1082 // deduced from an array bound and others are not:
1083 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
1084 // g({1, 2, 3}, {{}, {}});
1085 // ... should deduce T = {int, size_t (from array bound)}.
1086 Pack.New[0].wasDeducedFromArrayBound());
1087 }
1088
1089 // Pick where we're going to put the merged pack.
1091 if (Pack.Outer) {
1092 if (Pack.Outer->DeferredDeduction.isNull()) {
1093 // Defer checking this pack until we have a complete pack to compare
1094 // it against.
1095 Pack.Outer->DeferredDeduction = NewPack;
1096 continue;
1097 }
1098 Loc = &Pack.Outer->DeferredDeduction;
1099 } else {
1100 Loc = &Deduced[Pack.Index];
1101 }
1102
1103 // Check the new pack matches any previous value.
1104 DeducedTemplateArgument OldPack = *Loc;
1106 S.Context, OldPack, NewPack, DeducePackIfNotAlreadyDeduced);
1107
1108 Info.AggregateDeductionCandidateHasMismatchedArity =
1109 OldPack.getKind() == TemplateArgument::Pack &&
1110 NewPack.getKind() == TemplateArgument::Pack &&
1111 OldPack.pack_size() != NewPack.pack_size() && !Result.isNull();
1112
1113 // If we deferred a deduction of this pack, check that one now too.
1114 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
1115 OldPack = Result;
1116 NewPack = Pack.DeferredDeduction;
1117 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
1118 }
1119
1120 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
1121 if (Result.isNull()) {
1122 Info.Param = makeTemplateParameter(Param);
1123 Info.FirstArg = OldPack;
1124 Info.SecondArg = NewPack;
1125 return TemplateDeductionResult::Inconsistent;
1126 }
1127
1128 // If we have a pre-expanded pack and we didn't deduce enough elements
1129 // for it, fail deduction.
1130 if (std::optional<unsigned> Expansions = getExpandedPackSize(Param)) {
1131 if (*Expansions != PackElements) {
1132 Info.Param = makeTemplateParameter(Param);
1133 Info.FirstArg = Result;
1134 return TemplateDeductionResult::IncompletePack;
1135 }
1136 }
1137
1138 *Loc = Result;
1139 }
1140
1141 return TemplateDeductionResult::Success;
1142 }
1143
1144private:
1145 Sema &S;
1146 TemplateParameterList *TemplateParams;
1149 unsigned PackElements = 0;
1150 bool IsPartiallyExpanded = false;
1151 bool DeducePackIfNotAlreadyDeduced = false;
1152 bool DeducedFromEarlierParameter = false;
1153 /// The number of expansions, if we have a fully-expanded pack in this scope.
1154 std::optional<unsigned> FixedNumExpansions;
1155
1157};
1158
1159} // namespace
1160
1161/// Deduce the template arguments by comparing the list of parameter
1162/// types to the list of argument types, as in the parameter-type-lists of
1163/// function types (C++ [temp.deduct.type]p10).
1164///
1165/// \param S The semantic analysis object within which we are deducing
1166///
1167/// \param TemplateParams The template parameters that we are deducing
1168///
1169/// \param Params The list of parameter types
1170///
1171/// \param NumParams The number of types in \c Params
1172///
1173/// \param Args The list of argument types
1174///
1175/// \param NumArgs The number of types in \c Args
1176///
1177/// \param Info information about the template argument deduction itself
1178///
1179/// \param Deduced the deduced template arguments
1180///
1181/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1182/// how template argument deduction is performed.
1183///
1184/// \param PartialOrdering If true, we are performing template argument
1185/// deduction for during partial ordering for a call
1186/// (C++0x [temp.deduct.partial]).
1187///
1188/// \returns the result of template argument deduction so far. Note that a
1189/// "success" result means that template argument deduction has not yet failed,
1190/// but it may still fail, later, for other reasons.
1193 const QualType *Params, unsigned NumParams,
1194 const QualType *Args, unsigned NumArgs,
1197 unsigned TDF, bool PartialOrdering = false) {
1198 // C++0x [temp.deduct.type]p10:
1199 // Similarly, if P has a form that contains (T), then each parameter type
1200 // Pi of the respective parameter-type- list of P is compared with the
1201 // corresponding parameter type Ai of the corresponding parameter-type-list
1202 // of A. [...]
1203 unsigned ArgIdx = 0, ParamIdx = 0;
1204 for (; ParamIdx != NumParams; ++ParamIdx) {
1205 // Check argument types.
1206 const PackExpansionType *Expansion
1207 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1208 if (!Expansion) {
1209 // Simple case: compare the parameter and argument types at this point.
1210
1211 // Make sure we have an argument.
1212 if (ArgIdx >= NumArgs)
1213 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1214
1215 if (isa<PackExpansionType>(Args[ArgIdx])) {
1216 // C++0x [temp.deduct.type]p22:
1217 // If the original function parameter associated with A is a function
1218 // parameter pack and the function parameter associated with P is not
1219 // a function parameter pack, then template argument deduction fails.
1220 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1221 }
1222
1224 S, TemplateParams, Params[ParamIdx].getUnqualifiedType(),
1225 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, TDF,
1227 /*DeducedFromArrayBound=*/false);
1228 Result != TemplateDeductionResult::Success)
1229 return Result;
1230
1231 ++ArgIdx;
1232 continue;
1233 }
1234
1235 // C++0x [temp.deduct.type]p10:
1236 // If the parameter-declaration corresponding to Pi is a function
1237 // parameter pack, then the type of its declarator- id is compared with
1238 // each remaining parameter type in the parameter-type-list of A. Each
1239 // comparison deduces template arguments for subsequent positions in the
1240 // template parameter packs expanded by the function parameter pack.
1241
1242 QualType Pattern = Expansion->getPattern();
1243 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
1244
1245 // A pack scope with fixed arity is not really a pack any more, so is not
1246 // a non-deduced context.
1247 if (ParamIdx + 1 == NumParams || PackScope.hasFixedArity()) {
1248 for (; ArgIdx < NumArgs && PackScope.hasNextElement(); ++ArgIdx) {
1249 // Deduce template arguments from the pattern.
1251 S, TemplateParams, Pattern.getUnqualifiedType(),
1252 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, TDF,
1253 PartialOrdering, /*DeducedFromArrayBound=*/false);
1254 Result != TemplateDeductionResult::Success)
1255 return Result;
1256
1257 PackScope.nextPackElement();
1258 }
1259 } else {
1260 // C++0x [temp.deduct.type]p5:
1261 // The non-deduced contexts are:
1262 // - A function parameter pack that does not occur at the end of the
1263 // parameter-declaration-clause.
1264 //
1265 // FIXME: There is no wording to say what we should do in this case. We
1266 // choose to resolve this by applying the same rule that is applied for a
1267 // function call: that is, deduce all contained packs to their
1268 // explicitly-specified values (or to <> if there is no such value).
1269 //
1270 // This is seemingly-arbitrarily different from the case of a template-id
1271 // with a non-trailing pack-expansion in its arguments, which renders the
1272 // entire template-argument-list a non-deduced context.
1273
1274 // If the parameter type contains an explicitly-specified pack that we
1275 // could not expand, skip the number of parameters notionally created
1276 // by the expansion.
1277 std::optional<unsigned> NumExpansions = Expansion->getNumExpansions();
1278 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1279 for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs;
1280 ++I, ++ArgIdx)
1281 PackScope.nextPackElement();
1282 }
1283 }
1284
1285 // Build argument packs for each of the parameter packs expanded by this
1286 // pack expansion.
1287 if (auto Result = PackScope.finish();
1288 Result != TemplateDeductionResult::Success)
1289 return Result;
1290 }
1291
1292 // DR692, DR1395
1293 // C++0x [temp.deduct.type]p10:
1294 // If the parameter-declaration corresponding to P_i ...
1295 // During partial ordering, if Ai was originally a function parameter pack:
1296 // - if P does not contain a function parameter type corresponding to Ai then
1297 // Ai is ignored;
1298 if (PartialOrdering && ArgIdx + 1 == NumArgs &&
1299 isa<PackExpansionType>(Args[ArgIdx]))
1300 return TemplateDeductionResult::Success;
1301
1302 // Make sure we don't have any extra arguments.
1303 if (ArgIdx < NumArgs)
1304 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1305
1306 return TemplateDeductionResult::Success;
1307}
1308
1309/// Determine whether the parameter has qualifiers that the argument
1310/// lacks. Put another way, determine whether there is no way to add
1311/// a deduced set of qualifiers to the ParamType that would result in
1312/// its qualifiers matching those of the ArgType.
1314 QualType ArgType) {
1315 Qualifiers ParamQs = ParamType.getQualifiers();
1316 Qualifiers ArgQs = ArgType.getQualifiers();
1317
1318 if (ParamQs == ArgQs)
1319 return false;
1320
1321 // Mismatched (but not missing) Objective-C GC attributes.
1322 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1323 ParamQs.hasObjCGCAttr())
1324 return true;
1325
1326 // Mismatched (but not missing) address spaces.
1327 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1328 ParamQs.hasAddressSpace())
1329 return true;
1330
1331 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1332 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1333 ParamQs.hasObjCLifetime())
1334 return true;
1335
1336 // CVR qualifiers inconsistent or a superset.
1337 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1338}
1339
1341 const FunctionType *PF = P->getAs<FunctionType>(),
1342 *AF = A->getAs<FunctionType>();
1343
1344 // Just compare if not functions.
1345 if (!PF || !AF)
1346 return Context.hasSameType(P, A);
1347
1348 // Noreturn and noexcept adjustment.
1349 if (QualType AdjustedParam; IsFunctionConversion(P, A, AdjustedParam))
1350 P = AdjustedParam;
1351
1352 // FIXME: Compatible calling conventions.
1354}
1355
1356/// Get the index of the first template parameter that was originally from the
1357/// innermost template-parameter-list. This is 0 except when we concatenate
1358/// the template parameter lists of a class template and a constructor template
1359/// when forming an implicit deduction guide.
1361 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1362 if (!Guide || !Guide->isImplicit())
1363 return 0;
1364 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1365}
1366
1367/// Determine whether a type denotes a forwarding reference.
1368static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1369 // C++1z [temp.deduct.call]p3:
1370 // A forwarding reference is an rvalue reference to a cv-unqualified
1371 // template parameter that does not represent a template parameter of a
1372 // class template.
1373 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1374 if (ParamRef->getPointeeType().getQualifiers())
1375 return false;
1376 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1377 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1378 }
1379 return false;
1380}
1381
1382/// Attempt to deduce the template arguments by checking the base types
1383/// according to (C++20 [temp.deduct.call] p4b3.
1384///
1385/// \param S the semantic analysis object within which we are deducing.
1386///
1387/// \param RD the top level record object we are deducing against.
1388///
1389/// \param TemplateParams the template parameters that we are deducing.
1390///
1391/// \param P the template specialization parameter type.
1392///
1393/// \param Info information about the template argument deduction itself.
1394///
1395/// \param Deduced the deduced template arguments.
1396///
1397/// \returns the result of template argument deduction with the bases. "invalid"
1398/// means no matches, "success" found a single item, and the
1399/// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
1402 TemplateParameterList *TemplateParams, QualType P,
1405 // C++14 [temp.deduct.call] p4b3:
1406 // If P is a class and P has the form simple-template-id, then the
1407 // transformed A can be a derived class of the deduced A. Likewise if
1408 // P is a pointer to a class of the form simple-template-id, the
1409 // transformed A can be a pointer to a derived class pointed to by the
1410 // deduced A. However, if there is a class C that is a (direct or
1411 // indirect) base class of D and derived (directly or indirectly) from a
1412 // class B and that would be a valid deduced A, the deduced A cannot be
1413 // B or pointer to B, respectively.
1414 //
1415 // These alternatives are considered only if type deduction would
1416 // otherwise fail. If they yield more than one possible deduced A, the
1417 // type deduction fails.
1418
1419 // Use a breadth-first search through the bases to collect the set of
1420 // successful matches. Visited contains the set of nodes we have already
1421 // visited, while ToVisit is our stack of records that we still need to
1422 // visit. Matches contains a list of matches that have yet to be
1423 // disqualified.
1426 // We iterate over this later, so we have to use MapVector to ensure
1427 // determinism.
1428 llvm::MapVector<const CXXRecordDecl *,
1430 Matches;
1431
1432 auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
1433 for (const auto &Base : RD->bases()) {
1434 QualType T = Base.getType();
1435 assert(T->isRecordType() && "Base class that isn't a record?");
1436 if (Visited.insert(T->getAsCXXRecordDecl()).second)
1437 ToVisit.push_back(T);
1438 }
1439 };
1440
1441 // Set up the loop by adding all the bases.
1442 AddBases(RD);
1443
1444 // Search each path of bases until we either run into a successful match
1445 // (where all bases of it are invalid), or we run out of bases.
1446 while (!ToVisit.empty()) {
1447 QualType NextT = ToVisit.pop_back_val();
1448
1449 SmallVector<DeducedTemplateArgument, 8> DeducedCopy(Deduced.begin(),
1450 Deduced.end());
1453 S, TemplateParams, P, NextT, BaseInfo, DeducedCopy);
1454
1455 // If this was a successful deduction, add it to the list of matches,
1456 // otherwise we need to continue searching its bases.
1457 const CXXRecordDecl *RD = NextT->getAsCXXRecordDecl();
1459 Matches.insert({RD, DeducedCopy});
1460 else
1461 AddBases(RD);
1462 }
1463
1464 // At this point, 'Matches' contains a list of seemingly valid bases, however
1465 // in the event that we have more than 1 match, it is possible that the base
1466 // of one of the matches might be disqualified for being a base of another
1467 // valid match. We can count on cyclical instantiations being invalid to
1468 // simplify the disqualifications. That is, if A & B are both matches, and B
1469 // inherits from A (disqualifying A), we know that A cannot inherit from B.
1470 if (Matches.size() > 1) {
1471 Visited.clear();
1472 for (const auto &Match : Matches)
1473 AddBases(Match.first);
1474
1475 // We can give up once we have a single item (or have run out of things to
1476 // search) since cyclical inheritance isn't valid.
1477 while (Matches.size() > 1 && !ToVisit.empty()) {
1478 const CXXRecordDecl *RD = ToVisit.pop_back_val()->getAsCXXRecordDecl();
1479 Matches.erase(RD);
1480
1481 // Always add all bases, since the inheritance tree can contain
1482 // disqualifications for multiple matches.
1483 AddBases(RD);
1484 }
1485 }
1486
1487 if (Matches.empty())
1489 if (Matches.size() > 1)
1491
1492 std::swap(Matches.front().second, Deduced);
1494}
1495
1496/// Deduce the template arguments by comparing the parameter type and
1497/// the argument type (C++ [temp.deduct.type]).
1498///
1499/// \param S the semantic analysis object within which we are deducing
1500///
1501/// \param TemplateParams the template parameters that we are deducing
1502///
1503/// \param P the parameter type
1504///
1505/// \param A the argument type
1506///
1507/// \param Info information about the template argument deduction itself
1508///
1509/// \param Deduced the deduced template arguments
1510///
1511/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1512/// how template argument deduction is performed.
1513///
1514/// \param PartialOrdering Whether we're performing template argument deduction
1515/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1516///
1517/// \returns the result of template argument deduction so far. Note that a
1518/// "success" result means that template argument deduction has not yet failed,
1519/// but it may still fail, later, for other reasons.
1521 Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
1523 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1524 bool PartialOrdering, bool DeducedFromArrayBound) {
1525
1526 // If the argument type is a pack expansion, look at its pattern.
1527 // This isn't explicitly called out
1528 if (const auto *AExp = dyn_cast<PackExpansionType>(A))
1529 A = AExp->getPattern();
1530 assert(!isa<PackExpansionType>(A.getCanonicalType()));
1531
1532 if (PartialOrdering) {
1533 // C++11 [temp.deduct.partial]p5:
1534 // Before the partial ordering is done, certain transformations are
1535 // performed on the types used for partial ordering:
1536 // - If P is a reference type, P is replaced by the type referred to.
1537 const ReferenceType *PRef = P->getAs<ReferenceType>();
1538 if (PRef)
1539 P = PRef->getPointeeType();
1540
1541 // - If A is a reference type, A is replaced by the type referred to.
1542 const ReferenceType *ARef = A->getAs<ReferenceType>();
1543 if (ARef)
1544 A = A->getPointeeType();
1545
1546 if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
1547 // C++11 [temp.deduct.partial]p9:
1548 // If, for a given type, deduction succeeds in both directions (i.e.,
1549 // the types are identical after the transformations above) and both
1550 // P and A were reference types [...]:
1551 // - if [one type] was an lvalue reference and [the other type] was
1552 // not, [the other type] is not considered to be at least as
1553 // specialized as [the first type]
1554 // - if [one type] is more cv-qualified than [the other type],
1555 // [the other type] is not considered to be at least as specialized
1556 // as [the first type]
1557 // Objective-C ARC adds:
1558 // - [one type] has non-trivial lifetime, [the other type] has
1559 // __unsafe_unretained lifetime, and the types are otherwise
1560 // identical
1561 //
1562 // A is "considered to be at least as specialized" as P iff deduction
1563 // succeeds, so we model this as a deduction failure. Note that
1564 // [the first type] is P and [the other type] is A here; the standard
1565 // gets this backwards.
1566 Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
1567 if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
1568 PQuals.isStrictSupersetOf(AQuals) ||
1569 (PQuals.hasNonTrivialObjCLifetime() &&
1570 AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1571 PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
1572 Info.FirstArg = TemplateArgument(P);
1573 Info.SecondArg = TemplateArgument(A);
1575 }
1576 }
1577 Qualifiers DiscardedQuals;
1578 // C++11 [temp.deduct.partial]p7:
1579 // Remove any top-level cv-qualifiers:
1580 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1581 // version of P.
1582 P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
1583 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1584 // version of A.
1585 A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
1586 } else {
1587 // C++0x [temp.deduct.call]p4 bullet 1:
1588 // - If the original P is a reference type, the deduced A (i.e., the type
1589 // referred to by the reference) can be more cv-qualified than the
1590 // transformed A.
1591 if (TDF & TDF_ParamWithReferenceType) {
1592 Qualifiers Quals;
1593 QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
1595 P = S.Context.getQualifiedType(UnqualP, Quals);
1596 }
1597
1598 if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
1599 // C++0x [temp.deduct.type]p10:
1600 // If P and A are function types that originated from deduction when
1601 // taking the address of a function template (14.8.2.2) or when deducing
1602 // template arguments from a function declaration (14.8.2.6) and Pi and
1603 // Ai are parameters of the top-level parameter-type-list of P and A,
1604 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1605 // is an lvalue reference, in
1606 // which case the type of Pi is changed to be the template parameter
1607 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1608 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1609 // deduced as X&. - end note ]
1610 TDF &= ~TDF_TopLevelParameterTypeList;
1611 if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
1613 P = P->getPointeeType();
1614 }
1615 }
1616
1617 // C++ [temp.deduct.type]p9:
1618 // A template type argument T, a template template argument TT or a
1619 // template non-type argument i can be deduced if P and A have one of
1620 // the following forms:
1621 //
1622 // T
1623 // cv-list T
1624 if (const auto *TTP = P->getAs<TemplateTypeParmType>()) {
1625 // Just skip any attempts to deduce from a placeholder type or a parameter
1626 // at a different depth.
1627 if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
1629
1630 unsigned Index = TTP->getIndex();
1631
1632 // If the argument type is an array type, move the qualifiers up to the
1633 // top level, so they can be matched with the qualifiers on the parameter.
1634 if (A->isArrayType()) {
1635 Qualifiers Quals;
1636 A = S.Context.getUnqualifiedArrayType(A, Quals);
1637 if (Quals)
1638 A = S.Context.getQualifiedType(A, Quals);
1639 }
1640
1641 // The argument type can not be less qualified than the parameter
1642 // type.
1643 if (!(TDF & TDF_IgnoreQualifiers) &&
1645 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1646 Info.FirstArg = TemplateArgument(P);
1647 Info.SecondArg = TemplateArgument(A);
1649 }
1650
1651 // Do not match a function type with a cv-qualified type.
1652 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1653 if (A->isFunctionType() && P.hasQualifiers())
1655
1656 assert(TTP->getDepth() == Info.getDeducedDepth() &&
1657 "saw template type parameter with wrong depth");
1658 assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&
1659 "Unresolved overloaded function");
1661
1662 // Remove any qualifiers on the parameter from the deduced type.
1663 // We checked the qualifiers for consistency above.
1664 Qualifiers DeducedQs = DeducedType.getQualifiers();
1665 Qualifiers ParamQs = P.getQualifiers();
1666 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1667 if (ParamQs.hasObjCGCAttr())
1668 DeducedQs.removeObjCGCAttr();
1669 if (ParamQs.hasAddressSpace())
1670 DeducedQs.removeAddressSpace();
1671 if (ParamQs.hasObjCLifetime())
1672 DeducedQs.removeObjCLifetime();
1673
1674 // Objective-C ARC:
1675 // If template deduction would produce a lifetime qualifier on a type
1676 // that is not a lifetime type, template argument deduction fails.
1677 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1679 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1680 Info.FirstArg = TemplateArgument(P);
1681 Info.SecondArg = TemplateArgument(A);
1683 }
1684
1685 // Objective-C ARC:
1686 // If template deduction would produce an argument type with lifetime type
1687 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1688 if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
1689 !DeducedQs.hasObjCLifetime())
1691
1692 DeducedType =
1693 S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
1694
1695 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1697 checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
1698 if (Result.isNull()) {
1699 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1700 Info.FirstArg = Deduced[Index];
1701 Info.SecondArg = NewDeduced;
1703 }
1704
1705 Deduced[Index] = Result;
1707 }
1708
1709 // Set up the template argument deduction information for a failure.
1710 Info.FirstArg = TemplateArgument(P);
1711 Info.SecondArg = TemplateArgument(A);
1712
1713 // If the parameter is an already-substituted template parameter
1714 // pack, do nothing: we don't know which of its arguments to look
1715 // at, so we have to wait until all of the parameter packs in this
1716 // expansion have arguments.
1717 if (P->getAs<SubstTemplateTypeParmPackType>())
1719
1720 // Check the cv-qualifiers on the parameter and argument types.
1721 if (!(TDF & TDF_IgnoreQualifiers)) {
1722 if (TDF & TDF_ParamWithReferenceType) {
1725 } else if (TDF & TDF_ArgWithReferenceType) {
1726 // C++ [temp.deduct.conv]p4:
1727 // If the original A is a reference type, A can be more cv-qualified
1728 // than the deduced A
1729 if (!A.getQualifiers().compatiblyIncludes(P.getQualifiers()))
1731
1732 // Strip out all extra qualifiers from the argument to figure out the
1733 // type we're converting to, prior to the qualification conversion.
1734 Qualifiers Quals;
1735 A = S.Context.getUnqualifiedArrayType(A, Quals);
1736 A = S.Context.getQualifiedType(A, P.getQualifiers());
1737 } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
1738 if (P.getCVRQualifiers() != A.getCVRQualifiers())
1740 }
1741 }
1742
1743 // If the parameter type is not dependent, there is nothing to deduce.
1744 if (!P->isDependentType()) {
1745 if (TDF & TDF_SkipNonDependent)
1748 : S.Context.hasSameType(P, A))
1753 if (!(TDF & TDF_IgnoreQualifiers))
1755 // Otherwise, when ignoring qualifiers, the types not having the same
1756 // unqualified type does not mean they do not match, so in this case we
1757 // must keep going and analyze with a non-dependent parameter type.
1758 }
1759
1760 switch (P.getCanonicalType()->getTypeClass()) {
1761 // Non-canonical types cannot appear here.
1762#define NON_CANONICAL_TYPE(Class, Base) \
1763 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1764#define TYPE(Class, Base)
1765#include "clang/AST/TypeNodes.inc"
1766
1767 case Type::TemplateTypeParm:
1768 case Type::SubstTemplateTypeParmPack:
1769 llvm_unreachable("Type nodes handled above");
1770
1771 case Type::Auto:
1772 // C++23 [temp.deduct.funcaddr]/3:
1773 // A placeholder type in the return type of a function template is a
1774 // non-deduced context.
1775 // There's no corresponding wording for [temp.deduct.decl], but we treat
1776 // it the same to match other compilers.
1777 if (P->isDependentType())
1779 [[fallthrough]];
1780 case Type::Builtin:
1781 case Type::VariableArray:
1782 case Type::Vector:
1783 case Type::FunctionNoProto:
1784 case Type::Record:
1785 case Type::Enum:
1786 case Type::ObjCObject:
1787 case Type::ObjCInterface:
1788 case Type::ObjCObjectPointer:
1789 case Type::BitInt:
1790 return (TDF & TDF_SkipNonDependent) ||
1791 ((TDF & TDF_IgnoreQualifiers)
1793 : S.Context.hasSameType(P, A))
1796
1797 // _Complex T [placeholder extension]
1798 case Type::Complex: {
1799 const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
1800 if (!CA)
1803 S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
1804 Deduced, TDF);
1805 }
1806
1807 // _Atomic T [extension]
1808 case Type::Atomic: {
1809 const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
1810 if (!AA)
1813 S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
1814 Deduced, TDF);
1815 }
1816
1817 // T *
1818 case Type::Pointer: {
1819 QualType PointeeType;
1820 if (const auto *PA = A->getAs<PointerType>()) {
1821 PointeeType = PA->getPointeeType();
1822 } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
1823 PointeeType = PA->getPointeeType();
1824 } else {
1826 }
1828 S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
1829 PointeeType, Info, Deduced,
1831 }
1832
1833 // T &
1834 case Type::LValueReference: {
1835 const auto *RP = P->castAs<LValueReferenceType>(),
1836 *RA = A->getAs<LValueReferenceType>();
1837 if (!RA)
1839
1841 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1842 Deduced, 0);
1843 }
1844
1845 // T && [C++0x]
1846 case Type::RValueReference: {
1847 const auto *RP = P->castAs<RValueReferenceType>(),
1848 *RA = A->getAs<RValueReferenceType>();
1849 if (!RA)
1851
1853 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1854 Deduced, 0);
1855 }
1856
1857 // T [] (implied, but not stated explicitly)
1858 case Type::IncompleteArray: {
1859 const auto *IAA = S.Context.getAsIncompleteArrayType(A);
1860 if (!IAA)
1862
1863 const auto *IAP = S.Context.getAsIncompleteArrayType(P);
1864 assert(IAP && "Template parameter not of incomplete array type");
1865
1867 S, TemplateParams, IAP->getElementType(), IAA->getElementType(), Info,
1868 Deduced, TDF & TDF_IgnoreQualifiers);
1869 }
1870
1871 // T [integer-constant]
1872 case Type::ConstantArray: {
1873 const auto *CAA = S.Context.getAsConstantArrayType(A),
1875 assert(CAP);
1876 if (!CAA || CAA->getSize() != CAP->getSize())
1878
1880 S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
1881 Deduced, TDF & TDF_IgnoreQualifiers);
1882 }
1883
1884 // type [i]
1885 case Type::DependentSizedArray: {
1886 const auto *AA = S.Context.getAsArrayType(A);
1887 if (!AA)
1889
1890 // Check the element type of the arrays
1891 const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
1892 assert(DAP);
1894 S, TemplateParams, DAP->getElementType(), AA->getElementType(),
1895 Info, Deduced, TDF & TDF_IgnoreQualifiers);
1897 return Result;
1898
1899 // Determine the array bound is something we can deduce.
1900 const NonTypeTemplateParmDecl *NTTP =
1901 getDeducedParameterFromExpr(Info, DAP->getSizeExpr());
1902 if (!NTTP)
1904
1905 // We can perform template argument deduction for the given non-type
1906 // template parameter.
1907 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1908 "saw non-type template parameter with wrong depth");
1909 if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
1910 llvm::APSInt Size(CAA->getSize());
1912 S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
1913 /*ArrayBound=*/true, Info, Deduced);
1914 }
1915 if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
1916 if (DAA->getSizeExpr())
1918 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info, Deduced);
1919
1920 // Incomplete type does not match a dependently-sized array type
1922 }
1923
1924 // type(*)(T)
1925 // T(*)()
1926 // T(*)(T)
1927 case Type::FunctionProto: {
1928 const auto *FPP = P->castAs<FunctionProtoType>(),
1929 *FPA = A->getAs<FunctionProtoType>();
1930 if (!FPA)
1932
1933 if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
1934 FPP->getRefQualifier() != FPA->getRefQualifier() ||
1935 FPP->isVariadic() != FPA->isVariadic())
1937
1938 // Check return types.
1940 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
1941 Info, Deduced, 0,
1942 /*PartialOrdering=*/false,
1943 /*DeducedFromArrayBound=*/false);
1945 return Result;
1946
1947 // Check parameter types.
1949 S, TemplateParams, FPP->param_type_begin(), FPP->getNumParams(),
1950 FPA->param_type_begin(), FPA->getNumParams(), Info, Deduced,
1953 return Result;
1954
1957
1958 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1959 // deducing through the noexcept-specifier if it's part of the canonical
1960 // type. libstdc++ relies on this.
1961 Expr *NoexceptExpr = FPP->getNoexceptExpr();
1962 if (const NonTypeTemplateParmDecl *NTTP =
1963 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
1964 : nullptr) {
1965 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1966 "saw non-type template parameter with wrong depth");
1967
1968 llvm::APSInt Noexcept(1);
1969 switch (FPA->canThrow()) {
1970 case CT_Cannot:
1971 Noexcept = 1;
1972 [[fallthrough]];
1973
1974 case CT_Can:
1975 // We give E in noexcept(E) the "deduced from array bound" treatment.
1976 // FIXME: Should we?
1978 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
1979 /*DeducedFromArrayBound=*/true, Info, Deduced);
1980
1981 case CT_Dependent:
1982 if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
1984 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
1985 // Can't deduce anything from throw(T...).
1986 break;
1987 }
1988 }
1989 // FIXME: Detect non-deduced exception specification mismatches?
1990 //
1991 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
1992 // top-level differences in noexcept-specifications.
1993
1995 }
1996
1997 case Type::InjectedClassName:
1998 // Treat a template's injected-class-name as if the template
1999 // specialization type had been used.
2000
2001 // template-name<T> (where template-name refers to a class template)
2002 // template-name<i>
2003 // TT<T>
2004 // TT<i>
2005 // TT<>
2006 case Type::TemplateSpecialization: {
2007 // When Arg cannot be a derived class, we can just try to deduce template
2008 // arguments from the template-id.
2009 if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
2010 return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
2011 Deduced);
2012
2013 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
2014 Deduced.end());
2015
2016 auto Result =
2017 DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info, Deduced);
2019 return Result;
2020
2021 // We cannot inspect base classes as part of deduction when the type
2022 // is incomplete, so either instantiate any templates necessary to
2023 // complete the type, or skip over it if it cannot be completed.
2024 if (!S.isCompleteType(Info.getLocation(), A))
2025 return Result;
2026
2027 const CXXRecordDecl *RD = A->getAsCXXRecordDecl();
2028 if (RD->isInvalidDecl())
2029 return Result;
2030
2031 // Reset the incorrectly deduced argument from above.
2032 Deduced = DeducedOrig;
2033
2034 // Check bases according to C++14 [temp.deduct.call] p4b3:
2035 auto BaseResult =
2036 DeduceTemplateBases(S, RD, TemplateParams, P, Info, Deduced);
2038 : Result;
2039 }
2040
2041 // T type::*
2042 // T T::*
2043 // T (type::*)()
2044 // type (T::*)()
2045 // type (type::*)(T)
2046 // type (T::*)(T)
2047 // T (type::*)(T)
2048 // T (T::*)()
2049 // T (T::*)(T)
2050 case Type::MemberPointer: {
2051 const auto *MPP = P->castAs<MemberPointerType>(),
2052 *MPA = A->getAs<MemberPointerType>();
2053 if (!MPA)
2055
2056 QualType PPT = MPP->getPointeeType();
2057 if (PPT->isFunctionType())
2058 S.adjustMemberFunctionCC(PPT, /*HasThisPointer=*/false,
2059 /*IsCtorOrDtor=*/false, Info.getLocation());
2060 QualType APT = MPA->getPointeeType();
2061 if (APT->isFunctionType())
2062 S.adjustMemberFunctionCC(APT, /*HasThisPointer=*/false,
2063 /*IsCtorOrDtor=*/false, Info.getLocation());
2064
2065 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
2067 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF);
2069 return Result;
2071 S, TemplateParams, QualType(MPP->getClass(), 0),
2072 QualType(MPA->getClass(), 0), Info, Deduced, SubTDF);
2073 }
2074
2075 // (clang extension)
2076 //
2077 // type(^)(T)
2078 // T(^)()
2079 // T(^)(T)
2080 case Type::BlockPointer: {
2081 const auto *BPP = P->castAs<BlockPointerType>(),
2082 *BPA = A->getAs<BlockPointerType>();
2083 if (!BPA)
2086 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
2087 Deduced, 0);
2088 }
2089
2090 // (clang extension)
2091 //
2092 // T __attribute__(((ext_vector_type(<integral constant>))))
2093 case Type::ExtVector: {
2094 const auto *VP = P->castAs<ExtVectorType>();
2095 QualType ElementType;
2096 if (const auto *VA = A->getAs<ExtVectorType>()) {
2097 // Make sure that the vectors have the same number of elements.
2098 if (VP->getNumElements() != VA->getNumElements())
2100 ElementType = VA->getElementType();
2101 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2102 // We can't check the number of elements, since the argument has a
2103 // dependent number of elements. This can only occur during partial
2104 // ordering.
2105 ElementType = VA->getElementType();
2106 } else {
2108 }
2109 // Perform deduction on the element types.
2111 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
2112 TDF);
2113 }
2114
2115 case Type::DependentVector: {
2116 const auto *VP = P->castAs<DependentVectorType>();
2117
2118 if (const auto *VA = A->getAs<VectorType>()) {
2119 // Perform deduction on the element types.
2121 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2122 Info, Deduced, TDF);
2124 return Result;
2125
2126 // Perform deduction on the vector size, if we can.
2127 const NonTypeTemplateParmDecl *NTTP =
2128 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2129 if (!NTTP)
2131
2132 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2133 ArgSize = VA->getNumElements();
2134 // Note that we use the "array bound" rules here; just like in that
2135 // case, we don't have any particular type for the vector size, but
2136 // we can provide one if necessary.
2137 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2138 S.Context.UnsignedIntTy, true,
2139 Info, Deduced);
2140 }
2141
2142 if (const auto *VA = A->getAs<DependentVectorType>()) {
2143 // Perform deduction on the element types.
2145 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2146 Info, Deduced, TDF);
2148 return Result;
2149
2150 // Perform deduction on the vector size, if we can.
2151 const NonTypeTemplateParmDecl *NTTP =
2152 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2153 if (!NTTP)
2155
2156 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2157 VA->getSizeExpr(), Info, Deduced);
2158 }
2159
2161 }
2162
2163 // (clang extension)
2164 //
2165 // T __attribute__(((ext_vector_type(N))))
2166 case Type::DependentSizedExtVector: {
2167 const auto *VP = P->castAs<DependentSizedExtVectorType>();
2168
2169 if (const auto *VA = A->getAs<ExtVectorType>()) {
2170 // Perform deduction on the element types.
2172 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2173 Info, Deduced, TDF);
2175 return Result;
2176
2177 // Perform deduction on the vector size, if we can.
2178 const NonTypeTemplateParmDecl *NTTP =
2179 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2180 if (!NTTP)
2182
2183 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2184 ArgSize = VA->getNumElements();
2185 // Note that we use the "array bound" rules here; just like in that
2186 // case, we don't have any particular type for the vector size, but
2187 // we can provide one if necessary.
2188 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2189 S.Context.IntTy, true, Info,
2190 Deduced);
2191 }
2192
2193 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2194 // Perform deduction on the element types.
2196 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2197 Info, Deduced, TDF);
2199 return Result;
2200
2201 // Perform deduction on the vector size, if we can.
2202 const NonTypeTemplateParmDecl *NTTP =
2203 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2204 if (!NTTP)
2206
2207 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2208 VA->getSizeExpr(), Info, Deduced);
2209 }
2210
2212 }
2213
2214 // (clang extension)
2215 //
2216 // T __attribute__((matrix_type(<integral constant>,
2217 // <integral constant>)))
2218 case Type::ConstantMatrix: {
2219 const auto *MP = P->castAs<ConstantMatrixType>(),
2220 *MA = A->getAs<ConstantMatrixType>();
2221 if (!MA)
2223
2224 // Check that the dimensions are the same
2225 if (MP->getNumRows() != MA->getNumRows() ||
2226 MP->getNumColumns() != MA->getNumColumns()) {
2228 }
2229 // Perform deduction on element types.
2231 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2232 Deduced, TDF);
2233 }
2234
2235 case Type::DependentSizedMatrix: {
2236 const auto *MP = P->castAs<DependentSizedMatrixType>();
2237 const auto *MA = A->getAs<MatrixType>();
2238 if (!MA)
2240
2241 // Check the element type of the matrixes.
2243 S, TemplateParams, MP->getElementType(), MA->getElementType(),
2244 Info, Deduced, TDF);
2246 return Result;
2247
2248 // Try to deduce a matrix dimension.
2249 auto DeduceMatrixArg =
2250 [&S, &Info, &Deduced, &TemplateParams](
2251 Expr *ParamExpr, const MatrixType *A,
2252 unsigned (ConstantMatrixType::*GetArgDimension)() const,
2253 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2254 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2255 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
2256 if (!ParamExpr->isValueDependent()) {
2257 std::optional<llvm::APSInt> ParamConst =
2258 ParamExpr->getIntegerConstantExpr(S.Context);
2259 if (!ParamConst)
2261
2262 if (ACM) {
2263 if ((ACM->*GetArgDimension)() == *ParamConst)
2266 }
2267
2268 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2269 if (std::optional<llvm::APSInt> ArgConst =
2270 ArgExpr->getIntegerConstantExpr(S.Context))
2271 if (*ArgConst == *ParamConst)
2274 }
2275
2276 const NonTypeTemplateParmDecl *NTTP =
2277 getDeducedParameterFromExpr(Info, ParamExpr);
2278 if (!NTTP)
2280
2281 if (ACM) {
2282 llvm::APSInt ArgConst(
2284 ArgConst = (ACM->*GetArgDimension)();
2286 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
2287 /*ArrayBound=*/true, Info, Deduced);
2288 }
2289
2290 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2291 (ADM->*GetArgDimensionExpr)(),
2292 Info, Deduced);
2293 };
2294
2295 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
2299 return Result;
2300
2301 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2304 }
2305
2306 // (clang extension)
2307 //
2308 // T __attribute__(((address_space(N))))
2309 case Type::DependentAddressSpace: {
2310 const auto *ASP = P->castAs<DependentAddressSpaceType>();
2311
2312 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
2313 // Perform deduction on the pointer type.
2315 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2316 Info, Deduced, TDF);
2318 return Result;
2319
2320 // Perform deduction on the address space, if we can.
2321 const NonTypeTemplateParmDecl *NTTP =
2322 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2323 if (!NTTP)
2325
2327 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info, Deduced);
2328 }
2329
2331 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2332 false);
2333 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
2334
2335 // Perform deduction on the pointer types.
2337 S, TemplateParams, ASP->getPointeeType(),
2338 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF);
2340 return Result;
2341
2342 // Perform deduction on the address space, if we can.
2343 const NonTypeTemplateParmDecl *NTTP =
2344 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2345 if (!NTTP)
2347
2348 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2349 ArgAddressSpace, S.Context.IntTy,
2350 true, Info, Deduced);
2351 }
2352
2354 }
2355 case Type::DependentBitInt: {
2356 const auto *IP = P->castAs<DependentBitIntType>();
2357
2358 if (const auto *IA = A->getAs<BitIntType>()) {
2359 if (IP->isUnsigned() != IA->isUnsigned())
2361
2362 const NonTypeTemplateParmDecl *NTTP =
2363 getDeducedParameterFromExpr(Info, IP->getNumBitsExpr());
2364 if (!NTTP)
2366
2367 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2368 ArgSize = IA->getNumBits();
2369
2370 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2371 S.Context.IntTy, true, Info,
2372 Deduced);
2373 }
2374
2375 if (const auto *IA = A->getAs<DependentBitIntType>()) {
2376 if (IP->isUnsigned() != IA->isUnsigned())
2379 }
2380
2382 }
2383
2384 case Type::TypeOfExpr:
2385 case Type::TypeOf:
2386 case Type::DependentName:
2387 case Type::UnresolvedUsing:
2388 case Type::Decltype:
2389 case Type::UnaryTransform:
2390 case Type::DeducedTemplateSpecialization:
2391 case Type::DependentTemplateSpecialization:
2392 case Type::PackExpansion:
2393 case Type::Pipe:
2394 case Type::ArrayParameter:
2395 // No template argument deduction for these types
2397
2398 case Type::PackIndexing: {
2399 const PackIndexingType *PIT = P->getAs<PackIndexingType>();
2400 if (PIT->hasSelectedType()) {
2402 S, TemplateParams, PIT->getSelectedType(), A, Info, Deduced, TDF);
2403 }
2405 }
2406 }
2407
2408 llvm_unreachable("Invalid Type Class!");
2409}
2410
2416 // If the template argument is a pack expansion, perform template argument
2417 // deduction against the pattern of that expansion. This only occurs during
2418 // partial ordering.
2419 if (A.isPackExpansion())
2421
2422 switch (P.getKind()) {
2424 llvm_unreachable("Null template argument in parameter list");
2425
2429 S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0);
2430 Info.FirstArg = P;
2431 Info.SecondArg = A;
2433
2436 return DeduceTemplateArguments(S, TemplateParams, P.getAsTemplate(),
2437 A.getAsTemplate(), Info,
2438 /*DefaultArguments=*/{}, Deduced);
2439 Info.FirstArg = P;
2440 Info.SecondArg = A;
2442
2444 llvm_unreachable("caller should handle pack expansions");
2445
2448 isSameDeclaration(P.getAsDecl(), A.getAsDecl()))
2450
2451 Info.FirstArg = P;
2452 Info.SecondArg = A;
2454
2457 S.Context.hasSameType(P.getNullPtrType(), A.getNullPtrType()))
2459
2460 Info.FirstArg = P;
2461 Info.SecondArg = A;
2463
2466 if (hasSameExtendedValue(P.getAsIntegral(), A.getAsIntegral()))
2468 }
2469 Info.FirstArg = P;
2470 Info.SecondArg = A;
2472
2477
2478 Info.FirstArg = P;
2479 Info.SecondArg = A;
2481
2483 if (const NonTypeTemplateParmDecl *NTTP =
2484 getDeducedParameterFromExpr(Info, P.getAsExpr())) {
2485 switch (A.getKind()) {
2490 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2491 A.getNonTypeTemplateArgumentType(), Info, Deduced);
2492
2494 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
2495 A.getNullPtrType(), Info, Deduced);
2496
2499 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
2500 Info, Deduced);
2501
2507 Info.FirstArg = P;
2508 Info.SecondArg = A;
2510 }
2511 llvm_unreachable("Unknown template argument kind");
2512 }
2513
2514 // Can't deduce anything, but that's okay.
2517 llvm_unreachable("Argument packs should be expanded by the caller!");
2518 }
2519
2520 llvm_unreachable("Invalid TemplateArgument Kind!");
2521}
2522
2523/// Determine whether there is a template argument to be used for
2524/// deduction.
2525///
2526/// This routine "expands" argument packs in-place, overriding its input
2527/// parameters so that \c Args[ArgIdx] will be the available template argument.
2528///
2529/// \returns true if there is another template argument (which will be at
2530/// \c Args[ArgIdx]), false otherwise.
2532 unsigned &ArgIdx) {
2533 if (ArgIdx == Args.size())
2534 return false;
2535
2536 const TemplateArgument &Arg = Args[ArgIdx];
2537 if (Arg.getKind() != TemplateArgument::Pack)
2538 return true;
2539
2540 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2541 Args = Arg.pack_elements();
2542 ArgIdx = 0;
2543 return ArgIdx < Args.size();
2544}
2545
2546/// Determine whether the given set of template arguments has a pack
2547/// expansion that is not the last template argument.
2549 bool FoundPackExpansion = false;
2550 for (const auto &A : Args) {
2551 if (FoundPackExpansion)
2552 return true;
2553
2554 if (A.getKind() == TemplateArgument::Pack)
2555 return hasPackExpansionBeforeEnd(A.pack_elements());
2556
2557 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2558 // templates, it should not be treated as a pack expansion.
2559 if (A.isPackExpansion())
2560 FoundPackExpansion = true;
2561 }
2562
2563 return false;
2564}
2565
2572 bool NumberOfArgumentsMustMatch, PackFold PackFold) {
2573 if (PackFold == PackFold::ArgumentToParameter)
2574 std::swap(Ps, As);
2575 // C++0x [temp.deduct.type]p9:
2576 // If the template argument list of P contains a pack expansion that is not
2577 // the last template argument, the entire template argument list is a
2578 // non-deduced context.
2581
2582 // C++0x [temp.deduct.type]p9:
2583 // If P has a form that contains <T> or <i>, then each argument Pi of the
2584 // respective template argument list P is compared with the corresponding
2585 // argument Ai of the corresponding template argument list of A.
2586 unsigned ArgIdx = 0, ParamIdx = 0;
2588 const TemplateArgument &P = Ps[ParamIdx];
2589 if (!P.isPackExpansion()) {
2590 // The simple case: deduce template arguments by matching Pi and Ai.
2591
2592 // Check whether we have enough arguments.
2593 if (!hasTemplateArgumentForDeduction(As, ArgIdx))
2594 return NumberOfArgumentsMustMatch
2597
2598 // C++1z [temp.deduct.type]p9:
2599 // During partial ordering, if Ai was originally a pack expansion [and]
2600 // Pi is not a pack expansion, template argument deduction fails.
2601 if (As[ArgIdx].isPackExpansion())
2603
2604 // Perform deduction for this Pi/Ai pair.
2605 TemplateArgument Pi = P, Ai = As[ArgIdx];
2606 if (PackFold == PackFold::ArgumentToParameter)
2607 std::swap(Pi, Ai);
2608 if (auto Result =
2609 DeduceTemplateArguments(S, TemplateParams, Pi, Ai, Info, Deduced);
2611 return Result;
2612
2613 // Move to the next argument.
2614 ++ArgIdx;
2615 continue;
2616 }
2617
2618 // The parameter is a pack expansion.
2619
2620 // C++0x [temp.deduct.type]p9:
2621 // If Pi is a pack expansion, then the pattern of Pi is compared with
2622 // each remaining argument in the template argument list of A. Each
2623 // comparison deduces template arguments for subsequent positions in the
2624 // template parameter packs expanded by Pi.
2625 TemplateArgument Pattern = P.getPackExpansionPattern();
2626
2627 // Prepare to deduce the packs within the pattern.
2628 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2629
2630 // Keep track of the deduced template arguments for each parameter pack
2631 // expanded by this pack expansion (the outer index) and for each
2632 // template argument (the inner SmallVectors).
2633 for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
2634 PackScope.hasNextElement();
2635 ++ArgIdx) {
2636 TemplateArgument Pi = Pattern, Ai = As[ArgIdx];
2637 if (PackFold == PackFold::ArgumentToParameter)
2638 std::swap(Pi, Ai);
2639 // Deduce template arguments from the pattern.
2640 if (auto Result =
2641 DeduceTemplateArguments(S, TemplateParams, Pi, Ai, Info, Deduced);
2643 return Result;
2644
2645 PackScope.nextPackElement();
2646 }
2647
2648 // Build argument packs for each of the parameter packs expanded by this
2649 // pack expansion.
2650 if (auto Result = PackScope.finish();
2652 return Result;
2653 }
2654
2656}
2657
2662 bool NumberOfArgumentsMustMatch) {
2663 return ::DeduceTemplateArguments(*this, TemplateParams, Ps, As, Info, Deduced,
2664 NumberOfArgumentsMustMatch);
2665}
2666
2667/// Determine whether two template arguments are the same.
2668static bool isSameTemplateArg(ASTContext &Context,
2670 const TemplateArgument &Y,
2671 bool PartialOrdering,
2672 bool PackExpansionMatchesPack = false) {
2673 // If we're checking deduced arguments (X) against original arguments (Y),
2674 // we will have flattened packs to non-expansions in X.
2675 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2676 X = X.getPackExpansionPattern();
2677
2678 if (X.getKind() != Y.getKind())
2679 return false;
2680
2681 switch (X.getKind()) {
2683 llvm_unreachable("Comparing NULL template argument");
2684
2686 return Context.getCanonicalType(X.getAsType()) ==
2687 Context.getCanonicalType(Y.getAsType());
2688
2690 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
2691
2693 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2694
2697 return Context.getCanonicalTemplateName(
2698 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2701
2703 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2704
2706 return X.structurallyEquals(Y);
2707
2709 llvm::FoldingSetNodeID XID, YID;
2710 X.getAsExpr()->Profile(XID, Context, true);
2711 Y.getAsExpr()->Profile(YID, Context, true);
2712 return XID == YID;
2713 }
2714
2716 unsigned PackIterationSize = X.pack_size();
2717 if (X.pack_size() != Y.pack_size()) {
2718 if (!PartialOrdering)
2719 return false;
2720
2721 // C++0x [temp.deduct.type]p9:
2722 // During partial ordering, if Ai was originally a pack expansion:
2723 // - if P does not contain a template argument corresponding to Ai
2724 // then Ai is ignored;
2725 bool XHasMoreArg = X.pack_size() > Y.pack_size();
2726 if (!(XHasMoreArg && X.pack_elements().back().isPackExpansion()) &&
2727 !(!XHasMoreArg && Y.pack_elements().back().isPackExpansion()))
2728 return false;
2729
2730 if (XHasMoreArg)
2731 PackIterationSize = Y.pack_size();
2732 }
2733
2734 ArrayRef<TemplateArgument> XP = X.pack_elements();
2736 for (unsigned i = 0; i < PackIterationSize; ++i)
2737 if (!isSameTemplateArg(Context, XP[i], YP[i], PartialOrdering,
2738 PackExpansionMatchesPack))
2739 return false;
2740 return true;
2741 }
2742 }
2743
2744 llvm_unreachable("Invalid TemplateArgument Kind!");
2745}
2746
2749 QualType NTTPType, SourceLocation Loc,
2751 switch (Arg.getKind()) {
2753 llvm_unreachable("Can't get a NULL template argument here");
2754
2756 return TemplateArgumentLoc(
2758
2760 if (NTTPType.isNull())
2761 NTTPType = Arg.getParamTypeForDecl();
2764 .getAs<Expr>();
2766 }
2767
2769 if (NTTPType.isNull())
2770 NTTPType = Arg.getNullPtrType();
2772 .getAs<Expr>();
2773 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2774 E);
2775 }
2776
2781 }
2782
2788 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2789 else if (QualifiedTemplateName *QTN =
2790 Template.getAsQualifiedTemplateName())
2791 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2792
2794 return TemplateArgumentLoc(Context, Arg,
2795 Builder.getWithLocInContext(Context), Loc);
2796
2797 return TemplateArgumentLoc(
2798 Context, Arg, Builder.getWithLocInContext(Context), Loc, Loc);
2799 }
2800
2802 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2803
2806 }
2807
2808 llvm_unreachable("Invalid TemplateArgument Kind!");
2809}
2810
2813 SourceLocation Location) {
2815 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2816}
2817
2818/// Convert the given deduced template argument and add it to the set of
2819/// fully-converted template arguments.
2821 Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template,
2822 TemplateDeductionInfo &Info, bool IsDeduced,
2823 SmallVectorImpl<TemplateArgument> &SugaredOutput,
2824 SmallVectorImpl<TemplateArgument> &CanonicalOutput) {
2825 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2826 unsigned ArgumentPackIndex) {
2827 // Convert the deduced template argument into a template
2828 // argument that we can check, almost as if the user had written
2829 // the template argument explicitly.
2831 Arg, QualType(), Info.getLocation(), Param);
2832
2833 // Check the template argument, converting it as necessary.
2834 return S.CheckTemplateArgument(
2835 Param, ArgLoc, Template, Template->getLocation(),
2836 Template->getSourceRange().getEnd(), ArgumentPackIndex, SugaredOutput,
2837 CanonicalOutput,
2838 IsDeduced
2842 };
2843
2844 if (Arg.getKind() == TemplateArgument::Pack) {
2845 // This is a template argument pack, so check each of its arguments against
2846 // the template parameter.
2847 SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
2848 CanonicalPackedArgsBuilder;
2849 for (const auto &P : Arg.pack_elements()) {
2850 // When converting the deduced template argument, append it to the
2851 // general output list. We need to do this so that the template argument
2852 // checking logic has all of the prior template arguments available.
2853 DeducedTemplateArgument InnerArg(P);
2855 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2856 "deduced nested pack");
2857 if (P.isNull()) {
2858 // We deduced arguments for some elements of this pack, but not for
2859 // all of them. This happens if we get a conditionally-non-deduced
2860 // context in a pack expansion (such as an overload set in one of the
2861 // arguments).
2862 S.Diag(Param->getLocation(),
2863 diag::err_template_arg_deduced_incomplete_pack)
2864 << Arg << Param;
2865 return true;
2866 }
2867 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
2868 return true;
2869
2870 // Move the converted template argument into our argument pack.
2871 SugaredPackedArgsBuilder.push_back(SugaredOutput.pop_back_val());
2872 CanonicalPackedArgsBuilder.push_back(CanonicalOutput.pop_back_val());
2873 }
2874
2875 // If the pack is empty, we still need to substitute into the parameter
2876 // itself, in case that substitution fails.
2877 if (SugaredPackedArgsBuilder.empty()) {
2879 MultiLevelTemplateArgumentList Args(Template, SugaredOutput,
2880 /*Final=*/true);
2881
2882 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2883 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2884 NTTP, SugaredOutput,
2885 Template->getSourceRange());
2886 if (Inst.isInvalid() ||
2887 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2888 NTTP->getDeclName()).isNull())
2889 return true;
2890 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2891 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2892 TTP, SugaredOutput,
2893 Template->getSourceRange());
2894 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2895 return true;
2896 }
2897 // For type parameters, no substitution is ever required.
2898 }
2899
2900 // Create the resulting argument pack.
2901 SugaredOutput.push_back(
2902 TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
2903 CanonicalOutput.push_back(TemplateArgument::CreatePackCopy(
2904 S.Context, CanonicalPackedArgsBuilder));
2905 return false;
2906 }
2907
2908 return ConvertArg(Arg, 0);
2909}
2910
2911// FIXME: This should not be a template, but
2912// ClassTemplatePartialSpecializationDecl sadly does not derive from
2913// TemplateDecl.
2914template <typename TemplateDeclT>
2916 Sema &S, TemplateDeclT *Template, bool IsDeduced,
2919 SmallVectorImpl<TemplateArgument> &SugaredBuilder,
2920 SmallVectorImpl<TemplateArgument> &CanonicalBuilder,
2921 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2922 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2923 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2924
2925 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2926 NamedDecl *Param = TemplateParams->getParam(I);
2927
2928 // C++0x [temp.arg.explicit]p3:
2929 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2930 // be deduced to an empty sequence of template arguments.
2931 // FIXME: Where did the word "trailing" come from?
2932 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
2933 if (auto Result =
2934 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish();
2936 return Result;
2937 }
2938
2939 if (!Deduced[I].isNull()) {
2940 if (I < NumAlreadyConverted) {
2941 // We may have had explicitly-specified template arguments for a
2942 // template parameter pack (that may or may not have been extended
2943 // via additional deduced arguments).
2944 if (Param->isParameterPack() && CurrentInstantiationScope &&
2945 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2946 // Forget the partially-substituted pack; its substitution is now
2947 // complete.
2948 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2949 // We still need to check the argument in case it was extended by
2950 // deduction.
2951 } else {
2952 // We have already fully type-checked and converted this
2953 // argument, because it was explicitly-specified. Just record the
2954 // presence of this argument.
2955 SugaredBuilder.push_back(Deduced[I]);
2956 CanonicalBuilder.push_back(
2958 continue;
2959 }
2960 }
2961
2962 // We may have deduced this argument, so it still needs to be
2963 // checked and converted.
2964 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2965 IsDeduced, SugaredBuilder,
2966 CanonicalBuilder)) {
2967 Info.Param = makeTemplateParameter(Param);
2968 // FIXME: These template arguments are temporary. Free them!
2969 Info.reset(
2970 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
2971 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
2973 }
2974
2975 continue;
2976 }
2977
2978 // Substitute into the default template argument, if available.
2979 bool HasDefaultArg = false;
2980 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2981 if (!TD) {
2982 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2983 isa<VarTemplatePartialSpecializationDecl>(Template));
2985 }
2986
2987 TemplateArgumentLoc DefArg;
2988 {
2989 Qualifiers ThisTypeQuals;
2990 CXXRecordDecl *ThisContext = nullptr;
2991 if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
2992 if (Rec->isLambda())
2993 if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
2994 ThisContext = Method->getParent();
2995 ThisTypeQuals = Method->getMethodQualifiers();
2996 }
2997
2998 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
2999 S.getLangOpts().CPlusPlus17);
3000
3002 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param,
3003 SugaredBuilder, CanonicalBuilder, HasDefaultArg);
3004 }
3005
3006 // If there was no default argument, deduction is incomplete.
3007 if (DefArg.getArgument().isNull()) {
3009 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
3010 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3011 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3012 if (PartialOverloading) break;
3013
3016 }
3017
3018 // Check whether we can actually use the default argument.
3020 Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
3021 0, SugaredBuilder, CanonicalBuilder, Sema::CTAK_Specified)) {
3023 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
3024 // FIXME: These template arguments are temporary. Free them!
3025 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3026 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3028 }
3029
3030 // If we get here, we successfully used the default template argument.
3031 }
3032
3034}
3035
3037 if (auto *DC = dyn_cast<DeclContext>(D))
3038 return DC;
3039 return D->getDeclContext();
3040}
3041
3042template<typename T> struct IsPartialSpecialization {
3043 static constexpr bool value = false;
3044};
3045template<>
3047 static constexpr bool value = true;
3048};
3049template<>
3051 static constexpr bool value = true;
3052};
3053template <typename TemplateDeclT>
3054static bool DeducedArgsNeedReplacement(TemplateDeclT *Template) {
3055 return false;
3056}
3057template <>
3060 return !Spec->isClassScopeExplicitSpecialization();
3061}
3062template <>
3065 return !Spec->isClassScopeExplicitSpecialization();
3066}
3067
3068template <typename TemplateDeclT>
3070CheckDeducedArgumentConstraints(Sema &S, TemplateDeclT *Template,
3071 ArrayRef<TemplateArgument> SugaredDeducedArgs,
3072 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
3073 TemplateDeductionInfo &Info) {
3074 llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
3075 Template->getAssociatedConstraints(AssociatedConstraints);
3076
3077 std::optional<ArrayRef<TemplateArgument>> Innermost;
3078 // If we don't need to replace the deduced template arguments,
3079 // we can add them immediately as the inner-most argument list.
3080 if (!DeducedArgsNeedReplacement(Template))
3081 Innermost = CanonicalDeducedArgs;
3082
3084 Template, Template->getDeclContext(), /*Final=*/false, Innermost,
3085 /*RelativeToPrimary=*/true, /*Pattern=*/
3086 nullptr, /*ForConstraintInstantiation=*/true);
3087
3088 // getTemplateInstantiationArgs picks up the non-deduced version of the
3089 // template args when this is a variable template partial specialization and
3090 // not class-scope explicit specialization, so replace with Deduced Args
3091 // instead of adding to inner-most.
3092 if (!Innermost)
3093 MLTAL.replaceInnermostTemplateArguments(Template, CanonicalDeducedArgs);
3094
3095 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
3096 Info.getLocation(),
3099 Info.reset(
3100 TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
3101 TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
3103 }
3105}
3106
3107/// Complete template argument deduction for a partial specialization.
3108template <typename T>
3109static std::enable_if_t<IsPartialSpecialization<T>::value,
3112 Sema &S, T *Partial, bool IsPartialOrdering,
3113 ArrayRef<TemplateArgument> TemplateArgs,
3115 TemplateDeductionInfo &Info) {
3116 // Unevaluated SFINAE context.
3119 Sema::SFINAETrap Trap(S);
3120
3121 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
3122
3123 // C++ [temp.deduct.type]p2:
3124 // [...] or if any template argument remains neither deduced nor
3125 // explicitly specified, template argument deduction fails.
3126 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3128 S, Partial, IsPartialOrdering, Deduced, Info, SugaredBuilder,
3129 CanonicalBuilder);
3131 return Result;
3132
3133 // Form the template argument list from the deduced template arguments.
3134 TemplateArgumentList *SugaredDeducedArgumentList =
3135 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
3136 TemplateArgumentList *CanonicalDeducedArgumentList =
3137 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
3138
3139 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3140
3141 // Substitute the deduced template arguments into the template
3142 // arguments of the class template partial specialization, and
3143 // verify that the instantiated template arguments are both valid
3144 // and are equivalent to the template arguments originally provided
3145 // to the class template.
3146 LocalInstantiationScope InstScope(S);
3147 auto *Template = Partial->getSpecializedTemplate();
3148 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
3149 Partial->getTemplateArgsAsWritten();
3150
3151 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
3152 PartialTemplArgInfo->RAngleLoc);
3153
3154 if (S.SubstTemplateArguments(PartialTemplArgInfo->arguments(),
3156 SugaredBuilder,
3157 /*Final=*/true),
3158 InstArgs)) {
3159 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
3160 if (ParamIdx >= Partial->getTemplateParameters()->size())
3161 ParamIdx = Partial->getTemplateParameters()->size() - 1;
3162
3163 Decl *Param = const_cast<NamedDecl *>(
3164 Partial->getTemplateParameters()->getParam(ParamIdx));
3165 Info.Param = makeTemplateParameter(Param);
3166 Info.FirstArg = (*PartialTemplArgInfo)[ArgIdx].getArgument();
3168 }
3169
3171 SmallVector<TemplateArgument, 4> SugaredConvertedInstArgs,
3172 CanonicalConvertedInstArgs;
3174 Template, Partial->getLocation(), InstArgs, false,
3175 SugaredConvertedInstArgs, CanonicalConvertedInstArgs,
3176 /*UpdateArgsWithConversions=*/true, &ConstraintsNotSatisfied))
3180
3181 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3182 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3183 TemplateArgument InstArg = SugaredConvertedInstArgs.data()[I];
3184 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
3185 IsPartialOrdering)) {
3186 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3187 Info.FirstArg = TemplateArgs[I];
3188 Info.SecondArg = InstArg;
3190 }
3191 }
3192
3193 if (Trap.hasErrorOccurred())
3195
3196 if (auto Result = CheckDeducedArgumentConstraints(S, Partial, SugaredBuilder,
3197 CanonicalBuilder, Info);
3199 return Result;
3200
3202}
3203
3204/// Complete template argument deduction for a class or variable template,
3205/// when partial ordering against a partial specialization.
3206// FIXME: Factor out duplication with partial specialization version above.
3208 Sema &S, TemplateDecl *Template, bool PartialOrdering,
3209 ArrayRef<TemplateArgument> TemplateArgs,
3211 TemplateDeductionInfo &Info) {
3212 // Unevaluated SFINAE context.
3215 Sema::SFINAETrap Trap(S);
3216
3217 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
3218
3219 // C++ [temp.deduct.type]p2:
3220 // [...] or if any template argument remains neither deduced nor
3221 // explicitly specified, template argument deduction fails.
3222 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3224 S, Template, /*IsDeduced*/ PartialOrdering, Deduced, Info,
3225 SugaredBuilder, CanonicalBuilder,
3226 /*CurrentInstantiationScope=*/nullptr,
3227 /*NumAlreadyConverted=*/0U, /*PartialOverloading=*/false);
3229 return Result;
3230
3231 // Check that we produced the correct argument list.
3232 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3233 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3234 TemplateArgument InstArg = CanonicalBuilder[I];
3235 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg, PartialOrdering,
3236 /*PackExpansionMatchesPack=*/true)) {
3237 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3238 Info.FirstArg = TemplateArgs[I];
3239 Info.SecondArg = InstArg;
3241 }
3242 }
3243
3244 if (Trap.hasErrorOccurred())
3246
3247 if (auto Result = CheckDeducedArgumentConstraints(S, Template, SugaredBuilder,
3248 CanonicalBuilder, Info);
3250 return Result;
3251
3253}
3254/// Complete template argument deduction for DeduceTemplateArgumentsFromType.
3255/// FIXME: this is mostly duplicated with the above two versions. Deduplicate
3256/// the three implementations.
3258 Sema &S, TemplateDecl *TD,
3260 TemplateDeductionInfo &Info) {
3261 // Unevaluated SFINAE context.
3264 Sema::SFINAETrap Trap(S);
3265
3267
3268 // C++ [temp.deduct.type]p2:
3269 // [...] or if any template argument remains neither deduced nor
3270 // explicitly specified, template argument deduction fails.
3271 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3273 S, TD, /*IsPartialOrdering=*/false, Deduced, Info, SugaredBuilder,
3274 CanonicalBuilder);
3276 return Result;
3277
3278 if (Trap.hasErrorOccurred())
3280
3281 if (auto Result = CheckDeducedArgumentConstraints(S, TD, SugaredBuilder,
3282 CanonicalBuilder, Info);
3284 return Result;
3285
3287}
3288
3289/// Perform template argument deduction to determine whether the given template
3290/// arguments match the given class or variable template partial specialization
3291/// per C++ [temp.class.spec.match].
3292template <typename T>
3293static std::enable_if_t<IsPartialSpecialization<T>::value,
3296 ArrayRef<TemplateArgument> TemplateArgs,
3297 TemplateDeductionInfo &Info) {
3298 if (Partial->isInvalidDecl())
3300
3301 // C++ [temp.class.spec.match]p2:
3302 // A partial specialization matches a given actual template
3303 // argument list if the template arguments of the partial
3304 // specialization can be deduced from the actual template argument
3305 // list (14.8.2).
3306
3307 // Unevaluated SFINAE context.
3310 Sema::SFINAETrap Trap(S);
3311
3312 // This deduction has no relation to any outer instantiation we might be
3313 // performing.
3314 LocalInstantiationScope InstantiationScope(S);
3315
3317 Deduced.resize(Partial->getTemplateParameters()->size());
3319 S, Partial->getTemplateParameters(),
3320 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3321 /*NumberOfArgumentsMustMatch=*/false);
3323 return Result;
3324
3325 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3326 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs,
3327 Info);
3328 if (Inst.isInvalid())
3330
3331 if (Trap.hasErrorOccurred())
3333
3336 Result = ::FinishTemplateArgumentDeduction(S, Partial,
3337 /*IsPartialOrdering=*/false,
3338 TemplateArgs, Deduced, Info);
3339 });
3340 return Result;
3341}
3342
3345 ArrayRef<TemplateArgument> TemplateArgs,
3346 TemplateDeductionInfo &Info) {
3347 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3348}
3351 ArrayRef<TemplateArgument> TemplateArgs,
3352 TemplateDeductionInfo &Info) {
3353 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3354}
3355
3359 if (TD->isInvalidDecl())
3361
3362 QualType PType;
3363 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
3364 // Use the InjectedClassNameType.
3365 PType = Context.getTypeDeclType(CTD->getTemplatedDecl());
3366 } else if (const auto *AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(TD)) {
3367 PType = AliasTemplate->getTemplatedDecl()->getUnderlyingType();
3368 } else {
3369 assert(false && "Expected a class or alias template");
3370 }
3371
3372 // Unevaluated SFINAE context.
3375 SFINAETrap Trap(*this);
3376
3377 // This deduction has no relation to any outer instantiation we might be
3378 // performing.
3379 LocalInstantiationScope InstantiationScope(*this);
3380
3382 TD->getTemplateParameters()->size());
3385 if (auto DeducedResult = DeduceTemplateArguments(
3386 TD->getTemplateParameters(), PArgs, AArgs, Info, Deduced, false);
3387 DeducedResult != TemplateDeductionResult::Success) {
3388 return DeducedResult;
3389 }
3390
3391 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3392 InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs, Info);
3393 if (Inst.isInvalid())
3395
3396 if (Trap.hasErrorOccurred())
3398
3401 Result = ::FinishTemplateArgumentDeduction(*this, TD, Deduced, Info);
3402 });
3403 return Result;
3404}
3405
3406/// Determine whether the given type T is a simple-template-id type.
3408 if (const TemplateSpecializationType *Spec
3410 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
3411
3412 // C++17 [temp.local]p2:
3413 // the injected-class-name [...] is equivalent to the template-name followed
3414 // by the template-arguments of the class template specialization or partial
3415 // specialization enclosed in <>
3416 // ... which means it's equivalent to a simple-template-id.
3417 //
3418 // This only arises during class template argument deduction for a copy
3419 // deduction candidate, where it permits slicing.
3421 return true;
3422
3423 return false;
3424}
3425
3427 FunctionTemplateDecl *FunctionTemplate,
3428 TemplateArgumentListInfo &ExplicitTemplateArgs,
3431 TemplateDeductionInfo &Info) {
3432 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3433 TemplateParameterList *TemplateParams
3434 = FunctionTemplate->getTemplateParameters();
3435
3436 if (ExplicitTemplateArgs.size() == 0) {
3437 // No arguments to substitute; just copy over the parameter types and
3438 // fill in the function type.
3439 for (auto *P : Function->parameters())
3440 ParamTypes.push_back(P->getType());
3441
3442 if (FunctionType)
3443 *FunctionType = Function->getType();
3445 }
3446
3447 // Unevaluated SFINAE context.
3450 SFINAETrap Trap(*this);
3451
3452 // C++ [temp.arg.explicit]p3:
3453 // Template arguments that are present shall be specified in the
3454 // declaration order of their corresponding template-parameters. The
3455 // template argument list shall not specify more template-arguments than
3456 // there are corresponding template-parameters.
3457 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3458
3459 // Enter a new template instantiation context where we check the
3460 // explicitly-specified template arguments against this function template,
3461 // and then substitute them into the function parameter types.
3464 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3466 if (Inst.isInvalid())
3468
3470 ExplicitTemplateArgs, true, SugaredBuilder,
3471 CanonicalBuilder,
3472 /*UpdateArgsWithConversions=*/false) ||
3473 Trap.hasErrorOccurred()) {
3474 unsigned Index = SugaredBuilder.size();
3475 if (Index >= TemplateParams->size())
3477 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3479 }
3480
3481 // Form the template argument list from the explicitly-specified
3482 // template arguments.
3483 TemplateArgumentList *SugaredExplicitArgumentList =
3485 TemplateArgumentList *CanonicalExplicitArgumentList =
3486 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3487 Info.setExplicitArgs(SugaredExplicitArgumentList,
3488 CanonicalExplicitArgumentList);
3489
3490 // Template argument deduction and the final substitution should be
3491 // done in the context of the templated declaration. Explicit
3492 // argument substitution, on the other hand, needs to happen in the
3493 // calling context.
3494 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3495
3496 // If we deduced template arguments for a template parameter pack,
3497 // note that the template argument pack is partially substituted and record
3498 // the explicit template arguments. They'll be used as part of deduction
3499 // for this template parameter pack.
3500 unsigned PartiallySubstitutedPackIndex = -1u;
3501 if (!SugaredBuilder.empty()) {
3502 const TemplateArgument &Arg = SugaredBuilder.back();
3503 if (Arg.getKind() == TemplateArgument::Pack) {
3504 auto *Param = TemplateParams->getParam(SugaredBuilder.size() - 1);
3505 // If this is a fully-saturated fixed-size pack, it should be
3506 // fully-substituted, not partially-substituted.
3507 std::optional<unsigned> Expansions = getExpandedPackSize(Param);
3508 if (!Expansions || Arg.pack_size() < *Expansions) {
3509 PartiallySubstitutedPackIndex = SugaredBuilder.size() - 1;
3511 Param, Arg.pack_begin(), Arg.pack_size());
3512 }
3513 }
3514 }
3515
3516 const FunctionProtoType *Proto
3517 = Function->getType()->getAs<FunctionProtoType>();
3518 assert(Proto && "Function template does not have a prototype?");
3519
3520 // Isolate our substituted parameters from our caller.
3521 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3522
3523 ExtParameterInfoBuilder ExtParamInfos;
3524
3526 SugaredExplicitArgumentList->asArray(),
3527 /*Final=*/true);
3528
3529 // Instantiate the types of each of the function parameters given the
3530 // explicitly-specified template arguments. If the function has a trailing
3531 // return type, substitute it after the arguments to ensure we substitute
3532 // in lexical order.
3533 if (Proto->hasTrailingReturn()) {
3534 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3535 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3536 /*params=*/nullptr, ExtParamInfos))
3538 }
3539
3540 // Instantiate the return type.
3541 QualType ResultType;
3542 {
3543 // C++11 [expr.prim.general]p3:
3544 // If a declaration declares a member function or member function
3545 // template of a class X, the expression this is a prvalue of type
3546 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3547 // and the end of the function-definition, member-declarator, or
3548 // declarator.
3549 Qualifiers ThisTypeQuals;
3550 CXXRecordDecl *ThisContext = nullptr;
3551 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3552 ThisContext = Method->getParent();
3553 ThisTypeQuals = Method->getMethodQualifiers();
3554 }
3555
3556 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3558
3559 ResultType =
3560 SubstType(Proto->getReturnType(), MLTAL,
3561 Function->getTypeSpecStartLoc(), Function->getDeclName());
3562 if (ResultType.isNull() || Trap.hasErrorOccurred())
3564 // CUDA: Kernel function must have 'void' return type.
3565 if (getLangOpts().CUDA)
3566 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3567 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3568 << Function->getType() << Function->getSourceRange();
3570 }
3571 }
3572
3573 // Instantiate the types of each of the function parameters given the
3574 // explicitly-specified template arguments if we didn't do so earlier.
3575 if (!Proto->hasTrailingReturn() &&
3576 SubstParmTypes(Function->getLocation(), Function->parameters(),
3577 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3578 /*params*/ nullptr, ExtParamInfos))
3580
3581 if (FunctionType) {
3582 auto EPI = Proto->getExtProtoInfo();
3583 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3584 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3585 Function->getLocation(),
3586 Function->getDeclName(),
3587 EPI);
3588 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3590 }
3591
3592 // C++ [temp.arg.explicit]p2:
3593 // Trailing template arguments that can be deduced (14.8.2) may be
3594 // omitted from the list of explicit template-arguments. If all of the
3595 // template arguments can be deduced, they may all be omitted; in this
3596 // case, the empty template argument list <> itself may also be omitted.
3597 //
3598 // Take all of the explicitly-specified arguments and put them into
3599 // the set of deduced template arguments. The partially-substituted
3600 // parameter pack, however, will be set to NULL since the deduction
3601 // mechanism handles the partially-substituted argument pack directly.
3602 Deduced.reserve(TemplateParams->size());
3603 for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3604 const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
3605 if (I == PartiallySubstitutedPackIndex)
3606 Deduced.push_back(DeducedTemplateArgument());
3607 else
3608 Deduced.push_back(Arg);
3609 }
3610
3612}
3613
3614/// Check whether the deduced argument type for a call to a function
3615/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3618 Sema::OriginalCallArg OriginalArg,
3619 QualType DeducedA) {
3620 ASTContext &Context = S.Context;
3621
3622 auto Failed = [&]() -> TemplateDeductionResult {
3623 Info.FirstArg = TemplateArgument(DeducedA);
3624 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3625 Info.CallArgIndex = OriginalArg.ArgIdx;
3626 return OriginalArg.DecomposedParam
3629 };
3630
3631 QualType A = OriginalArg.OriginalArgType;
3632 QualType OriginalParamType = OriginalArg.OriginalParamType;
3633
3634 // Check for type equality (top-level cv-qualifiers are ignored).
3635 if (Context.hasSameUnqualifiedType(A, DeducedA))
3637
3638 // Strip off references on the argument types; they aren't needed for
3639 // the following checks.
3640 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3641 DeducedA = DeducedARef->getPointeeType();
3642 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3643 A = ARef->getPointeeType();
3644
3645 // C++ [temp.deduct.call]p4:
3646 // [...] However, there are three cases that allow a difference:
3647 // - If the original P is a reference type, the deduced A (i.e., the
3648 // type referred to by the reference) can be more cv-qualified than
3649 // the transformed A.
3650 if (const ReferenceType *OriginalParamRef
3651 = OriginalParamType->getAs<ReferenceType>()) {
3652 // We don't want to keep the reference around any more.
3653 OriginalParamType = OriginalParamRef->getPointeeType();
3654
3655 // FIXME: Resolve core issue (no number yet): if the original P is a
3656 // reference type and the transformed A is function type "noexcept F",
3657 // the deduced A can be F.
3658 QualType Tmp;
3659 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
3661
3662 Qualifiers AQuals = A.getQualifiers();
3663 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3664
3665 // Under Objective-C++ ARC, the deduced type may have implicitly
3666 // been given strong or (when dealing with a const reference)
3667 // unsafe_unretained lifetime. If so, update the original
3668 // qualifiers to include this lifetime.
3669 if (S.getLangOpts().ObjCAutoRefCount &&
3670 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3672 (DeducedAQuals.hasConst() &&
3673 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3674 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3675 }
3676
3677 if (AQuals == DeducedAQuals) {
3678 // Qualifiers match; there's nothing to do.
3679 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
3680 return Failed();
3681 } else {
3682 // Qualifiers are compatible, so have the argument type adopt the
3683 // deduced argument type's qualifiers as if we had performed the
3684 // qualification conversion.
3685 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3686 }
3687 }
3688
3689 // - The transformed A can be another pointer or pointer to member
3690 // type that can be converted to the deduced A via a function pointer
3691 // conversion and/or a qualification conversion.
3692 //
3693 // Also allow conversions which merely strip __attribute__((noreturn)) from
3694 // function types (recursively).
3695 bool ObjCLifetimeConversion = false;
3696 QualType ResultTy;
3697 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3698 (S.IsQualificationConversion(A, DeducedA, false,
3699 ObjCLifetimeConversion) ||
3700 S.IsFunctionConversion(A, DeducedA, ResultTy)))
3702
3703 // - If P is a class and P has the form simple-template-id, then the
3704 // transformed A can be a derived class of the deduced A. [...]
3705 // [...] Likewise, if P is a pointer to a class of the form
3706 // simple-template-id, the transformed A can be a pointer to a
3707 // derived class pointed to by the deduced A.
3708 if (const PointerType *OriginalParamPtr
3709 = OriginalParamType->getAs<PointerType>()) {
3710 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3711 if (const PointerType *APtr = A->getAs<PointerType>()) {
3712 if (A->getPointeeType()->isRecordType()) {
3713 OriginalParamType = OriginalParamPtr->getPointeeType();
3714 DeducedA = DeducedAPtr->getPointeeType();
3715 A = APtr->getPointeeType();
3716 }
3717 }
3718 }
3719 }
3720
3721 if (Context.hasSameUnqualifiedType(A, DeducedA))
3723
3724 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3725 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3727
3728 return Failed();
3729}
3730
3731/// Find the pack index for a particular parameter index in an instantiation of
3732/// a function template with specific arguments.
3733///
3734/// \return The pack index for whichever pack produced this parameter, or -1
3735/// if this was not produced by a parameter. Intended to be used as the
3736/// ArgumentPackSubstitutionIndex for further substitutions.
3737// FIXME: We should track this in OriginalCallArgs so we don't need to
3738// reconstruct it here.
3739static unsigned getPackIndexForParam(Sema &S,
3740 FunctionTemplateDecl *FunctionTemplate,
3742 unsigned ParamIdx) {
3743 unsigned Idx = 0;
3744 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3745 if (PD->isParameterPack()) {
3746 unsigned NumExpansions =
3747 S.getNumArgumentsInExpansion(PD->getType(), Args).value_or(1);
3748 if (Idx + NumExpansions > ParamIdx)
3749 return ParamIdx - Idx;
3750 Idx += NumExpansions;
3751 } else {
3752 if (Idx == ParamIdx)
3753 return -1; // Not a pack expansion
3754 ++Idx;
3755 }
3756 }
3757
3758 llvm_unreachable("parameter index would not be produced from template");
3759}
3760
3761// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`,
3762// we'll try to instantiate and update its explicit specifier after constraint
3763// checking.
3766 const MultiLevelTemplateArgumentList &SubstArgs,
3767 TemplateDeductionInfo &Info, FunctionTemplateDecl *FunctionTemplate,
3768 ArrayRef<TemplateArgument> DeducedArgs) {
3769 auto GetExplicitSpecifier = [](FunctionDecl *D) {
3770 return isa<CXXConstructorDecl>(D)
3771 ? cast<CXXConstructorDecl>(D)->getExplicitSpecifier()
3772 : cast<CXXConversionDecl>(D)->getExplicitSpecifier();
3773 };
3774 auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) {
3775 isa<CXXConstructorDecl>(D)
3776 ? cast<CXXConstructorDecl>(D)->setExplicitSpecifier(ES)
3777 : cast<CXXConversionDecl>(D)->setExplicitSpecifier(ES);
3778 };
3779
3780 ExplicitSpecifier ES = GetExplicitSpecifier(Specialization);
3781 Expr *ExplicitExpr = ES.getExpr();
3782 if (!ExplicitExpr)
3784 if (!ExplicitExpr->isValueDependent())
3786
3788 S, Info.getLocation(), FunctionTemplate, DeducedArgs,
3790 if (Inst.isInvalid())
3792 Sema::SFINAETrap Trap(S);
3793 const ExplicitSpecifier InstantiatedES =
3794 S.instantiateExplicitSpecifier(SubstArgs, ES);
3795 if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) {
3796 Specialization->setInvalidDecl(true);
3798 }
3799 SetExplicitSpecifier(Specialization, InstantiatedES);
3801}
3802
3804 FunctionTemplateDecl *FunctionTemplate,
3806 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3808 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3809 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
3810 // Unevaluated SFINAE context.
3813 SFINAETrap Trap(*this);
3814
3815 // Enter a new template instantiation context while we instantiate the
3816 // actual function declaration.
3817 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3819 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3821 if (Inst.isInvalid())
3823
3824 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3825
3826 // C++ [temp.deduct.type]p2:
3827 // [...] or if any template argument remains neither deduced nor
3828 // explicitly specified, template argument deduction fails.
3829 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3831 *this, FunctionTemplate, /*IsDeduced*/ true, Deduced, Info,
3832 SugaredBuilder, CanonicalBuilder, CurrentInstantiationScope,
3833 NumExplicitlySpecified, PartialOverloading);
3835 return Result;
3836
3837 // C++ [temp.deduct.call]p10: [DR1391]
3838 // If deduction succeeds for all parameters that contain
3839 // template-parameters that participate in template argument deduction,
3840 // and all template arguments are explicitly specified, deduced, or
3841 // obtained from default template arguments, remaining parameters are then
3842 // compared with the corresponding arguments. For each remaining parameter
3843 // P with a type that was non-dependent before substitution of any
3844 // explicitly-specified template arguments, if the corresponding argument
3845 // A cannot be implicitly converted to P, deduction fails.
3846 if (CheckNonDependent())
3848
3849 // Form the template argument list from the deduced template arguments.
3850 TemplateArgumentList *SugaredDeducedArgumentList =
3852 TemplateArgumentList *CanonicalDeducedArgumentList =
3853 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3854 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3855
3856 // Substitute the deduced template arguments into the function template
3857 // declaration to produce the function template specialization.
3858 DeclContext *Owner = FunctionTemplate->getDeclContext();
3859 if (FunctionTemplate->getFriendObjectKind())
3860 Owner = FunctionTemplate->getLexicalDeclContext();
3861 FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
3862 // additional check for inline friend,
3863 // ```
3864 // template <class F1> int foo(F1 X);
3865 // template <int A1> struct A {
3866 // template <class F1> friend int foo(F1 X) { return A1; }
3867 // };
3868 // template struct A<1>;
3869 // int a = foo(1.0);
3870 // ```
3871 const FunctionDecl *FDFriend;
3873 FD->isDefined(FDFriend, /*CheckForPendingFriendDefinition*/ true) &&
3875 FD = const_cast<FunctionDecl *>(FDFriend);
3876 Owner = FD->getLexicalDeclContext();
3877 }
3879 FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
3880 /*Final=*/false);
3881 Specialization = cast_or_null<FunctionDecl>(
3882 SubstDecl(FD, Owner, SubstArgs));
3883 if (!Specialization || Specialization->isInvalidDecl())
3885
3886 assert(isSameDeclaration(Specialization->getPrimaryTemplate(),
3888
3889 // If the template argument list is owned by the function template
3890 // specialization, release it.
3891 if (Specialization->getTemplateSpecializationArgs() ==
3892 CanonicalDeducedArgumentList &&
3893 !Trap.hasErrorOccurred())
3894 Info.takeCanonical();
3895
3896 // There may have been an error that did not prevent us from constructing a
3897 // declaration. Mark the declaration invalid and return with a substitution
3898 // failure.
3899 if (Trap.hasErrorOccurred()) {
3900 Specialization->setInvalidDecl(true);
3902 }
3903
3904 // C++2a [temp.deduct]p5
3905 // [...] When all template arguments have been deduced [...] all uses of
3906 // template parameters [...] are replaced with the corresponding deduced
3907 // or default argument values.
3908 // [...] If the function template has associated constraints
3909 // ([temp.constr.decl]), those constraints are checked for satisfaction
3910 // ([temp.constr.constr]). If the constraints are not satisfied, type
3911 // deduction fails.
3912 if (!PartialOverloading ||
3913 (CanonicalBuilder.size() ==
3914 FunctionTemplate->getTemplateParameters()->size())) {
3916 Info.getLocation(), Specialization, CanonicalBuilder,
3919
3921 Info.reset(Info.takeSugared(),
3922 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder));
3924 }
3925 }
3926
3927 // We skipped the instantiation of the explicit-specifier during the
3928 // substitution of `FD` before. So, we try to instantiate it back if
3929 // `Specialization` is either a constructor or a conversion function.
3930 if (isa<CXXConstructorDecl, CXXConversionDecl>(Specialization)) {
3933 Info, FunctionTemplate,
3934 DeducedArgs)) {
3936 }
3937 }
3938
3939 if (OriginalCallArgs) {
3940 // C++ [temp.deduct.call]p4:
3941 // In general, the deduction process attempts to find template argument
3942 // values that will make the deduced A identical to A (after the type A
3943 // is transformed as described above). [...]
3944 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
3945 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3946 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
3947
3948 auto ParamIdx = OriginalArg.ArgIdx;
3949 unsigned ExplicitOffset =
3950 Specialization->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
3951 if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset)
3952 // FIXME: This presumably means a pack ended up smaller than we
3953 // expected while deducing. Should this not result in deduction
3954 // failure? Can it even happen?
3955 continue;
3956
3957 QualType DeducedA;
3958 if (!OriginalArg.DecomposedParam) {
3959 // P is one of the function parameters, just look up its substituted
3960 // type.
3961 DeducedA =
3962 Specialization->getParamDecl(ParamIdx + ExplicitOffset)->getType();
3963 } else {
3964 // P is a decomposed element of a parameter corresponding to a
3965 // braced-init-list argument. Substitute back into P to find the
3966 // deduced A.
3967 QualType &CacheEntry =
3968 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3969 if (CacheEntry.isNull()) {
3971 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3972 ParamIdx));
3973 CacheEntry =
3974 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3975 Specialization->getTypeSpecStartLoc(),
3976 Specialization->getDeclName());
3977 }
3978 DeducedA = CacheEntry;
3979 }
3980
3981 if (auto TDK =
3982 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
3984 return TDK;
3985 }
3986 }
3987
3988 // If we suppressed any diagnostics while performing template argument
3989 // deduction, and if we haven't already instantiated this declaration,
3990 // keep track of these diagnostics. They'll be emitted if this specialization
3991 // is actually used.
3992 if (Info.diag_begin() != Info.diag_end()) {
3993 SuppressedDiagnosticsMap::iterator
3994 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3995 if (Pos == SuppressedDiagnostics.end())
3996 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3997 .append(Info.diag_begin(), Info.diag_end());
3998 }
3999
4001}
4002
4003/// Gets the type of a function for template-argument-deducton
4004/// purposes when it's considered as part of an overload set.
4006 FunctionDecl *Fn) {
4007 // We may need to deduce the return type of the function now.
4008 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
4009 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
4010 return {};
4011
4012 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
4013 if (Method->isImplicitObjectMemberFunction()) {
4014 // An instance method that's referenced in a form that doesn't
4015 // look like a member pointer is just invalid.
4017 return {};
4018
4019 return S.Context.getMemberPointerType(Fn->getType(),
4020 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
4021 }
4022
4023 if (!R.IsAddressOfOperand) return Fn->getType();
4024 return S.Context.getPointerType(Fn->getType());
4025}
4026
4027/// Apply the deduction rules for overload sets.
4028///
4029/// \return the null type if this argument should be treated as an
4030/// undeduced context
4031static QualType
4033 Expr *Arg, QualType ParamType,
4034 bool ParamWasReference,
4035 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4036
4038
4039 OverloadExpr *Ovl = R.Expression;
4040
4041 // C++0x [temp.deduct.call]p4
4042 unsigned TDF = 0;
4043 if (ParamWasReference)
4045 if (R.IsAddressOfOperand)
4046 TDF |= TDF_IgnoreQualifiers;
4047
4048 // C++0x [temp.deduct.call]p6:
4049 // When P is a function type, pointer to function type, or pointer
4050 // to member function type:
4051
4052 if (!ParamType->isFunctionType() &&
4053 !ParamType->isFunctionPointerType() &&
4054 !ParamType->isMemberFunctionPointerType()) {
4055 if (Ovl->hasExplicitTemplateArgs()) {
4056 // But we can still look for an explicit specialization.
4057 if (FunctionDecl *ExplicitSpec =
4059 Ovl, /*Complain=*/false,
4060 /*FoundDeclAccessPair=*/nullptr, FailedTSC))
4061 return GetTypeOfFunction(S, R, ExplicitSpec);
4062 }
4063
4064 DeclAccessPair DAP;
4065 if (FunctionDecl *Viable =
4067 return GetTypeOfFunction(S, R, Viable);
4068
4069 return {};
4070 }
4071
4072 // Gather the explicit template arguments, if any.
4073 TemplateArgumentListInfo ExplicitTemplateArgs;
4074 if (Ovl->hasExplicitTemplateArgs())
4075 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4076 QualType Match;
4077 for (UnresolvedSetIterator I = Ovl->decls_begin(),
4078 E = Ovl->decls_end(); I != E; ++I) {
4079 NamedDecl *D = (*I)->getUnderlyingDecl();
4080
4081 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
4082 // - If the argument is an overload set containing one or more
4083 // function templates, the parameter is treated as a
4084 // non-deduced context.
4085 if (!Ovl->hasExplicitTemplateArgs())
4086 return {};
4087
4088 // Otherwise, see if we can resolve a function type
4089 FunctionDecl *Specialization = nullptr;
4090 TemplateDeductionInfo Info(Ovl->getNameLoc());
4091 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
4094 continue;
4095
4096 D = Specialization;
4097 }
4098
4099 FunctionDecl *Fn = cast<FunctionDecl>(D);
4100 QualType ArgType = GetTypeOfFunction(S, R, Fn);
4101 if (ArgType.isNull()) continue;
4102
4103 // Function-to-pointer conversion.
4104 if (!ParamWasReference && ParamType->isPointerType() &&
4105 ArgType->isFunctionType())
4106 ArgType = S.Context.getPointerType(ArgType);
4107
4108 // - If the argument is an overload set (not containing function
4109 // templates), trial argument deduction is attempted using each
4110 // of the members of the set. If deduction succeeds for only one
4111 // of the overload set members, that member is used as the
4112 // argument value for the deduction. If deduction succeeds for
4113 // more than one member of the overload set the parameter is
4114 // treated as a non-deduced context.
4115
4116 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
4117 // Type deduction is done independently for each P/A pair, and
4118 // the deduced template argument values are then combined.
4119 // So we do not reject deductions which were made elsewhere.
4121 Deduced(TemplateParams->size());
4122 TemplateDeductionInfo Info(Ovl->getNameLoc());
4124 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF);
4126 continue;
4127 if (!Match.isNull())
4128 return {};
4129 Match = ArgType;
4130 }
4131
4132 return Match;
4133}
4134
4135/// Perform the adjustments to the parameter and argument types
4136/// described in C++ [temp.deduct.call].
4137///
4138/// \returns true if the caller should not attempt to perform any template
4139/// argument deduction based on this P/A pair because the argument is an
4140/// overloaded function set that could not be resolved.
4142 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4143 QualType &ParamType, QualType &ArgType,
4144 Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
4145 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4146 // C++0x [temp.deduct.call]p3:
4147 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
4148 // are ignored for type deduction.
4149 if (ParamType.hasQualifiers())
4150 ParamType = ParamType.getUnqualifiedType();
4151
4152 // [...] If P is a reference type, the type referred to by P is
4153 // used for type deduction.
4154 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
4155 if (ParamRefType)
4156 ParamType = ParamRefType->getPointeeType();
4157
4158 // Overload sets usually make this parameter an undeduced context,
4159 // but there are sometimes special circumstances. Typically
4160 // involving a template-id-expr.
4161 if (ArgType == S.Context.OverloadTy) {
4162 assert(Arg && "expected a non-null arg expression");
4163 ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType,
4164 ParamRefType != nullptr, FailedTSC);
4165 if (ArgType.isNull())
4166 return true;
4167 }
4168
4169 if (ParamRefType) {
4170 // If the argument has incomplete array type, try to complete its type.
4171 if (ArgType->isIncompleteArrayType()) {
4172 assert(Arg && "expected a non-null arg expression");
4173 ArgType = S.getCompletedType(Arg);
4174 }
4175
4176 // C++1z [temp.deduct.call]p3:
4177 // If P is a forwarding reference and the argument is an lvalue, the type
4178 // "lvalue reference to A" is used in place of A for type deduction.
4179 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
4180 ArgClassification.isLValue()) {
4181 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
4182 ArgType = S.Context.getAddrSpaceQualType(
4184 ArgType = S.Context.getLValueReferenceType(ArgType);
4185 }
4186 } else {
4187 // C++ [temp.deduct.call]p2:
4188 // If P is not a reference type:
4189 // - If A is an array type, the pointer type produced by the
4190 // array-to-pointer standard conversion (4.2) is used in place of
4191 // A for type deduction; otherwise,
4192 // - If A is a function type, the pointer type produced by the
4193 // function-to-pointer standard conversion (4.3) is used in place
4194 // of A for type deduction; otherwise,
4195 if (ArgType->canDecayToPointerType())
4196 ArgType = S.Context.getDecayedType(ArgType);
4197 else {
4198 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
4199 // type are ignored for type deduction.
4200 ArgType = ArgType.getUnqualifiedType();
4201 }
4202 }
4203
4204 // C++0x [temp.deduct.call]p4:
4205 // In general, the deduction process attempts to find template argument
4206 // values that will make the deduced A identical to A (after the type A
4207 // is transformed as described above). [...]
4209
4210 // - If the original P is a reference type, the deduced A (i.e., the
4211 // type referred to by the reference) can be more cv-qualified than
4212 // the transformed A.
4213 if (ParamRefType)
4215 // - The transformed A can be another pointer or pointer to member
4216 // type that can be converted to the deduced A via a qualification
4217 // conversion (4.4).
4218 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
4219 ArgType->isObjCObjectPointerType())
4220 TDF |= TDF_IgnoreQualifiers;
4221 // - If P is a class and P has the form simple-template-id, then the
4222 // transformed A can be a derived class of the deduced A. Likewise,
4223 // if P is a pointer to a class of the form simple-template-id, the
4224 // transformed A can be a pointer to a derived class pointed to by
4225 // the deduced A.
4226 if (isSimpleTemplateIdType(ParamType) ||
4227 (isa<PointerType>(ParamType) &&
4229 ParamType->castAs<PointerType>()->getPointeeType())))
4230 TDF |= TDF_DerivedClass;
4231
4232 return false;
4233}
4234
4235static bool
4237 QualType T);
4238
4240 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4241 QualType ParamType, QualType ArgType,
4242 Expr::Classification ArgClassification, Expr *Arg,
4246 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4247 TemplateSpecCandidateSet *FailedTSC = nullptr);
4248
4249/// Attempt template argument deduction from an initializer list
4250/// deemed to be an argument in a function call.
4252 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
4255 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
4256 unsigned TDF) {
4257 // C++ [temp.deduct.call]p1: (CWG 1591)
4258 // If removing references and cv-qualifiers from P gives
4259 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
4260 // a non-empty initializer list, then deduction is performed instead for
4261 // each element of the initializer list, taking P0 as a function template
4262 // parameter type and the initializer element as its argument
4263 //
4264 // We've already removed references and cv-qualifiers here.
4265 if (!ILE->getNumInits())
4267
4268 QualType ElTy;
4269 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
4270 if (ArrTy)
4271 ElTy = ArrTy->getElementType();
4272 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
4273 // Otherwise, an initializer list argument causes the parameter to be
4274 // considered a non-deduced context
4276 }
4277
4278 // Resolving a core issue: a braced-init-list containing any designators is
4279 // a non-deduced context.
4280 for (Expr *E : ILE->inits())
4281 if (isa<DesignatedInitExpr>(E))
4283
4284 // Deduction only needs to be done for dependent types.
4285 if (ElTy->isDependentType()) {
4286 for (Expr *E : ILE->inits()) {
4288 S, TemplateParams, 0, ElTy, E->getType(),
4289 E->Classify(S.getASTContext()), E, Info, Deduced,
4290 OriginalCallArgs, true, ArgIdx, TDF);
4292 return Result;
4293 }
4294 }
4295
4296 // in the P0[N] case, if N is a non-type template parameter, N is deduced
4297 // from the length of the initializer list.
4298 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
4299 // Determine the array bound is something we can deduce.
4300 if (const NonTypeTemplateParmDecl *NTTP =
4301 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
4302 // We can perform template argument deduction for the given non-type
4303 // template parameter.
4304 // C++ [temp.deduct.type]p13:
4305 // The type of N in the type T[N] is std::size_t.
4307 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
4309 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
4310 /*ArrayBound=*/true, Info, Deduced);
4312 return Result;
4313 }
4314 }
4315
4317}
4318
4319/// Perform template argument deduction per [temp.deduct.call] for a
4320/// single parameter / argument pair.
4322 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4323 QualType ParamType, QualType ArgType,
4324 Expr::Classification ArgClassification, Expr *Arg,
4328 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4329 TemplateSpecCandidateSet *FailedTSC) {
4330
4331 QualType OrigParamType = ParamType;
4332
4333 // If P is a reference type [...]
4334 // If P is a cv-qualified type [...]
4336 S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
4337 ArgClassification, Arg, TDF, FailedTSC))
4339
4340 // If [...] the argument is a non-empty initializer list [...]
4341 if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
4342 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
4343 Deduced, OriginalCallArgs, ArgIdx, TDF);
4344
4345 // [...] the deduction process attempts to find template argument values
4346 // that will make the deduced A identical to A
4347 //
4348 // Keep track of the argument type and corresponding parameter index,
4349 // so we can check for compatibility between the deduced A and A.
4350 if (Arg)
4351 OriginalCallArgs.push_back(
4352 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
4353 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
4354 ArgType, Info, Deduced, TDF);
4355}
4356
4358 FunctionTemplateDecl *FunctionTemplate,
4359 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4361 bool PartialOverloading, bool AggregateDeductionCandidate,
4362 QualType ObjectType, Expr::Classification ObjectClassification,
4363 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
4364 if (FunctionTemplate->isInvalidDecl())
4366
4367 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4368 unsigned NumParams = Function->getNumParams();
4369 bool HasExplicitObject = false;
4370 int ExplicitObjectOffset = 0;
4371 if (Function->hasCXXExplicitFunctionObjectParameter()) {
4372 HasExplicitObject = true;
4373 ExplicitObjectOffset = 1;
4374 }
4375
4376 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
4377
4378 // C++ [temp.deduct.call]p1:
4379 // Template argument deduction is done by comparing each function template
4380 // parameter type (call it P) with the type of the corresponding argument
4381 // of the call (call it A) as described below.
4382 if (Args.size() < Function->getMinRequiredExplicitArguments() &&
4383 !PartialOverloading)
4385 else if (TooManyArguments(NumParams, Args.size() + ExplicitObjectOffset,
4386 PartialOverloading)) {
4387 const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
4388 if (Proto->isTemplateVariadic())
4389 /* Do nothing */;
4390 else if (!Proto->isVariadic())
4392 }
4393
4394 // The types of the parameters from which we will perform template argument
4395 // deduction.
4396 LocalInstantiationScope InstScope(*this);
4397 TemplateParameterList *TemplateParams
4398 = FunctionTemplate->getTemplateParameters();
4400 SmallVector<QualType, 8> ParamTypes;
4401 unsigned NumExplicitlySpecified = 0;
4402 if (ExplicitTemplateArgs) {
4405 Result = SubstituteExplicitTemplateArguments(
4406 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4407 Info);
4408 });
4410 return Result;
4411
4412 NumExplicitlySpecified = Deduced.size();
4413 } else {
4414 // Just fill in the parameter types from the function declaration.
4415 for (unsigned I = 0; I != NumParams; ++I)
4416 ParamTypes.push_back(Function->getParamDecl(I)->getType());
4417 }
4418
4419 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
4420
4421 // Deduce an argument of type ParamType from an expression with index ArgIdx.
4422 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx,
4423 bool ExplicitObjectArgument) {
4424 // C++ [demp.deduct.call]p1: (DR1391)
4425 // Template argument deduction is done by comparing each function template
4426 // parameter that contains template-parameters that participate in
4427 // template argument deduction ...
4428 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4430
4431 if (ExplicitObjectArgument) {
4432 // ... with the type of the corresponding argument
4434 *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
4435 ObjectClassification,
4436 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4437 /*Decomposed*/ false, ArgIdx, /*TDF*/ 0);
4438 }
4439
4440 // ... with the type of the corresponding argument
4442 *this, TemplateParams, FirstInnerIndex, ParamType,
4443 Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()),
4444 Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false,
4445 ArgIdx, /*TDF*/ 0);
4446 };
4447
4448 // Deduce template arguments from the function parameters.
4449 Deduced.resize(TemplateParams->size());
4450 SmallVector<QualType, 8> ParamTypesForArgChecking;
4451 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4452 ParamIdx != NumParamTypes; ++ParamIdx) {
4453 QualType ParamType = ParamTypes[ParamIdx];
4454
4455 const PackExpansionType *ParamExpansion =
4456 dyn_cast<PackExpansionType>(ParamType);
4457 if (!ParamExpansion) {
4458 // Simple case: matching a function parameter to a function argument.
4459 if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0))
4460 break;
4461
4462 ParamTypesForArgChecking.push_back(ParamType);
4463
4464 if (ParamIdx == 0 && HasExplicitObject) {
4465 if (ObjectType.isNull())
4467
4468 if (auto Result = DeduceCallArgument(ParamType, 0,
4469 /*ExplicitObjectArgument=*/true);
4471 return Result;
4472 continue;
4473 }
4474
4475 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4476 /*ExplicitObjectArgument=*/false);
4478 return Result;
4479
4480 continue;
4481 }
4482
4483 bool IsTrailingPack = ParamIdx + 1 == NumParamTypes;
4484
4485 QualType ParamPattern = ParamExpansion->getPattern();
4486 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
4487 ParamPattern,
4488 AggregateDeductionCandidate && IsTrailingPack);
4489
4490 // C++0x [temp.deduct.call]p1:
4491 // For a function parameter pack that occurs at the end of the
4492 // parameter-declaration-list, the type A of each remaining argument of
4493 // the call is compared with the type P of the declarator-id of the
4494 // function parameter pack. Each comparison deduces template arguments
4495 // for subsequent positions in the template parameter packs expanded by
4496 // the function parameter pack. When a function parameter pack appears
4497 // in a non-deduced context [not at the end of the list], the type of
4498 // that parameter pack is never deduced.
4499 //
4500 // FIXME: The above rule allows the size of the parameter pack to change
4501 // after we skip it (in the non-deduced case). That makes no sense, so
4502 // we instead notionally deduce the pack against N arguments, where N is
4503 // the length of the explicitly-specified pack if it's expanded by the
4504 // parameter pack and 0 otherwise, and we treat each deduction as a
4505 // non-deduced context.
4506 if (IsTrailingPack || PackScope.hasFixedArity()) {
4507 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4508 PackScope.nextPackElement(), ++ArgIdx) {
4509 ParamTypesForArgChecking.push_back(ParamPattern);
4510 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4511 /*ExplicitObjectArgument=*/false);
4513 return Result;
4514 }
4515 } else {
4516 // If the parameter type contains an explicitly-specified pack that we
4517 // could not expand, skip the number of parameters notionally created
4518 // by the expansion.
4519 std::optional<unsigned> NumExpansions =
4520 ParamExpansion->getNumExpansions();
4521 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4522 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4523 ++I, ++ArgIdx) {
4524 ParamTypesForArgChecking.push_back(ParamPattern);
4525 // FIXME: Should we add OriginalCallArgs for these? What if the
4526 // corresponding argument is a list?
4527 PackScope.nextPackElement();
4528 }
4529 } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4530 PackScope.isDeducedFromEarlierParameter()) {
4531 // [temp.deduct.general#3]
4532 // When all template arguments have been deduced
4533 // or obtained from default template arguments, all uses of template
4534 // parameters in the template parameter list of the template are
4535 // replaced with the corresponding deduced or default argument values
4536 //
4537 // If we have a trailing parameter pack, that has been deduced
4538 // previously we substitute the pack here in a similar fashion as
4539 // above with the trailing parameter packs. The main difference here is
4540 // that, in this case we are not processing all of the remaining
4541 // arguments. We are only process as many arguments as we have in
4542 // the already deduced parameter.
4543 std::optional<unsigned> ArgPosAfterSubstitution =
4544 PackScope.getSavedPackSizeIfAllEqual();
4545 if (!ArgPosAfterSubstitution)
4546 continue;
4547
4548 unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4549 for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4550 ParamTypesForArgChecking.push_back(ParamPattern);
4551 if (auto Result =
4552 DeduceCallArgument(ParamPattern, ArgIdx,
4553 /*ExplicitObjectArgument=*/false);
4555 return Result;
4556
4557 PackScope.nextPackElement();
4558 }
4559 }
4560 }
4561
4562 // Build argument packs for each of the parameter packs expanded by this
4563 // pack expansion.
4564 if (auto Result = PackScope.finish();
4566 return Result;
4567 }
4568
4569 // Capture the context in which the function call is made. This is the context
4570 // that is needed when the accessibility of template arguments is checked.
4571 DeclContext *CallingCtx = CurContext;
4572
4575 Result = FinishTemplateArgumentDeduction(
4576 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4577 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
4578 ContextRAII SavedContext(*this, CallingCtx);
4579 return CheckNonDependent(ParamTypesForArgChecking);
4580 });
4581 });
4582 return Result;
4583}
4584
4587 bool AdjustExceptionSpec) {
4588 if (ArgFunctionType.isNull())
4589 return ArgFunctionType;
4590
4591 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4592 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4593 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4594 bool Rebuild = false;
4595
4596 CallingConv CC = FunctionTypeP->getCallConv();
4597 if (EPI.ExtInfo.getCC() != CC) {
4598 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4599 Rebuild = true;
4600 }
4601
4602 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4603 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4604 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4605 Rebuild = true;
4606 }
4607
4608 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4609 ArgFunctionTypeP->hasExceptionSpec())) {
4610 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4611 Rebuild = true;
4612 }
4613
4614 if (!Rebuild)
4615 return ArgFunctionType;
4616
4617 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4618 ArgFunctionTypeP->getParamTypes(), EPI);
4619}
4620
4622 FunctionTemplateDecl *FunctionTemplate,
4623 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4625 bool IsAddressOfFunction) {
4626 if (FunctionTemplate->isInvalidDecl())
4628
4629 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4630 TemplateParameterList *TemplateParams
4631 = FunctionTemplate->getTemplateParameters();
4632 QualType FunctionType = Function->getType();
4633
4634 // Substitute any explicit template arguments.
4635 LocalInstantiationScope InstScope(*this);
4637 unsigned NumExplicitlySpecified = 0;
4638 SmallVector<QualType, 4> ParamTypes;
4639 if (ExplicitTemplateArgs) {
4642 Result = SubstituteExplicitTemplateArguments(
4643 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4644 &FunctionType, Info);
4645 });
4647 return Result;
4648
4649 NumExplicitlySpecified = Deduced.size();
4650 }
4651
4652 // When taking the address of a function, we require convertibility of
4653 // the resulting function type. Otherwise, we allow arbitrary mismatches
4654 // of calling convention and noreturn.
4655 if (!IsAddressOfFunction)
4656 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4657 /*AdjustExceptionSpec*/false);
4658
4659 // Unevaluated SFINAE context.
4662 SFINAETrap Trap(*this);
4663
4664 Deduced.resize(TemplateParams->size());
4665
4666 // If the function has a deduced return type, substitute it for a dependent
4667 // type so that we treat it as a non-deduced context in what follows.
4668 bool HasDeducedReturnType = false;
4669 if (getLangOpts().CPlusPlus14 &&
4670 Function->getReturnType()->getContainedAutoType()) {
4672 HasDeducedReturnType = true;
4673 }
4674
4675 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
4676 unsigned TDF =
4678 // Deduce template arguments from the function type.
4680 *this, TemplateParams, FunctionType, ArgFunctionType, Info, Deduced,
4681 TDF);
4683 return Result;
4684 }
4685
4688 Result = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
4689 NumExplicitlySpecified,
4690 Specialization, Info);
4691 });
4693 return Result;
4694
4695 // If the function has a deduced return type, deduce it now, so we can check
4696 // that the deduced function type matches the requested type.
4697 if (HasDeducedReturnType && IsAddressOfFunction &&
4698 Specialization->getReturnType()->isUndeducedType() &&
4701
4702 // [C++26][expr.const]/p17
4703 // An expression or conversion is immediate-escalating if it is not initially
4704 // in an immediate function context and it is [...]
4705 // a potentially-evaluated id-expression that denotes an immediate function.
4706 if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
4707 Specialization->isImmediateEscalating() &&
4708 parentEvaluationContext().isPotentiallyEvaluated() &&
4710 Info.getLocation()))
4712
4713 // Adjust the exception specification of the argument to match the
4714 // substituted and resolved type we just formed. (Calling convention and
4715 // noreturn can't be dependent, so we don't actually need this for them
4716 // right now.)
4717 QualType SpecializationType = Specialization->getType();
4718 if (!IsAddressOfFunction) {
4719 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4720 /*AdjustExceptionSpec*/true);
4721
4722 // Revert placeholder types in the return type back to undeduced types so
4723 // that the comparison below compares the declared return types.
4724 if (HasDeducedReturnType) {
4725 SpecializationType = SubstAutoType(SpecializationType, QualType());
4726 ArgFunctionType = SubstAutoType(ArgFunctionType, QualType());
4727 }
4728 }
4729
4730 // If the requested function type does not match the actual type of the
4731 // specialization with respect to arguments of compatible pointer to function
4732 // types, template argument deduction fails.
4733 if (!ArgFunctionType.isNull()) {
4734 if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
4735 SpecializationType, ArgFunctionType)
4737 SpecializationType, ArgFunctionType)) {
4738 Info.FirstArg = TemplateArgument(SpecializationType);
4739 Info.SecondArg = TemplateArgument(ArgFunctionType);
4741 }
4742 }
4743
4745}
4746
4748 FunctionTemplateDecl *ConversionTemplate, QualType ObjectType,
4749 Expr::Classification ObjectClassification, QualType A,
4751 if (ConversionTemplate->isInvalidDecl())
4753
4754 CXXConversionDecl *ConversionGeneric
4755 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4756
4757 QualType P = ConversionGeneric->getConversionType();
4758 bool IsReferenceP = P->isReferenceType();
4759 bool IsReferenceA = A->isReferenceType();
4760
4761 // C++0x [temp.deduct.conv]p2:
4762 // If P is a reference type, the type referred to by P is used for
4763 // type deduction.
4764 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4765 P = PRef->getPointeeType();
4766
4767 // C++0x [temp.deduct.conv]p4:
4768 // [...] If A is a reference type, the type referred to by A is used
4769 // for type deduction.
4770 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4771 A = ARef->getPointeeType();
4772 // We work around a defect in the standard here: cv-qualifiers are also
4773 // removed from P and A in this case, unless P was a reference type. This
4774 // seems to mostly match what other compilers are doing.
4775 if (!IsReferenceP) {
4776 A = A.getUnqualifiedType();
4777 P = P.getUnqualifiedType();
4778 }
4779
4780 // C++ [temp.deduct.conv]p3:
4781 //
4782 // If A is not a reference type:
4783 } else {
4784 assert(!A->isReferenceType() && "Reference types were handled above");
4785
4786 // - If P is an array type, the pointer type produced by the
4787 // array-to-pointer standard conversion (4.2) is used in place
4788 // of P for type deduction; otherwise,
4789 if (P->isArrayType())
4791 // - If P is a function type, the pointer type produced by the
4792 // function-to-pointer standard conversion (4.3) is used in
4793 // place of P for type deduction; otherwise,
4794 else if (P->isFunctionType())
4796 // - If P is a cv-qualified type, the top level cv-qualifiers of
4797 // P's type are ignored for type deduction.
4798 else
4799 P = P.getUnqualifiedType();
4800
4801 // C++0x [temp.deduct.conv]p4:
4802 // If A is a cv-qualified type, the top level cv-qualifiers of A's
4803 // type are ignored for type deduction. If A is a reference type, the type
4804 // referred to by A is used for type deduction.
4805 A = A.getUnqualifiedType();
4806 }
4807
4808 // Unevaluated SFINAE context.
4811 SFINAETrap Trap(*this);
4812
4813 // C++ [temp.deduct.conv]p1:
4814 // Template argument deduction is done by comparing the return
4815 // type of the template conversion function (call it P) with the
4816 // type that is required as the result of the conversion (call it
4817 // A) as described in 14.8.2.4.
4818 TemplateParameterList *TemplateParams
4819 = ConversionTemplate->getTemplateParameters();
4821 Deduced.resize(TemplateParams->size());
4822
4823 // C++0x [temp.deduct.conv]p4:
4824 // In general, the deduction process attempts to find template
4825 // argument values that will make the deduced A identical to
4826 // A. However, there are two cases that allow a difference:
4827 unsigned TDF = 0;
4828 // - If the original A is a reference type, A can be more
4829 // cv-qualified than the deduced A (i.e., the type referred to
4830 // by the reference)
4831 if (IsReferenceA)
4833 // - The deduced A can be another pointer or pointer to member
4834 // type that can be converted to A via a qualification
4835 // conversion.
4836 //
4837 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4838 // both P and A are pointers or member pointers. In this case, we
4839 // just ignore cv-qualifiers completely).
4840 if ((P->isPointerType() && A->isPointerType()) ||
4841 (P->isMemberPointerType() && A->isMemberPointerType()))
4842 TDF |= TDF_IgnoreQualifiers;
4843
4845 if (ConversionGeneric->isExplicitObjectMemberFunction()) {
4846 QualType ParamType = ConversionGeneric->getParamDecl(0)->getType();
4849 *this, TemplateParams, getFirstInnerIndex(ConversionTemplate),
4850 ParamType, ObjectType, ObjectClassification,
4851 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4852 /*Decomposed*/ false, 0, /*TDF*/ 0);
4854 return Result;
4855 }
4856
4858 *this, TemplateParams, P, A, Info, Deduced, TDF);
4860 return Result;
4861
4862 // Create an Instantiation Scope for finalizing the operator.
4863 LocalInstantiationScope InstScope(*this);
4864 // Finish template argument deduction.
4865 FunctionDecl *ConversionSpecialized = nullptr;
4868 Result = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
4869 ConversionSpecialized, Info,
4870 &OriginalCallArgs);
4871 });
4872 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
4873 return Result;
4874}
4875
4878 TemplateArgumentListInfo *ExplicitTemplateArgs,
4881 bool IsAddressOfFunction) {
4882 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
4883 QualType(), Specialization, Info,
4884 IsAddressOfFunction);
4885}
4886
4887namespace {
4888 struct DependentAuto { bool IsPack; };
4889
4890 /// Substitute the 'auto' specifier or deduced template specialization type
4891 /// specifier within a type for a given replacement type.
4892 class SubstituteDeducedTypeTransform :
4893 public TreeTransform<SubstituteDeducedTypeTransform> {
4894 QualType Replacement;
4895 bool ReplacementIsPack;
4896 bool UseTypeSugar;
4898
4899 public:
4900 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
4901 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4902 ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
4903
4904 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4905 bool UseTypeSugar = true)
4906 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4907 Replacement(Replacement), ReplacementIsPack(false),
4908 UseTypeSugar(UseTypeSugar) {}
4909
4910 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4911 assert(isa<TemplateTypeParmType>(Replacement) &&
4912 "unexpected unsugared replacement kind");
4913 QualType Result = Replacement;
4915 NewTL.setNameLoc(TL.getNameLoc());
4916 return Result;
4917 }
4918
4919 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4920 // If we're building the type pattern to deduce against, don't wrap the
4921 // substituted type in an AutoType. Certain template deduction rules
4922 // apply only when a template type parameter appears directly (and not if
4923 // the parameter is found through desugaring). For instance:
4924 // auto &&lref = lvalue;
4925 // must transform into "rvalue reference to T" not "rvalue reference to
4926 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
4927 //
4928 // FIXME: Is this still necessary?
4929 if (!UseTypeSugar)
4930 return TransformDesugared(TLB, TL);
4931
4932 QualType Result = SemaRef.Context.getAutoType(
4933 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
4934 ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(),
4936 auto NewTL = TLB.push<AutoTypeLoc>(Result);
4937 NewTL.copy(TL);
4938 return Result;
4939 }
4940
4941 QualType TransformDeducedTemplateSpecializationType(
4943 if (!UseTypeSugar)
4944 return TransformDesugared(TLB, TL);
4945
4946 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
4948 Replacement, Replacement.isNull());
4949 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
4950 NewTL.setNameLoc(TL.getNameLoc());
4951 return Result;
4952 }
4953
4954 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4955 // Lambdas never need to be transformed.
4956 return E;
4957 }
4958 bool TransformExceptionSpec(SourceLocation Loc,
4960 SmallVectorImpl<QualType> &Exceptions,
4961 bool &Changed) {
4962 if (ESI.Type == EST_Uninstantiated) {
4963 ESI.instantiate();
4964 Changed = true;
4965 }
4966 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
4967 }
4968
4969 QualType Apply(TypeLoc TL) {
4970 // Create some scratch storage for the transformed type locations.
4971 // FIXME: We're just going to throw this information away. Don't build it.
4972 TypeLocBuilder TLB;
4973 TLB.reserve(TL.getFullDataSize());
4974 return TransformType(TLB, TL);
4975 }
4976 };
4977
4978} // namespace
4979
4982 QualType Deduced) {
4983 ConstraintSatisfaction Satisfaction;
4984 ConceptDecl *Concept = Type.getTypeConstraintConcept();
4985 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
4986 TypeLoc.getRAngleLoc());
4987 TemplateArgs.addArgument(
4990 Deduced, TypeLoc.getNameLoc())));
4991 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
4992 TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
4993
4994 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4995 if (S.CheckTemplateArgumentList(Concept, SourceLocation(), TemplateArgs,
4996 /*PartialTemplateArgs=*/false,
4997 SugaredConverted, CanonicalConverted))
4998 return true;
4999 MultiLevelTemplateArgumentList MLTAL(Concept, CanonicalConverted,
5000 /*Final=*/false);
5001 // Build up an EvaluationContext with an ImplicitConceptSpecializationDecl so
5002 // that the template arguments of the constraint can be preserved. For
5003 // example:
5004 //
5005 // template <class T>
5006 // concept C = []<D U = void>() { return true; }();
5007 //
5008 // We need the argument for T while evaluating type constraint D in
5009 // building the CallExpr to the lambda.
5013 S.getASTContext(), Concept->getDeclContext(), Concept->getLocation(),
5014 CanonicalConverted));
5015 if (S.CheckConstraintSatisfaction(Concept, {Concept->getConstraintExpr()},
5017 Satisfaction))
5018 return true;
5019 if (!Satisfaction.IsSatisfied) {
5020 std::string Buf;
5021 llvm::raw_string_ostream OS(Buf);
5022 OS << "'" << Concept->getName();
5023 if (TypeLoc.hasExplicitTemplateArgs()) {
5025 OS, Type.getTypeConstraintArguments(), S.getPrintingPolicy(),
5026 Type.getTypeConstraintConcept()->getTemplateParameters());
5027 }
5028 OS << "'";
5029 OS.flush();
5030 S.Diag(TypeLoc.getConceptNameLoc(),
5031 diag::err_placeholder_constraints_not_satisfied)
5032 << Deduced << Buf << TypeLoc.getLocalSourceRange();
5033 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
5034 return true;
5035 }
5036 return false;
5037}
5038
5041 TemplateDeductionInfo &Info, bool DependentDeduction,
5042 bool IgnoreConstraints,
5043 TemplateSpecCandidateSet *FailedTSC) {
5044 assert(DependentDeduction || Info.getDeducedDepth() == 0);
5045 if (Init->containsErrors())
5047
5048 const AutoType *AT = Type.getType()->getContainedAutoType();
5049 assert(AT);
5050
5051 if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
5052 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
5053 if (NonPlaceholder.isInvalid())
5055 Init = NonPlaceholder.get();
5056 }
5057
5058 DependentAuto DependentResult = {
5059 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
5060
5061 if (!DependentDeduction &&
5062 (Type.getType()->isDependentType() || Init->isTypeDependent() ||
5063 Init->containsUnexpandedParameterPack())) {
5064 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5065 assert(!Result.isNull() && "substituting DependentTy can't fail");
5067 }
5068
5069 // Make sure that we treat 'char[]' equaly as 'char*' in C23 mode.
5070 auto *String = dyn_cast<StringLiteral>(Init);
5071 if (getLangOpts().C23 && String && Type.getType()->isArrayType()) {
5072 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5073 TypeLoc TL = TypeLoc(Init->getType(), Type.getOpaqueData());
5074 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(TL);
5075 assert(!Result.isNull() && "substituting DependentTy can't fail");
5077 }
5078
5079 // Emit a warning if 'auto*' is used in pedantic and in C23 mode.
5080 if (getLangOpts().C23 && Type.getType()->isPointerType()) {
5081 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5082 }
5083
5084 auto *InitList = dyn_cast<InitListExpr>(Init);
5085 if (!getLangOpts().CPlusPlus && InitList) {
5086 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c)
5087 << (int)AT->getKeyword() << getLangOpts().C23;
5089 }
5090
5091 // Deduce type of TemplParam in Func(Init)
5093 Deduced.resize(1);
5094
5095 // If deduction failed, don't diagnose if the initializer is dependent; it
5096 // might acquire a matching type in the instantiation.
5097 auto DeductionFailed = [&](TemplateDeductionResult TDK) {
5098 if (Init->isTypeDependent()) {
5099 Result =
5100 SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5101 assert(!Result.isNull() && "substituting DependentTy can't fail");
5103 }
5104 return TDK;
5105 };
5106
5107 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
5108
5110 // If this is a 'decltype(auto)' specifier, do the decltype dance.
5111 if (AT->isDecltypeAuto()) {
5112 if (InitList) {
5113 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
5115 }
5116
5118 assert(!DeducedType.isNull());
5119 } else {
5120 LocalInstantiationScope InstScope(*this);
5121
5122 // Build template<class TemplParam> void Func(FuncParam);
5123 SourceLocation Loc = Init->getExprLoc();
5125 Context, nullptr, SourceLocation(), Loc, Info.getDeducedDepth(), 0,
5126 nullptr, false, false, false);
5127 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
5128 NamedDecl *TemplParamPtr = TemplParam;
5130 Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
5131
5132 if (InitList) {
5133 // Notionally, we substitute std::initializer_list<T> for 'auto' and
5134 // deduce against that. Such deduction only succeeds if removing
5135 // cv-qualifiers and references results in std::initializer_list<T>.
5136 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
5138
5139 SourceRange DeducedFromInitRange;
5140 for (Expr *Init : InitList->inits()) {
5141 // Resolving a core issue: a braced-init-list containing any designators
5142 // is a non-deduced context.
5143 if (isa<DesignatedInitExpr>(Init))
5146 *this, TemplateParamsSt.get(), 0, TemplArg, Init->getType(),
5147 Init->Classify(getASTContext()), Init, Info, Deduced,
5148 OriginalCallArgs, /*Decomposed=*/true,
5149 /*ArgIdx=*/0, /*TDF=*/0);
5152 Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction)
5153 << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
5154 << Init->getSourceRange();
5155 return DeductionFailed(TemplateDeductionResult::AlreadyDiagnosed);
5156 }
5157 return DeductionFailed(TDK);
5158 }
5159
5160 if (DeducedFromInitRange.isInvalid() &&
5161 Deduced[0].getKind() != TemplateArgument::Null)
5162 DeducedFromInitRange = Init->getSourceRange();
5163 }
5164 } else {
5165 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
5166 Diag(Loc, diag::err_auto_bitfield);
5168 }
5169 QualType FuncParam =
5170 SubstituteDeducedTypeTransform(*this, TemplArg).Apply(Type);
5171 assert(!FuncParam.isNull() &&
5172 "substituting template parameter for 'auto' failed");
5174 *this, TemplateParamsSt.get(), 0, FuncParam, Init->getType(),
5175 Init->Classify(getASTContext()), Init, Info, Deduced,
5176 OriginalCallArgs, /*Decomposed=*/false, /*ArgIdx=*/0, /*TDF=*/0,
5177 FailedTSC);
5179 return DeductionFailed(TDK);
5180 }
5181
5182 // Could be null if somehow 'auto' appears in a non-deduced context.
5183 if (Deduced[0].getKind() != TemplateArgument::Type)
5184 return DeductionFailed(TemplateDeductionResult::Incomplete);
5185 DeducedType = Deduced[0].getAsType();
5186
5187 if (InitList) {
5189 if (DeducedType.isNull())
5191 }
5192 }
5193
5194 if (!Result.isNull()) {
5196 Info.FirstArg = Result;
5197 Info.SecondArg = DeducedType;
5198 return DeductionFailed(TemplateDeductionResult::Inconsistent);
5199 }
5201 }
5202
5203 if (AT->isConstrained() && !IgnoreConstraints &&
5205 *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType))
5207
5208 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
5209 if (Result.isNull())
5211
5212 // Check that the deduced argument type is compatible with the original
5213 // argument type per C++ [temp.deduct.call]p4.
5214 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
5215 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
5216 assert((bool)InitList == OriginalArg.DecomposedParam &&
5217 "decomposed non-init-list in auto deduction?");
5218 if (auto TDK =
5219 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
5221 Result = QualType();
5222 return DeductionFailed(TDK);
5223 }
5224 }
5225
5227}
5228
5230 QualType TypeToReplaceAuto) {
5231 assert(TypeToReplaceAuto != Context.DependentTy);
5232 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5233 .TransformType(TypeWithAuto);
5234}
5235
5237 QualType TypeToReplaceAuto) {
5238 assert(TypeToReplaceAuto != Context.DependentTy);
5239 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5240 .TransformType(TypeWithAuto);
5241}
5242
5244 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5245 .TransformType(TypeWithAuto);
5246}
5247
5250 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5251 .TransformType(TypeWithAuto);
5252}
5253
5255 QualType TypeToReplaceAuto) {
5256 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5257 /*UseTypeSugar*/ false)
5258 .TransformType(TypeWithAuto);
5259}
5260
5262 QualType TypeToReplaceAuto) {
5263 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5264 /*UseTypeSugar*/ false)
5265 .TransformType(TypeWithAuto);
5266}
5267
5269 const Expr *Init) {
5270 if (isa<InitListExpr>(Init))
5271 Diag(VDecl->getLocation(),
5272 VDecl->isInitCapture()
5273 ? diag::err_init_capture_deduction_failure_from_init_list
5274 : diag::err_auto_var_deduction_failure_from_init_list)
5275 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
5276 else
5277 Diag(VDecl->getLocation(),
5278 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
5279 : diag::err_auto_var_deduction_failure)
5280 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5281 << Init->getSourceRange();
5282}
5283
5285 bool Diagnose) {
5286 assert(FD->getReturnType()->isUndeducedType());
5287
5288 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
5289 // within the return type from the call operator's type.
5291 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5292 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5293
5294 // For a generic lambda, instantiate the call operator if needed.
5295 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5297 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5298 if (!CallOp || CallOp->isInvalidDecl())
5299 return true;
5300
5301 // We might need to deduce the return type by instantiating the definition
5302 // of the operator() function.
5303 if (CallOp->getReturnType()->isUndeducedType()) {
5306 });
5307 }
5308 }
5309
5310 if (CallOp->isInvalidDecl())
5311 return true;
5312 assert(!CallOp->getReturnType()->isUndeducedType() &&
5313 "failed to deduce lambda return type");
5314
5315 // Build the new return type from scratch.
5316 CallingConv RetTyCC = FD->getReturnType()
5317 ->getPointeeType()
5318 ->castAs<FunctionType>()
5319 ->getCallConv();
5321 CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
5322 if (FD->getReturnType()->getAs<PointerType>())
5323 RetType = Context.getPointerType(RetType);
5324 else {
5325 assert(FD->getReturnType()->getAs<BlockPointerType>());
5326 RetType = Context.getBlockPointerType(RetType);
5327 }
5329 return false;
5330 }
5331
5335 });
5336 }
5337
5338 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
5339 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
5340 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
5341 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
5342 }
5343
5344 return StillUndeduced;
5345}
5346
5349 assert(FD->isImmediateEscalating());
5350
5352 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5353 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5354
5355 // For a generic lambda, instantiate the call operator if needed.
5356 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5358 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5359 if (!CallOp || CallOp->isInvalidDecl())
5360 return true;
5362 Loc, [&] { InstantiateFunctionDefinition(Loc, CallOp); });
5363 }
5364 return CallOp->isInvalidDecl();
5365 }
5366
5369 Loc, [&] { InstantiateFunctionDefinition(Loc, FD); });
5370 }
5371 return false;
5372}
5373
5375 const CXXMethodDecl *Method,
5376 QualType RawType,
5377 bool IsOtherRvr) {
5378 // C++20 [temp.func.order]p3.1, p3.2:
5379 // - The type X(M) is "rvalue reference to cv A" if the optional
5380 // ref-qualifier of M is && or if M has no ref-qualifier and the
5381 // positionally-corresponding parameter of the other transformed template
5382 // has rvalue reference type; if this determination depends recursively
5383 // upon whether X(M) is an rvalue reference type, it is not considered to
5384 // have rvalue reference type.
5385 //
5386 // - Otherwise, X(M) is "lvalue reference to cv A".
5387 assert(Method && !Method->isExplicitObjectMemberFunction() &&
5388 "expected a member function with no explicit object parameter");
5389
5390 RawType = Context.getQualifiedType(RawType, Method->getMethodQualifiers());
5391 if (Method->getRefQualifier() == RQ_RValue ||
5392 (IsOtherRvr && Method->getRefQualifier() == RQ_None))
5393 return Context.getRValueReferenceType(RawType);
5394 return Context.getLValueReferenceType(RawType);
5395}
5396
5397/// Determine whether the function template \p FT1 is at least as
5398/// specialized as \p FT2.
5400 const FunctionTemplateDecl *FT1,
5401 const FunctionTemplateDecl *FT2,
5403 bool Reversed,
5404 const SmallVector<QualType> &Args1,
5405 const SmallVector<QualType> &Args2) {
5406 assert(!Reversed || TPOC == TPOC_Call);
5407
5408 FunctionDecl *FD1 = FT1->getTemplatedDecl();
5409 FunctionDecl *FD2 = FT2->getTemplatedDecl();
5410 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
5411 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
5412
5413 assert(Proto1 && Proto2 && "Function templates must have prototypes");
5414 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
5416 Deduced.resize(TemplateParams->size());
5417
5418 // C++0x [temp.deduct.partial]p3:
5419 // The types used to determine the ordering depend on the context in which
5420 // the partial ordering is done:
5422 switch (TPOC) {
5423 case TPOC_Call:
5424 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
5425 Args1.data(), Args1.size(), Info, Deduced,
5426 TDF_None, /*PartialOrdering=*/true) !=
5428 return false;
5429
5430 break;
5431
5432 case TPOC_Conversion:
5433 // - In the context of a call to a conversion operator, the return types
5434 // of the conversion function templates are used.
5436 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
5437 Info, Deduced, TDF_None,
5438 /*PartialOrdering=*/true) != TemplateDeductionResult::Success)
5439 return false;
5440 break;
5441
5442 case TPOC_Other:
5443 // - In other contexts (14.6.6.2) the function template's function type
5444 // is used.
5446 S, TemplateParams, FD2->getType(), FD1->getType(), Info, Deduced,
5448 /*PartialOrdering=*/true) != TemplateDeductionResult::Success)
5449 return false;
5450 break;
5451 }
5452
5453 // C++0x [temp.deduct.partial]p11:
5454 // In most cases, all template parameters must have values in order for
5455 // deduction to succeed, but for partial ordering purposes a template
5456 // parameter may remain without a value provided it is not used in the
5457 // types being used for partial ordering. [ Note: a template parameter used
5458 // in a non-deduced context is considered used. -end note]
5459 unsigned ArgIdx = 0, NumArgs = Deduced.size();
5460 for (; ArgIdx != NumArgs; ++ArgIdx)
5461 if (Deduced[ArgIdx].isNull())
5462 break;
5463
5464 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
5465 // to substitute the deduced arguments back into the template and check that
5466 // we get the right type.
5467
5468 if (ArgIdx == NumArgs) {
5469 // All template arguments were deduced. FT1 is at least as specialized
5470 // as FT2.
5471 return true;
5472 }
5473
5474 // Figure out which template parameters were used.
5475 llvm::SmallBitVector UsedParameters(TemplateParams->size());
5476 switch (TPOC) {
5477 case TPOC_Call:
5478 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
5479 ::MarkUsedTemplateParameters(S.Context, Args2[I], /*OnlyDeduced=*/false,
5480 TemplateParams->getDepth(), UsedParameters);
5481 break;
5482
5483 case TPOC_Conversion:
5484 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(),
5485 /*OnlyDeduced=*/false,
5486 TemplateParams->getDepth(), UsedParameters);
5487 break;
5488
5489 case TPOC_Other:
5490 // We do not deduce template arguments from the exception specification
5491 // when determining the primary template of a function template
5492 // specialization or when taking the address of a function template.
5493 // Therefore, we do not mark template parameters in the exception
5494 // specification as used during partial ordering to prevent the following
5495 // from being ambiguous:
5496 //
5497 // template<typename T, typename U>
5498 // void f(U) noexcept(noexcept(T())); // #1
5499 //
5500 // template<typename T>
5501 // void f(T*) noexcept; // #2
5502 //
5503 // template<>
5504 // void f<int>(int*) noexcept; // explicit specialization of #2
5505 //
5506 // Although there is no corresponding wording in the standard, this seems
5507 // to be the intended behavior given the definition of
5508 // 'deduction substitution loci' in [temp.deduct].
5510 S.Context,
5512 /*OnlyDeduced=*/false, TemplateParams->getDepth(), UsedParameters);
5513 break;
5514 }
5515
5516 for (; ArgIdx != NumArgs; ++ArgIdx)
5517 // If this argument had no value deduced but was used in one of the types
5518 // used for partial ordering, then deduction fails.
5519 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
5520 return false;
5521
5522 return true;
5523}
5524
5527 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
5528 QualType RawObj1Ty, QualType RawObj2Ty, bool Reversed) {
5531 const FunctionDecl *FD1 = FT1->getTemplatedDecl();
5532 const FunctionDecl *FD2 = FT2->getTemplatedDecl();
5533 bool ShouldConvert1 = false;
5534 bool ShouldConvert2 = false;
5535 QualType Obj1Ty;
5536 QualType Obj2Ty;
5537 if (TPOC == TPOC_Call) {
5538 const FunctionProtoType *Proto1 =
5539 FD1->getType()->castAs<FunctionProtoType>();
5540 const FunctionProtoType *Proto2 =
5541 FD2->getType()->castAs<FunctionProtoType>();
5542
5543 // - In the context of a function call, the function parameter types are
5544 // used.
5545 const CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
5546 const CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
5547 // C++20 [temp.func.order]p3
5548 // [...] Each function template M that is a member function is
5549 // considered to have a new first parameter of type
5550 // X(M), described below, inserted in its function parameter list.
5551 //
5552 // Note that we interpret "that is a member function" as
5553 // "that is a member function with no expicit object argument".
5554 // Otherwise the ordering rules for methods with expicit objet arguments
5555 // against anything else make no sense.
5556 ShouldConvert1 = Method1 && !Method1->isExplicitObjectMemberFunction();
5557 ShouldConvert2 = Method2 && !Method2->isExplicitObjectMemberFunction();
5558 if (ShouldConvert1) {
5559 bool IsRValRef2 =
5560 ShouldConvert2
5561 ? Method2->getRefQualifier() == RQ_RValue
5562 : Proto2->param_type_begin()[0]->isRValueReferenceType();
5563 // Compare 'this' from Method1 against first parameter from Method2.
5564 Obj1Ty = GetImplicitObjectParameterType(this->Context, Method1, RawObj1Ty,
5565 IsRValRef2);
5566 Args1.push_back(Obj1Ty);
5567 }
5568 if (ShouldConvert2) {
5569 bool IsRValRef1 =
5570 ShouldConvert1
5571 ? Method1->getRefQualifier() == RQ_RValue
5572 : Proto1->param_type_begin()[0]->isRValueReferenceType();
5573 // Compare 'this' from Method2 against first parameter from Method1.
5574 Obj2Ty = GetImplicitObjectParameterType(this->Context, Method2, RawObj2Ty,
5575 IsRValRef1);
5576 Args2.push_back(Obj2Ty);
5577 }
5578 size_t NumComparedArguments = NumCallArguments1;
5579 // Either added an argument above or the prototype includes an explicit
5580 // object argument we need to count
5581 if (Method1)
5582 ++NumComparedArguments;
5583
5584 Args1.insert(Args1.end(), Proto1->param_type_begin(),
5585 Proto1->param_type_end());
5586 Args2.insert(Args2.end(), Proto2->param_type_begin(),
5587 Proto2->param_type_end());
5588
5589 // C++ [temp.func.order]p5:
5590 // The presence of unused ellipsis and default arguments has no effect on
5591 // the partial ordering of function templates.
5592 Args1.resize(std::min(Args1.size(), NumComparedArguments));
5593 Args2.resize(std::min(Args2.size(), NumComparedArguments));
5594
5595 if (Reversed)
5596 std::reverse(Args2.begin(), Args2.end());
5597 }
5598 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, Reversed,
5599 Args1, Args2);
5600 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, Reversed,
5601 Args2, Args1);
5602 // C++ [temp.deduct.partial]p10:
5603 // F is more specialized than G if F is at least as specialized as G and G
5604 // is not at least as specialized as F.
5605 if (Better1 != Better2) // We have a clear winner
5606 return Better1 ? FT1 : FT2;
5607
5608 if (!Better1 && !Better2) // Neither is better than the other
5609 return nullptr;
5610
5611 // C++ [temp.deduct.partial]p11:
5612 // ... and if G has a trailing function parameter pack for which F does not
5613 // have a corresponding parameter, and if F does not have a trailing
5614 // function parameter pack, then F is more specialized than G.
5615
5616 SmallVector<QualType> Param1;
5617 Param1.reserve(FD1->param_size() + ShouldConvert1);
5618 if (ShouldConvert1)
5619 Param1.push_back(Obj1Ty);
5620 for (const auto &P : FD1->parameters())
5621 Param1.push_back(P->getType());
5622
5623 SmallVector<QualType> Param2;
5624 Param2.reserve(FD2->param_size() + ShouldConvert2);
5625 if (ShouldConvert2)
5626 Param2.push_back(Obj2Ty);
5627 for (const auto &P : FD2->parameters())
5628 Param2.push_back(P->getType());
5629
5630 unsigned NumParams1 = Param1.size();
5631 unsigned NumParams2 = Param2.size();
5632
5633 bool Variadic1 =
5634 FD1->param_size() && FD1->parameters().back()->isParameterPack();
5635 bool Variadic2 =
5636 FD2->param_size() && FD2->parameters().back()->isParameterPack();
5637 if (Variadic1 != Variadic2) {
5638 if (Variadic1 && NumParams1 > NumParams2)
5639 return FT2;
5640 if (Variadic2 && NumParams2 > NumParams1)
5641 return FT1;
5642 }
5643
5644 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
5645 // there is no wording or even resolution for this issue.
5646 for (int i = 0, e = std::min(NumParams1, NumParams2); i < e; ++i) {
5647 QualType T1 = Param1[i].getCanonicalType();
5648 QualType T2 = Param2[i].getCanonicalType();
5649 auto *TST1 = dyn_cast<TemplateSpecializationType>(T1);
5650 auto *TST2 = dyn_cast<TemplateSpecializationType>(T2);
5651 if (!TST1 || !TST2)
5652 continue;
5653 const TemplateArgument &TA1 = TST1->template_arguments().back();
5654 if (TA1.getKind() == TemplateArgument::Pack) {
5655 assert(TST1->template_arguments().size() ==
5656 TST2->template_arguments().size());
5657 const TemplateArgument &TA2 = TST2->template_arguments().back();
5658 assert(TA2.getKind() == TemplateArgument::Pack);
5659 unsigned PackSize1 = TA1.pack_size();
5660 unsigned PackSize2 = TA2.pack_size();
5661 bool IsPackExpansion1 =
5662 PackSize1 && TA1.pack_elements().back().isPackExpansion();
5663 bool IsPackExpansion2 =
5664 PackSize2 && TA2.pack_elements().back().isPackExpansion();
5665 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
5666 if (PackSize1 > PackSize2 && IsPackExpansion1)
5667 return FT2;
5668 if (PackSize1 < PackSize2 && IsPackExpansion2)
5669 return FT1;
5670 }
5671 }
5672 }
5673
5674 if (!Context.getLangOpts().CPlusPlus20)
5675 return nullptr;
5676
5677 // Match GCC on not implementing [temp.func.order]p6.2.1.
5678
5679 // C++20 [temp.func.order]p6:
5680 // If deduction against the other template succeeds for both transformed
5681 // templates, constraints can be considered as follows:
5682
5683 // C++20 [temp.func.order]p6.1:
5684 // If their template-parameter-lists (possibly including template-parameters
5685 // invented for an abbreviated function template ([dcl.fct])) or function
5686 // parameter lists differ in length, neither template is more specialized
5687 // than the other.
5690 if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
5691 return nullptr;
5692
5693 // C++20 [temp.func.order]p6.2.2:
5694 // Otherwise, if the corresponding template-parameters of the
5695 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
5696 // function parameters that positionally correspond between the two
5697 // templates are not of the same type, neither template is more specialized
5698 // than the other.
5699 if (!TemplateParameterListsAreEqual(TPL1, TPL2, false,
5701 return nullptr;
5702
5703 // [dcl.fct]p5:
5704 // Any top-level cv-qualifiers modifying a parameter type are deleted when
5705 // forming the function type.
5706 for (unsigned i = 0; i < NumParams1; ++i)
5707 if (!Context.hasSameUnqualifiedType(Param1[i], Param2[i]))
5708 return nullptr;
5709
5710 // C++20 [temp.func.order]p6.3:
5711 // Otherwise, if the context in which the partial ordering is done is
5712 // that of a call to a conversion function and the return types of the
5713 // templates are not the same, then neither template is more specialized
5714 // than the other.
5715 if (TPOC == TPOC_Conversion &&
5717 return nullptr;
5718
5720 FT1->getAssociatedConstraints(AC1);
5721 FT2->getAssociatedConstraints(AC2);
5722 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
5723 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
5724 return nullptr;
5725 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
5726 return nullptr;
5727 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
5728 return nullptr;
5729 return AtLeastAsConstrained1 ? FT1 : FT2;
5730}
5731
5734 TemplateSpecCandidateSet &FailedCandidates,
5735 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
5736 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
5737 bool Complain, QualType TargetType) {
5738 if (SpecBegin == SpecEnd) {
5739 if (Complain) {
5740 Diag(Loc, NoneDiag);
5741 FailedCandidates.NoteCandidates(*this, Loc);
5742 }
5743 return SpecEnd;
5744 }
5745
5746 if (SpecBegin + 1 == SpecEnd)
5747 return SpecBegin;
5748
5749 // Find the function template that is better than all of the templates it
5750 // has been compared to.
5751 UnresolvedSetIterator Best = SpecBegin;
5752 FunctionTemplateDecl *BestTemplate
5753 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
5754 assert(BestTemplate && "Not a function template specialization?");
5755 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
5756 FunctionTemplateDecl *Challenger
5757 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
5758 assert(Challenger && "Not a function template specialization?");
5759 if (declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
5760 Loc, TPOC_Other, 0),
5761 Challenger)) {
5762 Best = I;
5763 BestTemplate = Challenger;
5764 }
5765 }
5766
5767 // Make sure that the "best" function template is more specialized than all
5768 // of the others.
5769 bool Ambiguous = false;
5770 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
5771 FunctionTemplateDecl *Challenger
5772 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
5773 if (I != Best &&
5774 !declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
5775 Loc, TPOC_Other, 0),
5776 BestTemplate)) {
5777 Ambiguous = true;
5778 break;
5779 }
5780 }
5781
5782 if (!Ambiguous) {
5783 // We found an answer. Return it.
5784 return Best;
5785 }
5786
5787 // Diagnose the ambiguity.
5788 if (Complain) {
5789 Diag(Loc, AmbigDiag);
5790
5791 // FIXME: Can we order the candidates in some sane way?
5792 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
5793 PartialDiagnostic PD = CandidateDiag;
5794 const auto *FD = cast<FunctionDecl>(*I);
5796 FD->getPrimaryTemplate()->getTemplateParameters(),
5797 *FD->getTemplateSpecializationArgs());
5798 if (!TargetType.isNull())
5799 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
5800 Diag((*I)->getLocation(), PD);
5801 }
5802 }
5803
5804 return SpecEnd;
5805}
5806
5808 FunctionDecl *FD2) {
5809 assert(!FD1->getDescribedTemplate() && !FD2->getDescribedTemplate() &&
5810 "not for function templates");
5811 assert(!FD1->isFunctionTemplateSpecialization() ||
5812 isa<CXXConversionDecl>(FD1));
5813 assert(!FD2->isFunctionTemplateSpecialization() ||
5814 isa<CXXConversionDecl>(FD2));
5815
5816 FunctionDecl *F1 = FD1;
5818 F1 = P;
5819
5820 FunctionDecl *F2 = FD2;
5822 F2 = P;
5823
5825 F1->getAssociatedConstraints(AC1);
5826 F2->getAssociatedConstraints(AC2);
5827 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
5828 if (IsAtLeastAsConstrained(F1, AC1, F2, AC2, AtLeastAsConstrained1))
5829 return nullptr;
5830 if (IsAtLeastAsConstrained(F2, AC2, F1, AC1, AtLeastAsConstrained2))
5831 return nullptr;
5832 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
5833 return nullptr;
5834 return AtLeastAsConstrained1 ? FD1 : FD2;
5835}
5836
5837/// Determine whether one partial specialization, P1, is at least as
5838/// specialized than another, P2.
5839///
5840/// \tparam TemplateLikeDecl The kind of P2, which must be a
5841/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
5842/// \param T1 The injected-class-name of P1 (faked for a variable template).
5843/// \param T2 The injected-class-name of P2 (faked for a variable template).
5844template<typename TemplateLikeDecl>
5846 TemplateLikeDecl *P2,
5847 TemplateDeductionInfo &Info) {
5848 // C++ [temp.class.order]p1:
5849 // For two class template partial specializations, the first is at least as
5850 // specialized as the second if, given the following rewrite to two
5851 // function templates, the first function template is at least as
5852 // specialized as the second according to the ordering rules for function
5853 // templates (14.6.6.2):
5854 // - the first function template has the same template parameters as the
5855 // first partial specialization and has a single function parameter
5856 // whose type is a class template specialization with the template
5857 // arguments of the first partial specialization, and
5858 // - the second function template has the same template parameters as the
5859 // second partial specialization and has a single function parameter
5860 // whose type is a class template specialization with the template
5861 // arguments of the second partial specialization.
5862 //
5863 // Rather than synthesize function templates, we merely perform the
5864 // equivalent partial ordering by performing deduction directly on
5865 // the template arguments of the class template partial
5866 // specializations. This computation is slightly simpler than the
5867 // general problem of function template partial ordering, because
5868 // class template partial specializations are more constrained. We
5869 // know that every template parameter is deducible from the class
5870 // template partial specialization's template arguments, for
5871 // example.
5873
5874 // Determine whether P1 is at least as specialized as P2.
5875 Deduced.resize(P2->getTemplateParameters()->size());
5877 S, P2->getTemplateParameters(), T2, T1, Info, Deduced, TDF_None,
5878 /*PartialOrdering=*/true) != TemplateDeductionResult::Success)
5879 return false;
5880
5881 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
5882 Deduced.end());
5883 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
5884 Info);
5885 if (Inst.isInvalid())
5886 return false;
5887
5888 const auto *TST1 = cast<TemplateSpecializationType>(T1);
5889 bool AtLeastAsSpecialized;
5891 AtLeastAsSpecialized =
5892 FinishTemplateArgumentDeduction(
5893 S, P2, /*IsPartialOrdering=*/true, TST1->template_arguments(),
5894 Deduced, Info) == TemplateDeductionResult::Success;
5895 });
5896 return AtLeastAsSpecialized;
5897}
5898
5899namespace {
5900// A dummy class to return nullptr instead of P2 when performing "more
5901// specialized than primary" check.
5902struct GetP2 {
5903 template <typename T1, typename T2,
5904 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
5905 T2 *operator()(T1 *, T2 *P2) {
5906 return P2;
5907 }
5908 template <typename T1, typename T2,
5909 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
5910 T1 *operator()(T1 *, T2 *) {
5911 return nullptr;
5912 }
5913};
5914
5915// The assumption is that two template argument lists have the same size.
5916struct TemplateArgumentListAreEqual {
5917 ASTContext &Ctx;
5918 TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
5919
5920 template <typename T1, typename T2,
5921 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
5922 bool operator()(T1 *PS1, T2 *PS2) {
5923 ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
5924 Args2 = PS2->getTemplateArgs().asArray();
5925
5926 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
5927 // We use profile, instead of structural comparison of the arguments,
5928 // because canonicalization can't do the right thing for dependent
5929 // expressions.
5930 llvm::FoldingSetNodeID IDA, IDB;
5931 Args1[I].Profile(IDA, Ctx);
5932 Args2[I].Profile(IDB, Ctx);
5933 if (IDA != IDB)
5934 return false;
5935 }
5936 return true;
5937 }
5938
5939 template <typename T1, typename T2,
5940 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
5941 bool operator()(T1 *Spec, T2 *Primary) {
5942 ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
5943 Args2 = Primary->getInjectedTemplateArgs();
5944
5945 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
5946 // We use profile, instead of structural comparison of the arguments,
5947 // because canonicalization can't do the right thing for dependent
5948 // expressions.
5949 llvm::FoldingSetNodeID IDA, IDB;
5950 Args1[I].Profile(IDA, Ctx);
5951 // Unlike the specialization arguments, the injected arguments are not
5952 // always canonical.
5953 Ctx.getCanonicalTemplateArgument(Args2[I]).Profile(IDB, Ctx);
5954 if (IDA != IDB)
5955 return false;
5956 }
5957 return true;
5958 }
5959};
5960} // namespace
5961
5962/// Returns the more specialized template specialization between T1/P1 and
5963/// T2/P2.
5964/// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
5965/// specialization and T2/P2 is the primary template.
5966/// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
5967///
5968/// \param T1 the type of the first template partial specialization
5969///
5970/// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
5971/// template partial specialization; otherwise, the type of the
5972/// primary template.
5973///
5974/// \param P1 the first template partial specialization
5975///
5976/// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
5977/// partial specialization; otherwise, the primary template.
5978///
5979/// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
5980/// more specialized, returns nullptr if P1 is not more specialized.
5981/// - otherwise, returns the more specialized template partial
5982/// specialization. If neither partial specialization is more
5983/// specialized, returns NULL.
5984template <typename TemplateLikeDecl, typename PrimaryDel>
5985static TemplateLikeDecl *
5986getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
5987 PrimaryDel *P2, TemplateDeductionInfo &Info) {
5988 constexpr bool IsMoreSpecialThanPrimaryCheck =
5989 !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
5990
5991 bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, Info);
5992 if (IsMoreSpecialThanPrimaryCheck && !Better1)
5993 return nullptr;
5994
5995 bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1, Info);
5996 if (IsMoreSpecialThanPrimaryCheck && !Better2)
5997 return P1;
5998
5999 // C++ [temp.deduct.partial]p10:
6000 // F is more specialized than G if F is at least as specialized as G and G
6001 // is not at least as specialized as F.
6002 if (Better1 != Better2) // We have a clear winner
6003 return Better1 ? P1 : GetP2()(P1, P2);
6004
6005 if (!Better1 && !Better2)
6006 return nullptr;
6007
6008 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
6009 // there is no wording or even resolution for this issue.
6010 auto *TST1 = cast<TemplateSpecializationType>(T1);
6011 auto *TST2 = cast<TemplateSpecializationType>(T2);
6012 const TemplateArgument &TA1 = TST1->template_arguments().back();
6013 if (TA1.getKind() == TemplateArgument::Pack) {
6014 assert(TST1->template_arguments().size() ==
6015 TST2->template_arguments().size());
6016 const TemplateArgument &TA2 = TST2->template_arguments().back();
6017 assert(TA2.getKind() == TemplateArgument::Pack);
6018 unsigned PackSize1 = TA1.pack_size();
6019 unsigned PackSize2 = TA2.pack_size();
6020 bool IsPackExpansion1 =
6021 PackSize1 && TA1.pack_elements().back().isPackExpansion();
6022 bool IsPackExpansion2 =
6023 PackSize2 && TA2.pack_elements().back().isPackExpansion();
6024 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
6025 if (PackSize1 > PackSize2 && IsPackExpansion1)
6026 return GetP2()(P1, P2);
6027 if (PackSize1 < PackSize2 && IsPackExpansion2)
6028 return P1;
6029 }
6030 }
6031
6032 if (!S.Context.getLangOpts().CPlusPlus20)
6033 return nullptr;
6034
6035 // Match GCC on not implementing [temp.func.order]p6.2.1.
6036
6037 // C++20 [temp.func.order]p6:
6038 // If deduction against the other template succeeds for both transformed
6039 // templates, constraints can be considered as follows:
6040
6041 TemplateParameterList *TPL1 = P1->getTemplateParameters();
6042 TemplateParameterList *TPL2 = P2->getTemplateParameters();
6043 if (TPL1->size() != TPL2->size())
6044 return nullptr;
6045
6046 // C++20 [temp.func.order]p6.2.2:
6047 // Otherwise, if the corresponding template-parameters of the
6048 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6049 // function parameters that positionally correspond between the two
6050 // templates are not of the same type, neither template is more specialized
6051 // than the other.
6052 if (!S.TemplateParameterListsAreEqual(TPL1, TPL2, false,
6054 return nullptr;
6055
6056 if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
6057 return nullptr;
6058
6060 P1->getAssociatedConstraints(AC1);
6061 P2->getAssociatedConstraints(AC2);
6062 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6063 if (S.IsAtLeastAsConstrained(P1, AC1, P2, AC2, AtLeastAsConstrained1) ||
6064 (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
6065 return nullptr;
6066 if (S.IsAtLeastAsConstrained(P2, AC2, P1, AC1, AtLeastAsConstrained2))
6067 return nullptr;
6068 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6069 return nullptr;
6070 return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
6071}
6072
6080
6082 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6083}
6084
6087 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
6088 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
6089 QualType PartialT = Spec->getInjectedSpecializationType();
6090
6092 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6093 if (MaybeSpec)
6094 Info.clearSFINAEDiagnostic();
6095 return MaybeSpec;
6096}
6097
6102 // Pretend the variable template specializations are class template
6103 // specializations and form a fake injected class name type for comparison.
6104 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
6105 "the partial specializations being compared should specialize"
6106 " the same template.");
6109 Name, PS1->getTemplateArgs().asArray());
6111 Name, PS2->getTemplateArgs().asArray());
6112
6114 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6115}
6116
6119 VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
6120 TemplateName Name(Primary);
6122 Name, Primary->getInjectedTemplateArgs());
6124 Name, Spec->getTemplateArgs().asArray());
6125
6127 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6128 if (MaybeSpec)
6129 Info.clearSFINAEDiagnostic();
6130 return MaybeSpec;
6131}
6132
6135 bool IsDeduced) {
6136 // C++1z [temp.arg.template]p4: (DR 150)
6137 // A template template-parameter P is at least as specialized as a
6138 // template template-argument A if, given the following rewrite to two
6139 // function templates...
6140
6141 // Rather than synthesize function templates, we merely perform the
6142 // equivalent partial ordering by performing deduction directly on
6143 // the template parameter lists of the template template parameters.
6144 //
6146
6147 // Given an invented class template X with the template parameter list of
6148 // A (including default arguments):
6149 // - Each function template has a single function parameter whose type is
6150 // a specialization of X with template arguments corresponding to the
6151 // template parameters from the respective function template
6154
6155 // Check P's arguments against A's parameter list. This will fill in default
6156 // template arguments as needed. AArgs are already correct by construction.
6157 // We can't just use CheckTemplateIdType because that will expand alias
6158 // templates.
6160 {
6161 SFINAETrap Trap(*this);
6162
6164 TemplateArgumentListInfo PArgList(P->getLAngleLoc(),
6165 P->getRAngleLoc());
6166 for (unsigned I = 0, N = P->size(); I != N; ++I) {
6167 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
6168 // expansions, to form an "as written" argument list.
6169 TemplateArgument Arg = PArgs[I];
6170 if (Arg.getKind() == TemplateArgument::Pack) {
6171 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
6172 Arg = *Arg.pack_begin();
6173 }
6175 Arg, QualType(), P->getParam(I)->getLocation()));
6176 }
6177 PArgs.clear();
6178
6179 // C++1z [temp.arg.template]p3:
6180 // If the rewrite produces an invalid type, then P is not at least as
6181 // specialized as A.
6183 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, SugaredPArgs,
6184 PArgs, /*UpdateArgsWithConversions=*/true,
6185 /*ConstraintsNotSatisfied=*/nullptr,
6186 /*PartialOrderTTP=*/true) ||
6187 Trap.hasErrorOccurred())
6188 return false;
6189 }
6190
6191 // Determine whether P1 is at least as specialized as P2.
6194 Deduced.resize(A->size());
6195
6196 // ... the function template corresponding to P is at least as specialized
6197 // as the function template corresponding to A according to the partial
6198 // ordering rules for function templates.
6199
6200 // Provisional resolution for CWG2398: Regarding temp.arg.template]p4, when
6201 // applying the partial ordering rules for function templates on
6202 // the rewritten template template parameters:
6203 // - In a deduced context, the matching of packs versus fixed-size needs to
6204 // be inverted between Ps and As. On non-deduced context, matching needs to
6205 // happen both ways, according to [temp.arg.template]p3, but this is
6206 // currently implemented as a special case elsewhere.
6207 if (::DeduceTemplateArguments(*this, A, AArgs, PArgs, Info, Deduced,
6208 /*NumberOfArgumentsMustMatch=*/false,
6209 IsDeduced ? PackFold::ArgumentToParameter
6210 : PackFold::ParameterToArgument) !=
6212 return false;
6213
6214 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
6215 Sema::InstantiatingTemplate Inst(*this, Info.getLocation(), AArg, DeducedArgs,
6216 Info);
6217 if (Inst.isInvalid())
6218 return false;
6219
6220 bool AtLeastAsSpecialized;
6222 AtLeastAsSpecialized =
6223 ::FinishTemplateArgumentDeduction(
6224 *this, AArg, /*IsPartialOrdering=*/true, PArgs, Deduced, Info) ==
6225 TemplateDeductionResult::Success;
6226 });
6227 return AtLeastAsSpecialized;
6228}
6229
6230namespace {
6231struct MarkUsedTemplateParameterVisitor :
6232 RecursiveASTVisitor<MarkUsedTemplateParameterVisitor> {
6233 llvm::SmallBitVector &Used;
6234 unsigned Depth;
6235
6236 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used,
6237 unsigned Depth)
6238 : Used(Used), Depth(Depth) { }
6239
6240 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
6241 if (T->getDepth() == Depth)
6242 Used[T->getIndex()] = true;
6243 return true;
6244 }
6245
6246 bool TraverseTemplateName(TemplateName Template) {
6247 if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
6248 Template.getAsTemplateDecl()))
6249 if (TTP->getDepth() == Depth)
6250 Used[TTP->getIndex()] = true;
6252 TraverseTemplateName(Template);
6253 return true;
6254 }
6255
6256 bool VisitDeclRefExpr(DeclRefExpr *E) {
6257 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
6258 if (NTTP->getDepth() == Depth)
6259 Used[NTTP->getIndex()] = true;
6260 return true;
6261 }
6262};
6263}
6264
6265/// Mark the template parameters that are used by the given
6266/// expression.
6267static void
6269 const Expr *E,
6270 bool OnlyDeduced,
6271 unsigned Depth,
6272 llvm::SmallBitVector &Used) {
6273 if (!OnlyDeduced) {
6274 MarkUsedTemplateParameterVisitor(Used, Depth)
6275 .TraverseStmt(const_cast<Expr *>(E));
6276 return;
6277 }
6278
6279 // We can deduce from a pack expansion.
6280 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
6281 E = Expansion->getPattern();
6282
6284 if (!NTTP)
6285 return;
6286
6287 if (NTTP->getDepth() == Depth)
6288 Used[NTTP->getIndex()] = true;
6289
6290 // In C++17 mode, additional arguments may be deduced from the type of a
6291 // non-type argument.
6292 if (Ctx.getLangOpts().CPlusPlus17)
6293 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
6294}
6295
6296/// Mark the template parameters that are used by the given
6297/// nested name specifier.
6298static void
6301 bool OnlyDeduced,
6302 unsigned Depth,
6303 llvm::SmallBitVector &Used) {
6304 if (!NNS)
6305 return;
6306
6307 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
6308 Used);
6310 OnlyDeduced, Depth, Used);
6311}
6312
6313/// Mark the template parameters that are used by the given
6314/// template name.
6315static void
6317 TemplateName Name,
6318 bool OnlyDeduced,
6319 unsigned Depth,
6320 llvm::SmallBitVector &Used) {
6321 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
6323 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
6324 if (TTP->getDepth() == Depth)
6325 Used[TTP->getIndex()] = true;
6326 }
6327 return;
6328 }
6329
6330 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
6331 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
6332 Depth, Used);
6333 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
6334 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
6335 Depth, Used);
6336}
6337
6338/// Mark the template parameters that are used by the given
6339/// type.
6340static void
6342 bool OnlyDeduced,
6343 unsigned Depth,
6344 llvm::SmallBitVector &Used) {
6345 if (T.isNull())
6346 return;
6347
6348 // Non-dependent types have nothing deducible
6349 if (!T->isDependentType())
6350 return;
6351
6352 T = Ctx.getCanonicalType(T);
6353 switch (T->getTypeClass()) {
6354 case Type::Pointer:
6356 cast<PointerType>(T)->getPointeeType(),
6357 OnlyDeduced,
6358 Depth,
6359 Used);
6360 break;
6361
6362 case Type::BlockPointer:
6364 cast<BlockPointerType>(T)->getPointeeType(),
6365 OnlyDeduced,
6366 Depth,
6367 Used);
6368 break;
6369
6370 case Type::LValueReference:
6371 case Type::RValueReference:
6373 cast<ReferenceType>(T)->getPointeeType(),
6374 OnlyDeduced,
6375 Depth,
6376 Used);
6377 break;
6378
6379 case Type::MemberPointer: {
6380 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
6381 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
6382 Depth, Used);
6383 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
6384 OnlyDeduced, Depth, Used);
6385 break;
6386 }
6387
6388 case Type::DependentSizedArray:
6390 cast<DependentSizedArrayType>(T)->getSizeExpr(),
6391 OnlyDeduced, Depth, Used);
6392 // Fall through to check the element type
6393 [[fallthrough]];
6394
6395 case Type::ConstantArray:
6396 case Type::IncompleteArray:
6397 case Type::ArrayParameter:
6399 cast<ArrayType>(T)->getElementType(),
6400 OnlyDeduced, Depth, Used);
6401 break;
6402 case Type::Vector:
6403 case Type::ExtVector:
6405 cast<VectorType>(T)->getElementType(),
6406 OnlyDeduced, Depth, Used);
6407 break;
6408
6409 case Type::DependentVector: {
6410 const auto *VecType = cast<DependentVectorType>(T);
6411 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6412 Depth, Used);
6413 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
6414 Used);
6415 break;
6416 }
6417 case Type::DependentSizedExtVector: {
6418 const DependentSizedExtVectorType *VecType
6419 = cast<DependentSizedExtVectorType>(T);
6420 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6421 Depth, Used);
6422 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
6423 Depth, Used);
6424 break;
6425 }
6426
6427 case Type::DependentAddressSpace: {
6428 const DependentAddressSpaceType *DependentASType =
6429 cast<DependentAddressSpaceType>(T);
6430 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
6431 OnlyDeduced, Depth, Used);
6433 DependentASType->getAddrSpaceExpr(),
6434 OnlyDeduced, Depth, Used);
6435 break;
6436 }
6437
6438 case Type::ConstantMatrix: {
6439 const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T);
6440 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6441 Depth, Used);
6442 break;
6443 }
6444
6445 case Type::DependentSizedMatrix: {
6446 const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(T);
6447 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6448 Depth, Used);
6449 MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
6450 Used);
6451 MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
6452 Depth, Used);
6453 break;
6454 }
6455
6456 case Type::FunctionProto: {
6457 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
6458 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
6459 Used);
6460 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
6461 // C++17 [temp.deduct.type]p5:
6462 // The non-deduced contexts are: [...]
6463 // -- A function parameter pack that does not occur at the end of the
6464 // parameter-declaration-list.
6465 if (!OnlyDeduced || I + 1 == N ||
6466 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
6467 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
6468 Depth, Used);
6469 } else {
6470 // FIXME: C++17 [temp.deduct.call]p1:
6471 // When a function parameter pack appears in a non-deduced context,
6472 // the type of that pack is never deduced.
6473 //
6474 // We should also track a set of "never deduced" parameters, and
6475 // subtract that from the list of deduced parameters after marking.
6476 }
6477 }
6478 if (auto *E = Proto->getNoexceptExpr())
6479 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
6480 break;
6481 }
6482
6483 case Type::TemplateTypeParm: {
6484 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
6485 if (TTP->getDepth() == Depth)
6486 Used[TTP->getIndex()] = true;
6487 break;
6488 }
6489
6490 case Type::SubstTemplateTypeParmPack: {
6492 = cast<SubstTemplateTypeParmPackType>(T);
6493 if (Subst->getReplacedParameter()->getDepth() == Depth)
6494 Used[Subst->getIndex()] = true;
6496 OnlyDeduced, Depth, Used);
6497 break;
6498 }
6499
6500 case Type::InjectedClassName:
6501 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
6502 [[fallthrough]];
6503
6504 case Type::TemplateSpecialization: {
6505 const TemplateSpecializationType *Spec
6506 = cast<TemplateSpecializationType>(T);
6507 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
6508 Depth, Used);
6509
6510 // C++0x [temp.deduct.type]p9:
6511 // If the template argument list of P contains a pack expansion that is
6512 // not the last template argument, the entire template argument list is a
6513 // non-deduced context.
6514 if (OnlyDeduced &&
6516 break;
6517
6518 for (const auto &Arg : Spec->template_arguments())
6519 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6520 break;
6521 }
6522
6523 case Type::Complex:
6524 if (!OnlyDeduced)
6526 cast<ComplexType>(T)->getElementType(),
6527 OnlyDeduced, Depth, Used);
6528 break;
6529
6530 case Type::Atomic:
6531 if (!OnlyDeduced)
6533 cast<AtomicType>(T)->getValueType(),
6534 OnlyDeduced, Depth, Used);
6535 break;
6536
6537 case Type::DependentName:
6538 if (!OnlyDeduced)
6540 cast<DependentNameType>(T)->getQualifier(),
6541 OnlyDeduced, Depth, Used);
6542 break;
6543
6544 case Type::DependentTemplateSpecialization: {
6545 // C++14 [temp.deduct.type]p5:
6546 // The non-deduced contexts are:
6547 // -- The nested-name-specifier of a type that was specified using a
6548 // qualified-id
6549 //
6550 // C++14 [temp.deduct.type]p6:
6551 // When a type name is specified in a way that includes a non-deduced
6552 // context, all of the types that comprise that type name are also
6553 // non-deduced.
6554 if (OnlyDeduced)
6555 break;
6556
6558 = cast<DependentTemplateSpecializationType>(T);
6559
6561 OnlyDeduced, Depth, Used);
6562
6563 for (const auto &Arg : Spec->template_arguments())
6564 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6565 break;
6566 }
6567
6568 case Type::TypeOf:
6569 if (!OnlyDeduced)
6570 MarkUsedTemplateParameters(Ctx, cast<TypeOfType>(T)->getUnmodifiedType(),
6571 OnlyDeduced, Depth, Used);
6572 break;
6573
6574 case Type::TypeOfExpr:
6575 if (!OnlyDeduced)
6577 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
6578 OnlyDeduced, Depth, Used);
6579 break;
6580
6581 case Type::Decltype:
6582 if (!OnlyDeduced)
6584 cast<DecltypeType>(T)->getUnderlyingExpr(),
6585 OnlyDeduced, Depth, Used);
6586 break;
6587
6588 case Type::PackIndexing:
6589 if (!OnlyDeduced) {
6590 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getPattern(),
6591 OnlyDeduced, Depth, Used);
6592 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getIndexExpr(),
6593 OnlyDeduced, Depth, Used);
6594 }
6595 break;
6596
6597 case Type::UnaryTransform:
6598 if (!OnlyDeduced)
6600 cast<UnaryTransformType>(T)->getUnderlyingType(),
6601 OnlyDeduced, Depth, Used);
6602 break;
6603
6604 case Type::PackExpansion:
6606 cast<PackExpansionType>(T)->getPattern(),
6607 OnlyDeduced, Depth, Used);
6608 break;
6609
6610 case Type::Auto:
6611 case Type::DeducedTemplateSpecialization:
6613 cast<DeducedType>(T)->getDeducedType(),
6614 OnlyDeduced, Depth, Used);
6615 break;
6616 case Type::DependentBitInt:
6618 cast<DependentBitIntType>(T)->getNumBitsExpr(),
6619 OnlyDeduced, Depth, Used);
6620 break;
6621
6622 // None of these types have any template parameters in them.
6623 case Type::Builtin:
6624 case Type::VariableArray:
6625 case Type::FunctionNoProto:
6626 case Type::Record:
6627 case Type::Enum:
6628 case Type::ObjCInterface:
6629 case Type::ObjCObject:
6630 case Type::ObjCObjectPointer:
6631 case Type::UnresolvedUsing:
6632 case Type::Pipe:
6633 case Type::BitInt:
6634#define TYPE(Class, Base)
6635#define ABSTRACT_TYPE(Class, Base)
6636#define DEPENDENT_TYPE(Class, Base)
6637#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6638#include "clang/AST/TypeNodes.inc"
6639 break;
6640 }
6641}
6642
6643/// Mark the template parameters that are used by this
6644/// template argument.
6645static void
6648 bool OnlyDeduced,
6649 unsigned Depth,
6650 llvm::SmallBitVector &Used) {
6651 switch (TemplateArg.getKind()) {
6657 break;
6658
6660 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
6661 Depth, Used);
6662 break;
6663
6667 TemplateArg.getAsTemplateOrTemplatePattern(),
6668 OnlyDeduced, Depth, Used);
6669 break;
6670
6672 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
6673 Depth, Used);
6674 break;
6675
6677 for (const auto &P : TemplateArg.pack_elements())
6678 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
6679 break;
6680 }
6681}
6682
6683void
6684Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
6685 unsigned Depth,
6686 llvm::SmallBitVector &Used) {
6687 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
6688}
6689
6690void
6692 bool OnlyDeduced, unsigned Depth,
6693 llvm::SmallBitVector &Used) {
6694 // C++0x [temp.deduct.type]p9:
6695 // If the template argument list of P contains a pack expansion that is not
6696 // the last template argument, the entire template argument list is a
6697 // non-deduced context.
6698 if (OnlyDeduced &&
6699 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
6700 return;
6701
6702 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6703 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
6704 Depth, Used);
6705}
6706
6708 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
6709 llvm::SmallBitVector &Deduced) {
6710 TemplateParameterList *TemplateParams
6711 = FunctionTemplate->getTemplateParameters();
6712 Deduced.clear();
6713 Deduced.resize(TemplateParams->size());
6714
6715 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
6716 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
6717 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
6718 true, TemplateParams->getDepth(), Deduced);
6719}
6720
6722 FunctionTemplateDecl *FunctionTemplate,
6723 QualType T) {
6724 if (!T->isDependentType())
6725 return false;
6726
6727 TemplateParameterList *TemplateParams
6728 = FunctionTemplate->getTemplateParameters();
6729 llvm::SmallBitVector Deduced(TemplateParams->size());
6730 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
6731 Deduced);
6732
6733 return Deduced.any();
6734}
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:1171
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:146
#define X(type, name)
Definition: Value.h:143
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:758
static bool isSameTemplateArg(ASTContext &Context, TemplateArgument X, const TemplateArgument &Y, bool PartialOrdering, bool PackExpansionMatchesPack=false)
Determine whether two template arguments are the same.
static bool isAtLeastAsSpecializedAs(Sema &S, SourceLocation Loc, const FunctionTemplateDecl *FT1, const FunctionTemplateDecl *FT2, TemplatePartialOrderingContext TPOC, bool Reversed, const SmallVector< QualType > &Args1, const SmallVector< QualType > &Args2)
Determine whether the function template FT1 is at least as specialized as FT2.
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 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 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 TemplateDeductionResult DeduceTemplateBases(Sema &S, const CXXRecordDecl *RD, TemplateParameterList *TemplateParams, QualType P, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced)
Attempt to deduce the template arguments by checking the base types according to (C++20 [temp....
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 DeduceTemplateSpecArguments(Sema &S, TemplateParameterList *TemplateParams, const QualType P, QualType A, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced)
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.
static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template, TemplateDeductionInfo &Info, bool IsDeduced, SmallVectorImpl< TemplateArgument > &SugaredOutput, SmallVectorImpl< TemplateArgument > &CanonicalOutput)
Convert the given deduced template argument and add it to the set of fully-converted template argumen...
static TemplateParameter makeTemplateParameter(Decl *D)
Helper function to build a TemplateParameter when we don't know its type statically.
static TemplateDeductionResult CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info, Sema::OriginalCallArg OriginalArg, QualType DeducedA)
Check whether the deduced argument type for a call to a function template matches the actual argument...
static TemplateDeductionResult DeduceNullPtrTemplateArgument(Sema &S, TemplateParameterList *TemplateParams, const NonTypeTemplateParmDecl *NTTP, QualType NullPtrType, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced)
Deduce the value of the given non-type template parameter from the given null pointer template argume...
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 TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, PackFold PackFold=PackFold::ParameterToArgument)
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 QualType GetImplicitObjectParameterType(ASTContext &Context, const CXXMethodDecl *Method, QualType RawType, bool IsOtherRvr)
static TemplateDeductionResult DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType, InitListExpr *ILE, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< Sema::OriginalCallArg > &OriginalCallArgs, unsigned ArgIdx, unsigned TDF)
Attempt template argument deduction from an initializer list deemed to be an argument in a function c...
static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD)
Get the index of the first template parameter that was originally from the innermost template-paramet...
@ ArgumentToParameter
@ ParameterToArgument
static TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch(Sema &S, TemplateParameterList *TemplateParams, QualType Param, QualType Arg, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned TDF, bool PartialOrdering=false, bool DeducedFromArrayBound=false)
Deduce the template arguments by comparing the parameter type and the argument type (C++ [temp....
static TemplateDeductionResult DeduceNonTypeTemplateArgument(Sema &S, TemplateParameterList *TemplateParams, const NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced, QualType ValueType, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced)
Deduce the value of the given non-type template parameter as the given deduced template argument.
static TemplateDeductionResult ConvertDeducedTemplateArguments(Sema &S, TemplateDeclT *Template, bool IsDeduced, SmallVectorImpl< DeducedTemplateArgument > &Deduced, TemplateDeductionInfo &Info, SmallVectorImpl< TemplateArgument > &SugaredBuilder, SmallVectorImpl< TemplateArgument > &CanonicalBuilder, LocalInstantiationScope *CurrentInstantiationScope=nullptr, unsigned NumAlreadyConverted=0, bool PartialOverloading=false)
static bool DeducedArgsNeedReplacement(TemplateDeclT *Template)
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 NamedDecl * getTemplateParameterWithDefault(Sema &S, NamedDecl *A, TemplateArgument Default)
Create a shallow copy of a given template parameter declaration, with empty source locations and usin...
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)
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.
C Language Family Type Representation.
__device__ int
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2825
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 ...
TemplateName getCanonicalTemplateName(const TemplateName &Name) const
Retrieves the "canonical" template name that refers to a given template.
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:2628
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2644
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
void getInjectedTemplateArgs(const TemplateParameterList *Params, SmallVectorImpl< TemplateArgument > &Args)
Get a template argument list with one argument per template parameter in a template parameter list,...
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:2831
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:1147
CanQualType NullPtrTy
Definition: ASTContext.h:1146
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:1637
const LangOptions & getLangOpts() const
Definition: ASTContext.h:797
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl)
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:1120
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y) const
Determine whether the given template names refer to the same template.
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:1128
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2210
LangAS getDefaultOpenCLPointeeAddrSpace()
Returns default address space based on OpenCL version and enabled features.
Definition: ASTContext.h:1462
CanQualType OverloadTy
Definition: ASTContext.h:1147
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2675
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:2394
CanQualType UnsignedIntTy
Definition: ASTContext.h:1129
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:1615
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
const DependentSizedArrayType * getAsDependentSizedArrayType(QualType T) const
Definition: ASTContext.h:2834
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:6375
ArrayRef< TemplateArgument > getTypeConstraintArguments() const
Definition: Type.h:6385
bool isDecltypeAuto() const
Definition: Type.h:6398
ConceptDecl * getTypeConstraintConcept() const
Definition: Type.h:6390
AutoTypeKeyword getKeyword() const
Definition: Type.h:6406
bool isConstrained() const
Definition: Type.h:6394
A fixed int type of a specified bitwidth.
Definition: Type.h:7633
Pointer to a block type.
Definition: Type.h:3397
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2866
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2906
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2064
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:2493
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2240
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2225
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:1633
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:3134
Declaration of a C++20 concept.
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:421
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4219
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4240
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4237
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:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
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:261
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:242
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1207
bool isInvalidDecl() const
Definition: DeclBase.h:595
SourceLocation getLocation() const
Definition: DeclBase.h:446
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:232
DeclContext * getDeclContext()
Definition: DeclBase.h:455
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
Kind getKind() const
Definition: DeclBase.h:449
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:434
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:6442
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6341
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3907
Expr * getAddrSpaceExpr() const
Definition: Type.h:3918
QualType getPointeeType() const
Definition: Type.h:3919
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3947
QualType getElementType() const
Definition: Type.h:3962
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4278
Expr * getColumnExpr() const
Definition: Type.h:4291
Expr * getRowExpr() const
Definition: Type.h:4290
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:491
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:6895
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6914
NestedNameSpecifier * getQualifier() const
Definition: Type.h:6911
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4073
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6762
RAII object that enters a new expression evaluation context.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1901
bool isInvalid() const
Determine if the explicit specifier is invalid.
Definition: DeclCXX.h:1930
const Expr * getExpr() const
Definition: DeclCXX.h:1910
The return type of classify().
Definition: Expr.h:330
bool isLValue() const
Definition: Expr.h:380
This represents one expression.
Definition: Expr.h:110
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:405
QualType getType() const
Definition: Expr.h:142
ExtVectorType - Extended vector type.
Definition: Type.h:4113
Stores a list of template parameters and the associated requires-clause (if any) for a TemplateDecl a...
Definition: DeclTemplate.h:222
Represents a function declaration or definition.
Definition: Decl.h:1932
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2669
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4040
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4028
QualType getReturnType() const
Definition: Decl.h:2717
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2646
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:4099
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4164
bool isImmediateEscalating() const
Definition: Decl.cpp:3256
void getAssociatedConstraints(SmallVectorImpl< const Expr * > &AC) const
Get the associated-constraints of this function declaration.
Definition: Decl.h:2624
size_t param_size() const
Definition: Decl.h:2662
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:3191
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5002
param_type_iterator param_type_begin() const
Definition: Type.h:5415
const ExtParameterInfo * getExtParameterInfosOrNull() const
Return a pointer to the beginning of the array of extra parameter information, if present,...
Definition: Type.h:5453
unsigned getNumParams() const
Definition: Type.h:5255
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: Type.h:5395
QualType getParamType(unsigned i) const
Definition: Type.h:5257
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5288
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5266
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:5340
param_type_iterator param_type_end() const
Definition: Type.h:5419
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5262
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4308
QualType getReturnType() const
Definition: Type.h:4630
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes an C or C++ initializer list.
Definition: Expr.h:5029
unsigned getNumInits() const
Definition: Expr.h:5059
ArrayRef< Expr * > inits()
Definition: Expr.h:5069
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6612
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3472
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
void SetPartiallySubstitutedPack(NamedDecl *Pack, const TemplateArgument *ExplicitArgs, unsigned NumExplicitArgs)
Note that the given parameter pack has been partially substituted via explicit specification of templ...
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: Type.h:4183
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4197
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3508
QualType getPointeeType() const
Definition: Type.h:3524
const Type * getClass() const
Definition: Type.h:3538
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:249
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
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...
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
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:7399
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition: ExprCXX.h:2982
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition: ExprCXX.h:3134
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3043
SourceLocation getNameLoc() const
Gets the location of the name.
Definition: ExprCXX.h:3095
decls_iterator decls_begin() const
Definition: ExprCXX.h:3075
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition: ExprCXX.h:3154
decls_iterator decls_end() const
Definition: ExprCXX.h:3078
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4179
Represents a pack expansion of types.
Definition: Type.h:6960
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:6981
std::optional< unsigned > getNumExpansions() const
Retrieve the number of expansions that this pack expansion will generate, if known.
Definition: Type.h:6985
bool hasSelectedType() const
Definition: Type.h:5851
QualType getSelectedType() const
Definition: Type.h:5844
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3187
QualType getPointeeType() const
Definition: Type.h:3197
A (possibly-)qualified type.
Definition: Type.h:941
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7839
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7750
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7876
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7790
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:7951
QualType getCanonicalType() const
Definition: Type.h:7802
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7844
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7871
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7796
Represents a template name as written in source code.
Definition: TemplateName.h:434
The collection of all-type qualifiers we support.
Definition: Type.h:319
unsigned getCVRQualifiers() const
Definition: Type.h:475
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:482
GC getObjCGCAttr() const
Definition: Type.h:506
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:348
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:341
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:337
void removeObjCLifetime()
Definition: Type.h:538
bool isStrictSupersetOf(Qualifiers Other) const
Determine whether this set of qualifiers is a strict superset of another set of qualifiers,...
Definition: Type.cpp:60
bool hasConst() const
Definition: Type.h:444
bool hasNonTrivialObjCLifetime() const
True if the lifetime is neither None or ExplicitNone.
Definition: Type.h:546
bool hasAddressSpace() const
Definition: Type.h:557
void removeObjCGCAttr()
Definition: Type.h:510
void removeAddressSpace()
Definition: Type.h:583
bool hasObjCGCAttr() const
Definition: Type.h:505
void setCVRQualifiers(unsigned mask)
Definition: Type.h:478
bool hasObjCLifetime() const
Definition: Type.h:531
ObjCLifetime getObjCLifetime() const
Definition: Type.h:532
Qualifiers withoutObjCLifetime() const
Definition: Type.h:520
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:732
LangAS getAddressSpace() const
Definition: Type.h:558
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:535
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3490
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5965
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
bool TraverseTemplateName(TemplateName Template)
Recursively visit a template name and dispatch to the appropriate method.
ArrayRef< TemplateArgument > getInjectedTemplateArgs()
Retrieve the "injected" template arguments that correspond to the template parameters of this templat...
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3428
QualType getPointeeType() const
Definition: Type.h:3446
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:13247
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8115
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3065
A helper class for building up ExtParameterInfos.
Definition: Sema.h:12669
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:12688
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12141
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12171
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:535
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:12698
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:1166
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:6508
@ CTAK_DeducedFromArrayBound
The template argument was deduced from an array bound via template argument deduction.
Definition: Sema.h:11705
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:11697
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition: Sema.h:11701
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition: Sema.h:1004
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:2611
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
ASTContext & getASTContext() const
Definition: Sema.h:602
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:701
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:910
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc, bool IsDeduced)
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition: Sema.h:11875
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:595
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:14410
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr, bool PartialOrderingTTP=false)
Check that the given template arguments can be provided to the given template, converting the argumen...
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false)
Returns the more specialized function template according to the rules of function template partial or...
std::optional< unsigned > getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs)
Determine the number of arguments in the given pack expansion type.
ExplicitSpecifier instantiateExplicitSpecifier(const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES)
TemplateDeductionResult SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< QualType > &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info)
Substitute the explicitly-provided template arguments into the given function template according to C...
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl * > Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl * > *OutParams, ExtParameterInfoBuilder &ParamInfos)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult)
Given an expression that refers to an overloaded function, try to resolve that function to a single f...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1139
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition: Sema.h:12204
QualType getDecltypeForExpr(Expr *E)
getDecltypeForExpr - Given an expr, will return the decltype for that expression, according to the ru...
Definition: SemaType.cpp:9417
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20709
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:14980
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are used in a given expression.
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
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:8880
TypeSourceInfo * SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init)
TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, SourceLocation Location)
Get a template argument mapping the given template parameter to itself, e.g.
bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD, SourceLocation Loc)
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
TemplateDeductionResult FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl< OriginalCallArg > const *OriginalCallArgs=nullptr, bool PartialOverloading=false, llvm::function_ref< bool()> CheckNonDependent=[] { return false;})
Finish template argument deduction for a function template, checking the deduced template arguments f...
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:573
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
Definition: SemaType.cpp:8003
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"...
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)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition: Sema.h:12542
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:6283
TemplateArgument getArgumentPack() const
Definition: Type.cpp:4244
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
Definition: Type.h:6309
const TemplateTypeParmDecl * getReplacedParameter() const
Gets the template parameter declaration that was substituted for.
Definition: Type.cpp:4236
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:244
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:280
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Definition: DeclTemplate.h:265
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:274
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:394
bool isTypeAlias() const
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: DeclTemplate.h:438
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:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:203
TemplateDecl * getAsTemplateDecl() 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:355
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:180
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:6480
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6548
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6546
QualType desugar() const
Definition: Type.h:6557
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, bool Typename, TemplateParameterList *Params)
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
unsigned getDepth() const
Retrieve the depth of the template parameter.
Wrapper for template type parameters.
Definition: TypeLoc.h:758
unsigned getIndex() const
Definition: Type.h:6173
unsigned getDepth() const
Definition: Type.h:6172
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
const Type * getTypeForDecl() const
Definition: Decl.h:3391
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:7721
SourceLocation getNameLoc() const
Definition: TypeLoc.h:535
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
The base class of the type hierarchy.
Definition: Type.h:1829
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isVoidType() const
Definition: Type.h:8319
bool isIncompleteArrayType() const
Definition: Type.h:8083
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:8295
bool isRValueReferenceType() const
Definition: Type.h:8029
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8477
bool isArrayType() const
Definition: Type.h:8075
bool isFunctionPointerType() const
Definition: Type.h:8043
bool isPointerType() const
Definition: Type.h:8003
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8607
bool isReferenceType() const
Definition: Type.h:8021
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2800
bool isLValueReferenceType() const
Definition: Type.h:8025
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2695
QualType getCanonicalTypeInternal() const
Definition: Type.h:2978
bool isMemberPointerType() const
Definition: Type.h:8057
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4970
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8453
bool isFunctionType() const
Definition: Type.h:7999
bool isObjCObjectPointerType() const
Definition: Type.h:8145
bool isMemberFunctionPointerType() const
Definition: Type.h:8061
bool isAnyPointerType() const
Definition: Type.h:8011
TypeClass getTypeClass() const
Definition: Type.h:2334
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2360
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8540
bool isRecordType() const
Definition: Type.h:8103
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:667
QualType getType() const
Definition: Decl.h:678
QualType getType() const
Definition: Value.cpp:234
Represents a variable declaration or definition.
Definition: Decl.h:879
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1519
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:4021
Provides information about an attempted template argument deduction, whose success or failure was des...
void setExplicitArgs(TemplateArgumentList *NewDeducedSugared, TemplateArgumentList *NewDeducedCanonical)
Provide an initial template argument list that contains the explicitly-specified arguments.
TemplateArgumentList * takeCanonical()
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
SourceLocation getLocation() const
Returns the location at which template argument is occurring.
void clearSFINAEDiagnostic()
Discard any SFINAE diagnostics.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
diag_iterator diag_end() const
Returns an iterator at the end of the sequence of suppressed diagnostics.
void reset(TemplateArgumentList *NewDeducedSugared, TemplateArgumentList *NewDeducedCanonical)
Provide a new template argument list that contains the results of template argument deduction.
unsigned getDeducedDepth() const
The depth of template parameters for which deduction is being performed.
diag_iterator diag_begin() const
Returns an iterator at the beginning of the sequence of suppressed diagnostics.
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
The JSON file list parser is used to communicate input to InstallAPI.
@ CPlusPlus20
Definition: LangStandard.h:60
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus11
Definition: LangStandard.h:57
@ CPlusPlus14
Definition: LangStandard.h:58
bool isTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:77
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1778
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1784
unsigned toTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:81
@ Result
The result type of a method or function.
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:65
std::pair< unsigned, unsigned > getDepthAndIndex(NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:61
std::optional< unsigned > getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition: ASTLambda.h:62
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
TPOC
The context in which partial ordering of function templates occurs.
Definition: Template.h:298
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition: Template.h:304
@ TPOC_Other
Partial ordering of function templates in other contexts, e.g., taking the address of a function temp...
Definition: Template.h:309
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition: Template.h:300
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:387
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Invalid
The declaration was invalid; do nothing.
@ Success
Template argument deduction was successful.
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ EST_Uninstantiated
not instantiated yet
@ EST_None
no exception specification
TemplateDeductionFlags
Various flags that control template argument deduction.
@ TDF_None
No template argument deduction flags, which indicates the strictest results for template argument ded...
@ TDF_DerivedClass
Within template argument deduction from a function call, we are matching in a case where we can perfo...
@ TDF_TopLevelParameterTypeList
Whether we are performing template argument deduction for parameters and arguments in a top-level tem...
@ TDF_IgnoreQualifiers
Within template argument deduction from a function call, we are matching in a case where we ignore cv...
@ TDF_ParamWithReferenceType
Within template argument deduction from a function call, we are matching with a parameter type for wh...
@ TDF_SkipNonDependent
Allow non-dependent types to differ, e.g., when performing template argument deduction from a functio...
@ TDF_AllowCompatibleFunctionType
Within template argument deduction from overload resolution per C++ [over.over] allow matching functi...
@ TDF_ArgWithReferenceType
Within template argument deduction for a conversion function, we are matching with an argument type f...
ActionResult< CXXBaseSpecifier * > BaseResult
Definition: Ownership.h:251
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
#define bool
Definition: stdbool.h:24
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:5059
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5061
Extra information about a function prototype.
Definition: Type.h:5087
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:5095
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5088
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition: Sema.h:12736
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:12743
A stack object to be created when performing template instantiation.
Definition: Sema.h:12900
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:13054
brief A function argument from which we performed template argument
Definition: Sema.h:12304
Location information for a TemplateArgument.
Definition: TemplateBase.h:472