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 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
507 TemplateArgument New(D, T);
509 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
510}
511
512/// Create a shallow copy of a given template parameter declaration, with
513/// empty source locations and using the given TemplateArgument as it's
514/// default argument.
515///
516/// \returns The new template parameter declaration.
519 switch (A->getKind()) {
520 case Decl::TemplateTypeParm: {
521 auto *T = cast<TemplateTypeParmDecl>(A);
524 T->getDepth(), T->getIndex(), T->getIdentifier(),
525 T->wasDeclaredWithTypename(), T->isParameterPack(),
526 T->hasTypeConstraint());
527 R->setDefaultArgument(
528 S.Context,
530 if (R->hasTypeConstraint()) {
531 auto *C = R->getTypeConstraint();
532 R->setTypeConstraint(C->getConceptReference(),
533 C->getImmediatelyDeclaredConstraint());
534 }
535 return R;
536 }
537 case Decl::NonTypeTemplateParm: {
538 auto *T = cast<NonTypeTemplateParmDecl>(A);
541 T->getDepth(), T->getIndex(), T->getIdentifier(), T->getType(),
542 T->isParameterPack(), T->getTypeSourceInfo());
543 R->setDefaultArgument(S.Context,
545 Default, Default.getNonTypeTemplateArgumentType(),
546 SourceLocation()));
547 if (auto *PTC = T->getPlaceholderTypeConstraint())
548 R->setPlaceholderTypeConstraint(PTC);
549 return R;
550 }
551 case Decl::TemplateTemplateParm: {
552 auto *T = cast<TemplateTemplateParmDecl>(A);
554 S.Context, A->getDeclContext(), SourceLocation(), T->getDepth(),
555 T->getIndex(), T->isParameterPack(), T->getIdentifier(),
556 T->wasDeclaredWithTypename(), T->getTemplateParameters());
557 R->setDefaultArgument(
558 S.Context,
560 return R;
561 }
562 default:
563 llvm_unreachable("Unexpected Decl Kind");
564 }
565}
566
569 TemplateName Param, TemplateName Arg,
571 ArrayRef<TemplateArgument> DefaultArguments,
573 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
574 if (!ParamDecl) {
575 // The parameter type is dependent and is not a template template parameter,
576 // so there is nothing that we can deduce.
577 return TemplateDeductionResult::Success;
578 }
579
580 if (auto *TempParam = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
581 // If we're not deducing at this depth, there's nothing to deduce.
582 if (TempParam->getDepth() != Info.getDeducedDepth())
583 return TemplateDeductionResult::Success;
584
585 auto NewDeduced = DeducedTemplateArgument(Arg);
586 // Provisional resolution for CWG2398: If Arg is also a template template
587 // param, and it names a template specialization, then we deduce a
588 // synthesized template template parameter based on A, but using the TS's
589 // arguments as defaults.
590 if (auto *TempArg = dyn_cast_or_null<TemplateTemplateParmDecl>(
591 Arg.getAsTemplateDecl())) {
592 assert(!TempArg->isExpandedParameterPack());
593
594 TemplateParameterList *As = TempArg->getTemplateParameters();
595 if (DefaultArguments.size() != 0) {
596 assert(DefaultArguments.size() <= As->size());
597 SmallVector<NamedDecl *, 4> Params(As->size());
598 for (unsigned I = 0; I < DefaultArguments.size(); ++I)
599 Params[I] = getTemplateParameterWithDefault(S, As->getParam(I),
600 DefaultArguments[I]);
601 for (unsigned I = DefaultArguments.size(); I < As->size(); ++I)
602 Params[I] = As->getParam(I);
603 // FIXME: We could unique these, and also the parameters, but we don't
604 // expect programs to contain a large enough amount of these deductions
605 // for that to be worthwhile.
606 auto *TPL = TemplateParameterList::Create(
607 S.Context, SourceLocation(), SourceLocation(), Params,
609 NewDeduced = DeducedTemplateArgument(
611 S.Context, TempArg->getDeclContext(), SourceLocation(),
612 TempArg->getDepth(), TempArg->getPosition(),
613 TempArg->isParameterPack(), TempArg->getIdentifier(),
614 TempArg->wasDeclaredWithTypename(), TPL)));
615 }
616 }
617
619 Deduced[TempParam->getIndex()],
620 NewDeduced);
621 if (Result.isNull()) {
622 Info.Param = TempParam;
623 Info.FirstArg = Deduced[TempParam->getIndex()];
624 Info.SecondArg = NewDeduced;
625 return TemplateDeductionResult::Inconsistent;
626 }
627
628 Deduced[TempParam->getIndex()] = Result;
629 return TemplateDeductionResult::Success;
630 }
631
632 // Verify that the two template names are equivalent.
633 if (S.Context.hasSameTemplateName(Param, Arg))
634 return TemplateDeductionResult::Success;
635
636 // Mismatch of non-dependent template parameter to argument.
637 Info.FirstArg = TemplateArgument(Param);
638 Info.SecondArg = TemplateArgument(Arg);
639 return TemplateDeductionResult::NonDeducedMismatch;
640}
641
642/// Deduce the template arguments by comparing the template parameter
643/// type (which is a template-id) with the template argument type.
644///
645/// \param S the Sema
646///
647/// \param TemplateParams the template parameters that we are deducing
648///
649/// \param P the parameter type
650///
651/// \param A the argument type
652///
653/// \param Info information about the template argument deduction itself
654///
655/// \param Deduced the deduced template arguments
656///
657/// \returns the result of template argument deduction so far. Note that a
658/// "success" result means that template argument deduction has not yet failed,
659/// but it may still fail, later, for other reasons.
660
662 for (const Type *T = QT.getTypePtr(); /**/; /**/) {
663 const TemplateSpecializationType *TST =
665 assert(TST && "Expected a TemplateSpecializationType");
666 if (!TST->isSugared())
667 return TST;
668 T = TST->desugar().getTypePtr();
669 }
670}
671
674 const QualType P, QualType A,
677 QualType UP = P;
678 if (const auto *IP = P->getAs<InjectedClassNameType>())
679 UP = IP->getInjectedSpecializationType();
680
681 assert(isa<TemplateSpecializationType>(UP.getCanonicalType()));
683 TemplateName TNP = TP->getTemplateName();
684
685 // If the parameter is an alias template, there is nothing to deduce.
686 if (const auto *TD = TNP.getAsTemplateDecl(); TD && TD->isTypeAlias())
687 return TemplateDeductionResult::Success;
688
689 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
690 // arguments.
694 ->template_arguments();
695
696 QualType UA = A;
697 std::optional<NestedNameSpecifier *> NNS;
698 // Treat an injected-class-name as its underlying template-id.
699 if (const auto *Elaborated = A->getAs<ElaboratedType>()) {
700 NNS = Elaborated->getQualifier();
701 } else if (const auto *Injected = A->getAs<InjectedClassNameType>()) {
702 UA = Injected->getInjectedSpecializationType();
703 NNS = nullptr;
704 }
705
706 // Check whether the template argument is a dependent template-id.
707 if (isa<TemplateSpecializationType>(UA.getCanonicalType())) {
709 TemplateName TNA = SA->getTemplateName();
710
711 // If the argument is an alias template, there is nothing to deduce.
712 if (const auto *TD = TNA.getAsTemplateDecl(); TD && TD->isTypeAlias())
713 return TemplateDeductionResult::Success;
714
715 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
716 // arguments.
720 ->template_arguments();
721
722 // Perform template argument deduction for the template name.
723 if (auto Result = DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
724 AResolved, Deduced);
725 Result != TemplateDeductionResult::Success)
726 return Result;
727
728 // Perform template argument deduction on each template
729 // argument. Ignore any missing/extra arguments, since they could be
730 // filled in by default arguments.
731 return DeduceTemplateArguments(S, TemplateParams, PResolved, AResolved,
732 Info, Deduced,
733 /*NumberOfArgumentsMustMatch=*/false);
734 }
735
736 // If the argument type is a class template specialization, we
737 // perform template argument deduction using its template
738 // arguments.
739 const auto *RA = UA->getAs<RecordType>();
740 const auto *SA =
741 RA ? dyn_cast<ClassTemplateSpecializationDecl>(RA->getDecl()) : nullptr;
742 if (!SA) {
744 Info.SecondArg = TemplateArgument(A);
745 return TemplateDeductionResult::NonDeducedMismatch;
746 }
747
748 TemplateName TNA = TemplateName(SA->getSpecializedTemplate());
749 if (NNS)
751 *NNS, false, TemplateName(SA->getSpecializedTemplate()));
752
753 // Perform template argument deduction for the template name.
754 if (auto Result =
755 DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
756 SA->getTemplateArgs().asArray(), Deduced);
757 Result != TemplateDeductionResult::Success)
758 return Result;
759
760 // Perform template argument deduction for the template arguments.
761 return DeduceTemplateArguments(S, TemplateParams, PResolved,
762 SA->getTemplateArgs().asArray(), Info, Deduced,
763 /*NumberOfArgumentsMustMatch=*/true);
764}
765
767 assert(T->isCanonicalUnqualified());
768
769 switch (T->getTypeClass()) {
770 case Type::TypeOfExpr:
771 case Type::TypeOf:
772 case Type::DependentName:
773 case Type::Decltype:
774 case Type::PackIndexing:
775 case Type::UnresolvedUsing:
776 case Type::TemplateTypeParm:
777 case Type::Auto:
778 return true;
779
780 case Type::ConstantArray:
781 case Type::IncompleteArray:
782 case Type::VariableArray:
783 case Type::DependentSizedArray:
785 cast<ArrayType>(T)->getElementType().getTypePtr());
786
787 default:
788 return false;
789 }
790}
791
792/// Determines whether the given type is an opaque type that
793/// might be more qualified when instantiated.
797}
798
799/// Helper function to build a TemplateParameter when we don't
800/// know its type statically.
802 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
803 return TemplateParameter(TTP);
804 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
805 return TemplateParameter(NTTP);
806
807 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
808}
809
810/// A pack that we're currently deducing.
812 // The index of the pack.
813 unsigned Index;
814
815 // The old value of the pack before we started deducing it.
817
818 // A deferred value of this pack from an inner deduction, that couldn't be
819 // deduced because this deduction hadn't happened yet.
821
822 // The new value of the pack.
824
825 // The outer deduction for this pack, if any.
826 DeducedPack *Outer = nullptr;
827
828 DeducedPack(unsigned Index) : Index(Index) {}
829};
830
831namespace {
832
833/// A scope in which we're performing pack deduction.
834class PackDeductionScope {
835public:
836 /// Prepare to deduce the packs named within Pattern.
837 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
840 bool DeducePackIfNotAlreadyDeduced = false)
841 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info),
842 DeducePackIfNotAlreadyDeduced(DeducePackIfNotAlreadyDeduced){
843 unsigned NumNamedPacks = addPacks(Pattern);
844 finishConstruction(NumNamedPacks);
845 }
846
847 /// Prepare to directly deduce arguments of the parameter with index \p Index.
848 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
850 TemplateDeductionInfo &Info, unsigned Index)
851 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
852 addPack(Index);
853 finishConstruction(1);
854 }
855
856private:
857 void addPack(unsigned Index) {
858 // Save the deduced template argument for the parameter pack expanded
859 // by this pack expansion, then clear out the deduction.
860 DeducedFromEarlierParameter = !Deduced[Index].isNull();
861 DeducedPack Pack(Index);
862 Pack.Saved = Deduced[Index];
863 Deduced[Index] = TemplateArgument();
864
865 // FIXME: What if we encounter multiple packs with different numbers of
866 // pre-expanded expansions? (This should already have been diagnosed
867 // during substitution.)
868 if (std::optional<unsigned> ExpandedPackExpansions =
869 getExpandedPackSize(TemplateParams->getParam(Index)))
870 FixedNumExpansions = ExpandedPackExpansions;
871
872 Packs.push_back(Pack);
873 }
874
875 unsigned addPacks(TemplateArgument Pattern) {
876 // Compute the set of template parameter indices that correspond to
877 // parameter packs expanded by the pack expansion.
878 llvm::SmallBitVector SawIndices(TemplateParams->size());
880
881 auto AddPack = [&](unsigned Index) {
882 if (SawIndices[Index])
883 return;
884 SawIndices[Index] = true;
885 addPack(Index);
886
887 // Deducing a parameter pack that is a pack expansion also constrains the
888 // packs appearing in that parameter to have the same deduced arity. Also,
889 // in C++17 onwards, deducing a non-type template parameter deduces its
890 // type, so we need to collect the pending deduced values for those packs.
891 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
892 TemplateParams->getParam(Index))) {
893 if (!NTTP->isExpandedParameterPack())
894 if (auto *Expansion = dyn_cast<PackExpansionType>(NTTP->getType()))
895 ExtraDeductions.push_back(Expansion->getPattern());
896 }
897 // FIXME: Also collect the unexpanded packs in any type and template
898 // parameter packs that are pack expansions.
899 };
900
901 auto Collect = [&](TemplateArgument Pattern) {
903 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
904 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
905 unsigned Depth, Index;
906 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
907 if (Depth == Info.getDeducedDepth())
908 AddPack(Index);
909 }
910 };
911
912 // Look for unexpanded packs in the pattern.
913 Collect(Pattern);
914 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
915
916 unsigned NumNamedPacks = Packs.size();
917
918 // Also look for unexpanded packs that are indirectly deduced by deducing
919 // the sizes of the packs in this pattern.
920 while (!ExtraDeductions.empty())
921 Collect(ExtraDeductions.pop_back_val());
922
923 return NumNamedPacks;
924 }
925
926 void finishConstruction(unsigned NumNamedPacks) {
927 // Dig out the partially-substituted pack, if there is one.
928 const TemplateArgument *PartialPackArgs = nullptr;
929 unsigned NumPartialPackArgs = 0;
930 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
931 if (auto *Scope = S.CurrentInstantiationScope)
932 if (auto *Partial = Scope->getPartiallySubstitutedPack(
933 &PartialPackArgs, &NumPartialPackArgs))
934 PartialPackDepthIndex = getDepthAndIndex(Partial);
935
936 // This pack expansion will have been partially or fully expanded if
937 // it only names explicitly-specified parameter packs (including the
938 // partially-substituted one, if any).
939 bool IsExpanded = true;
940 for (unsigned I = 0; I != NumNamedPacks; ++I) {
941 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
942 IsExpanded = false;
943 IsPartiallyExpanded = false;
944 break;
945 }
946 if (PartialPackDepthIndex ==
947 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
948 IsPartiallyExpanded = true;
949 }
950 }
951
952 // Skip over the pack elements that were expanded into separate arguments.
953 // If we partially expanded, this is the number of partial arguments.
954 if (IsPartiallyExpanded)
955 PackElements += NumPartialPackArgs;
956 else if (IsExpanded)
957 PackElements += *FixedNumExpansions;
958
959 for (auto &Pack : Packs) {
960 if (Info.PendingDeducedPacks.size() > Pack.Index)
961 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
962 else
963 Info.PendingDeducedPacks.resize(Pack.Index + 1);
964 Info.PendingDeducedPacks[Pack.Index] = &Pack;
965
966 if (PartialPackDepthIndex ==
967 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
968 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
969 // We pre-populate the deduced value of the partially-substituted
970 // pack with the specified value. This is not entirely correct: the
971 // value is supposed to have been substituted, not deduced, but the
972 // cases where this is observable require an exact type match anyway.
973 //
974 // FIXME: If we could represent a "depth i, index j, pack elem k"
975 // parameter, we could substitute the partially-substituted pack
976 // everywhere and avoid this.
977 if (!IsPartiallyExpanded)
978 Deduced[Pack.Index] = Pack.New[PackElements];
979 }
980 }
981 }
982
983public:
984 ~PackDeductionScope() {
985 for (auto &Pack : Packs)
986 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
987 }
988
989 // Return the size of the saved packs if all of them has the same size.
990 std::optional<unsigned> getSavedPackSizeIfAllEqual() const {
991 unsigned PackSize = Packs[0].Saved.pack_size();
992
993 if (std::all_of(Packs.begin() + 1, Packs.end(), [&PackSize](const auto &P) {
994 return P.Saved.pack_size() == PackSize;
995 }))
996 return PackSize;
997 return {};
998 }
999
1000 /// Determine whether this pack has already been deduced from a previous
1001 /// argument.
1002 bool isDeducedFromEarlierParameter() const {
1003 return DeducedFromEarlierParameter;
1004 }
1005
1006 /// Determine whether this pack has already been partially expanded into a
1007 /// sequence of (prior) function parameters / template arguments.
1008 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
1009
1010 /// Determine whether this pack expansion scope has a known, fixed arity.
1011 /// This happens if it involves a pack from an outer template that has
1012 /// (notionally) already been expanded.
1013 bool hasFixedArity() { return FixedNumExpansions.has_value(); }
1014
1015 /// Determine whether the next element of the argument is still part of this
1016 /// pack. This is the case unless the pack is already expanded to a fixed
1017 /// length.
1018 bool hasNextElement() {
1019 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
1020 }
1021
1022 /// Move to deducing the next element in each pack that is being deduced.
1023 void nextPackElement() {
1024 // Capture the deduced template arguments for each parameter pack expanded
1025 // by this pack expansion, add them to the list of arguments we've deduced
1026 // for that pack, then clear out the deduced argument.
1027 for (auto &Pack : Packs) {
1028 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
1029 if (!Pack.New.empty() || !DeducedArg.isNull()) {
1030 while (Pack.New.size() < PackElements)
1031 Pack.New.push_back(DeducedTemplateArgument());
1032 if (Pack.New.size() == PackElements)
1033 Pack.New.push_back(DeducedArg);
1034 else
1035 Pack.New[PackElements] = DeducedArg;
1036 DeducedArg = Pack.New.size() > PackElements + 1
1037 ? Pack.New[PackElements + 1]
1039 }
1040 }
1041 ++PackElements;
1042 }
1043
1044 /// Finish template argument deduction for a set of argument packs,
1045 /// producing the argument packs and checking for consistency with prior
1046 /// deductions.
1047 TemplateDeductionResult finish() {
1048 // Build argument packs for each of the parameter packs expanded by this
1049 // pack expansion.
1050 for (auto &Pack : Packs) {
1051 // Put back the old value for this pack.
1052 Deduced[Pack.Index] = Pack.Saved;
1053
1054 // Always make sure the size of this pack is correct, even if we didn't
1055 // deduce any values for it.
1056 //
1057 // FIXME: This isn't required by the normative wording, but substitution
1058 // and post-substitution checking will always fail if the arity of any
1059 // pack is not equal to the number of elements we processed. (Either that
1060 // or something else has gone *very* wrong.) We're permitted to skip any
1061 // hard errors from those follow-on steps by the intent (but not the
1062 // wording) of C++ [temp.inst]p8:
1063 //
1064 // If the function selected by overload resolution can be determined
1065 // without instantiating a class template definition, it is unspecified
1066 // whether that instantiation actually takes place
1067 Pack.New.resize(PackElements);
1068
1069 // Build or find a new value for this pack.
1071 if (Pack.New.empty()) {
1072 // If we deduced an empty argument pack, create it now.
1074 } else {
1075 TemplateArgument *ArgumentPack =
1076 new (S.Context) TemplateArgument[Pack.New.size()];
1077 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
1078 NewPack = DeducedTemplateArgument(
1079 TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())),
1080 // FIXME: This is wrong, it's possible that some pack elements are
1081 // deduced from an array bound and others are not:
1082 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
1083 // g({1, 2, 3}, {{}, {}});
1084 // ... should deduce T = {int, size_t (from array bound)}.
1085 Pack.New[0].wasDeducedFromArrayBound());
1086 }
1087
1088 // Pick where we're going to put the merged pack.
1090 if (Pack.Outer) {
1091 if (Pack.Outer->DeferredDeduction.isNull()) {
1092 // Defer checking this pack until we have a complete pack to compare
1093 // it against.
1094 Pack.Outer->DeferredDeduction = NewPack;
1095 continue;
1096 }
1097 Loc = &Pack.Outer->DeferredDeduction;
1098 } else {
1099 Loc = &Deduced[Pack.Index];
1100 }
1101
1102 // Check the new pack matches any previous value.
1103 DeducedTemplateArgument OldPack = *Loc;
1105 S.Context, OldPack, NewPack, DeducePackIfNotAlreadyDeduced);
1106
1107 Info.AggregateDeductionCandidateHasMismatchedArity =
1108 OldPack.getKind() == TemplateArgument::Pack &&
1109 NewPack.getKind() == TemplateArgument::Pack &&
1110 OldPack.pack_size() != NewPack.pack_size() && !Result.isNull();
1111
1112 // If we deferred a deduction of this pack, check that one now too.
1113 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
1114 OldPack = Result;
1115 NewPack = Pack.DeferredDeduction;
1116 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
1117 }
1118
1119 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
1120 if (Result.isNull()) {
1121 Info.Param = makeTemplateParameter(Param);
1122 Info.FirstArg = OldPack;
1123 Info.SecondArg = NewPack;
1124 return TemplateDeductionResult::Inconsistent;
1125 }
1126
1127 // If we have a pre-expanded pack and we didn't deduce enough elements
1128 // for it, fail deduction.
1129 if (std::optional<unsigned> Expansions = getExpandedPackSize(Param)) {
1130 if (*Expansions != PackElements) {
1131 Info.Param = makeTemplateParameter(Param);
1132 Info.FirstArg = Result;
1133 return TemplateDeductionResult::IncompletePack;
1134 }
1135 }
1136
1137 *Loc = Result;
1138 }
1139
1140 return TemplateDeductionResult::Success;
1141 }
1142
1143private:
1144 Sema &S;
1145 TemplateParameterList *TemplateParams;
1148 unsigned PackElements = 0;
1149 bool IsPartiallyExpanded = false;
1150 bool DeducePackIfNotAlreadyDeduced = false;
1151 bool DeducedFromEarlierParameter = false;
1152 /// The number of expansions, if we have a fully-expanded pack in this scope.
1153 std::optional<unsigned> FixedNumExpansions;
1154
1156};
1157
1158} // namespace
1159
1160/// Deduce the template arguments by comparing the list of parameter
1161/// types to the list of argument types, as in the parameter-type-lists of
1162/// function types (C++ [temp.deduct.type]p10).
1163///
1164/// \param S The semantic analysis object within which we are deducing
1165///
1166/// \param TemplateParams The template parameters that we are deducing
1167///
1168/// \param Params The list of parameter types
1169///
1170/// \param NumParams The number of types in \c Params
1171///
1172/// \param Args The list of argument types
1173///
1174/// \param NumArgs The number of types in \c Args
1175///
1176/// \param Info information about the template argument deduction itself
1177///
1178/// \param Deduced the deduced template arguments
1179///
1180/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1181/// how template argument deduction is performed.
1182///
1183/// \param PartialOrdering If true, we are performing template argument
1184/// deduction for during partial ordering for a call
1185/// (C++0x [temp.deduct.partial]).
1186///
1187/// \returns the result of template argument deduction so far. Note that a
1188/// "success" result means that template argument deduction has not yet failed,
1189/// but it may still fail, later, for other reasons.
1192 const QualType *Params, unsigned NumParams,
1193 const QualType *Args, unsigned NumArgs,
1196 unsigned TDF, bool PartialOrdering = false) {
1197 // C++0x [temp.deduct.type]p10:
1198 // Similarly, if P has a form that contains (T), then each parameter type
1199 // Pi of the respective parameter-type- list of P is compared with the
1200 // corresponding parameter type Ai of the corresponding parameter-type-list
1201 // of A. [...]
1202 unsigned ArgIdx = 0, ParamIdx = 0;
1203 for (; ParamIdx != NumParams; ++ParamIdx) {
1204 // Check argument types.
1205 const PackExpansionType *Expansion
1206 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1207 if (!Expansion) {
1208 // Simple case: compare the parameter and argument types at this point.
1209
1210 // Make sure we have an argument.
1211 if (ArgIdx >= NumArgs)
1212 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1213
1214 if (isa<PackExpansionType>(Args[ArgIdx])) {
1215 // C++0x [temp.deduct.type]p22:
1216 // If the original function parameter associated with A is a function
1217 // parameter pack and the function parameter associated with P is not
1218 // a function parameter pack, then template argument deduction fails.
1219 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1220 }
1221
1223 S, TemplateParams, Params[ParamIdx].getUnqualifiedType(),
1224 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, TDF,
1226 /*DeducedFromArrayBound=*/false);
1227 Result != TemplateDeductionResult::Success)
1228 return Result;
1229
1230 ++ArgIdx;
1231 continue;
1232 }
1233
1234 // C++0x [temp.deduct.type]p10:
1235 // If the parameter-declaration corresponding to Pi is a function
1236 // parameter pack, then the type of its declarator- id is compared with
1237 // each remaining parameter type in the parameter-type-list of A. Each
1238 // comparison deduces template arguments for subsequent positions in the
1239 // template parameter packs expanded by the function parameter pack.
1240
1241 QualType Pattern = Expansion->getPattern();
1242 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
1243
1244 // A pack scope with fixed arity is not really a pack any more, so is not
1245 // a non-deduced context.
1246 if (ParamIdx + 1 == NumParams || PackScope.hasFixedArity()) {
1247 for (; ArgIdx < NumArgs && PackScope.hasNextElement(); ++ArgIdx) {
1248 // Deduce template arguments from the pattern.
1250 S, TemplateParams, Pattern.getUnqualifiedType(),
1251 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, TDF,
1252 PartialOrdering, /*DeducedFromArrayBound=*/false);
1253 Result != TemplateDeductionResult::Success)
1254 return Result;
1255
1256 PackScope.nextPackElement();
1257 }
1258 } else {
1259 // C++0x [temp.deduct.type]p5:
1260 // The non-deduced contexts are:
1261 // - A function parameter pack that does not occur at the end of the
1262 // parameter-declaration-clause.
1263 //
1264 // FIXME: There is no wording to say what we should do in this case. We
1265 // choose to resolve this by applying the same rule that is applied for a
1266 // function call: that is, deduce all contained packs to their
1267 // explicitly-specified values (or to <> if there is no such value).
1268 //
1269 // This is seemingly-arbitrarily different from the case of a template-id
1270 // with a non-trailing pack-expansion in its arguments, which renders the
1271 // entire template-argument-list a non-deduced context.
1272
1273 // If the parameter type contains an explicitly-specified pack that we
1274 // could not expand, skip the number of parameters notionally created
1275 // by the expansion.
1276 std::optional<unsigned> NumExpansions = Expansion->getNumExpansions();
1277 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1278 for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs;
1279 ++I, ++ArgIdx)
1280 PackScope.nextPackElement();
1281 }
1282 }
1283
1284 // Build argument packs for each of the parameter packs expanded by this
1285 // pack expansion.
1286 if (auto Result = PackScope.finish();
1287 Result != TemplateDeductionResult::Success)
1288 return Result;
1289 }
1290
1291 // DR692, DR1395
1292 // C++0x [temp.deduct.type]p10:
1293 // If the parameter-declaration corresponding to P_i ...
1294 // During partial ordering, if Ai was originally a function parameter pack:
1295 // - if P does not contain a function parameter type corresponding to Ai then
1296 // Ai is ignored;
1297 if (PartialOrdering && ArgIdx + 1 == NumArgs &&
1298 isa<PackExpansionType>(Args[ArgIdx]))
1299 return TemplateDeductionResult::Success;
1300
1301 // Make sure we don't have any extra arguments.
1302 if (ArgIdx < NumArgs)
1303 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1304
1305 return TemplateDeductionResult::Success;
1306}
1307
1308/// Determine whether the parameter has qualifiers that the argument
1309/// lacks. Put another way, determine whether there is no way to add
1310/// a deduced set of qualifiers to the ParamType that would result in
1311/// its qualifiers matching those of the ArgType.
1313 QualType ArgType) {
1314 Qualifiers ParamQs = ParamType.getQualifiers();
1315 Qualifiers ArgQs = ArgType.getQualifiers();
1316
1317 if (ParamQs == ArgQs)
1318 return false;
1319
1320 // Mismatched (but not missing) Objective-C GC attributes.
1321 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1322 ParamQs.hasObjCGCAttr())
1323 return true;
1324
1325 // Mismatched (but not missing) address spaces.
1326 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1327 ParamQs.hasAddressSpace())
1328 return true;
1329
1330 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1331 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1332 ParamQs.hasObjCLifetime())
1333 return true;
1334
1335 // CVR qualifiers inconsistent or a superset.
1336 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1337}
1338
1340 const FunctionType *PF = P->getAs<FunctionType>(),
1341 *AF = A->getAs<FunctionType>();
1342
1343 // Just compare if not functions.
1344 if (!PF || !AF)
1345 return Context.hasSameType(P, A);
1346
1347 // Noreturn and noexcept adjustment.
1348 if (QualType AdjustedParam; IsFunctionConversion(P, A, AdjustedParam))
1349 P = AdjustedParam;
1350
1351 // FIXME: Compatible calling conventions.
1353}
1354
1355/// Get the index of the first template parameter that was originally from the
1356/// innermost template-parameter-list. This is 0 except when we concatenate
1357/// the template parameter lists of a class template and a constructor template
1358/// when forming an implicit deduction guide.
1360 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1361 if (!Guide || !Guide->isImplicit())
1362 return 0;
1363 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1364}
1365
1366/// Determine whether a type denotes a forwarding reference.
1367static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1368 // C++1z [temp.deduct.call]p3:
1369 // A forwarding reference is an rvalue reference to a cv-unqualified
1370 // template parameter that does not represent a template parameter of a
1371 // class template.
1372 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1373 if (ParamRef->getPointeeType().getQualifiers())
1374 return false;
1375 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1376 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1377 }
1378 return false;
1379}
1380
1382 return cast<CXXRecordDecl>(
1384}
1385
1386/// Attempt to deduce the template arguments by checking the base types
1387/// according to (C++20 [temp.deduct.call] p4b3.
1388///
1389/// \param S the semantic analysis object within which we are deducing.
1390///
1391/// \param RD the top level record object we are deducing against.
1392///
1393/// \param TemplateParams the template parameters that we are deducing.
1394///
1395/// \param P the template specialization parameter type.
1396///
1397/// \param Info information about the template argument deduction itself.
1398///
1399/// \param Deduced the deduced template arguments.
1400///
1401/// \returns the result of template argument deduction with the bases. "invalid"
1402/// means no matches, "success" found a single item, and the
1403/// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
1406 TemplateParameterList *TemplateParams, QualType P,
1409 // C++14 [temp.deduct.call] p4b3:
1410 // If P is a class and P has the form simple-template-id, then the
1411 // transformed A can be a derived class of the deduced A. Likewise if
1412 // P is a pointer to a class of the form simple-template-id, the
1413 // transformed A can be a pointer to a derived class pointed to by the
1414 // deduced A. However, if there is a class C that is a (direct or
1415 // indirect) base class of D and derived (directly or indirectly) from a
1416 // class B and that would be a valid deduced A, the deduced A cannot be
1417 // B or pointer to B, respectively.
1418 //
1419 // These alternatives are considered only if type deduction would
1420 // otherwise fail. If they yield more than one possible deduced A, the
1421 // type deduction fails.
1422
1423 // Use a breadth-first search through the bases to collect the set of
1424 // successful matches. Visited contains the set of nodes we have already
1425 // visited, while ToVisit is our stack of records that we still need to
1426 // visit. Matches contains a list of matches that have yet to be
1427 // disqualified.
1430 // We iterate over this later, so we have to use MapVector to ensure
1431 // determinism.
1432 llvm::MapVector<const CXXRecordDecl *,
1434 Matches;
1435
1436 auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
1437 for (const auto &Base : RD->bases()) {
1438 QualType T = Base.getType();
1439 assert(T->isRecordType() && "Base class that isn't a record?");
1440 if (Visited.insert(::getCanonicalRD(T)).second)
1441 ToVisit.push_back(T);
1442 }
1443 };
1444
1445 // Set up the loop by adding all the bases.
1446 AddBases(RD);
1447
1448 // Search each path of bases until we either run into a successful match
1449 // (where all bases of it are invalid), or we run out of bases.
1450 while (!ToVisit.empty()) {
1451 QualType NextT = ToVisit.pop_back_val();
1452
1453 SmallVector<DeducedTemplateArgument, 8> DeducedCopy(Deduced.begin(),
1454 Deduced.end());
1457 S, TemplateParams, P, NextT, BaseInfo, DeducedCopy);
1458
1459 // If this was a successful deduction, add it to the list of matches,
1460 // otherwise we need to continue searching its bases.
1461 const CXXRecordDecl *RD = ::getCanonicalRD(NextT);
1463 Matches.insert({RD, DeducedCopy});
1464 else
1465 AddBases(RD);
1466 }
1467
1468 // At this point, 'Matches' contains a list of seemingly valid bases, however
1469 // in the event that we have more than 1 match, it is possible that the base
1470 // of one of the matches might be disqualified for being a base of another
1471 // valid match. We can count on cyclical instantiations being invalid to
1472 // simplify the disqualifications. That is, if A & B are both matches, and B
1473 // inherits from A (disqualifying A), we know that A cannot inherit from B.
1474 if (Matches.size() > 1) {
1475 Visited.clear();
1476 for (const auto &Match : Matches)
1477 AddBases(Match.first);
1478
1479 // We can give up once we have a single item (or have run out of things to
1480 // search) since cyclical inheritance isn't valid.
1481 while (Matches.size() > 1 && !ToVisit.empty()) {
1482 const CXXRecordDecl *RD = ::getCanonicalRD(ToVisit.pop_back_val());
1483 Matches.erase(RD);
1484
1485 // Always add all bases, since the inheritance tree can contain
1486 // disqualifications for multiple matches.
1487 AddBases(RD);
1488 }
1489 }
1490
1491 if (Matches.empty())
1493 if (Matches.size() > 1)
1495
1496 std::swap(Matches.front().second, Deduced);
1498}
1499
1500/// Deduce the template arguments by comparing the parameter type and
1501/// the argument type (C++ [temp.deduct.type]).
1502///
1503/// \param S the semantic analysis object within which we are deducing
1504///
1505/// \param TemplateParams the template parameters that we are deducing
1506///
1507/// \param P the parameter type
1508///
1509/// \param A the argument type
1510///
1511/// \param Info information about the template argument deduction itself
1512///
1513/// \param Deduced the deduced template arguments
1514///
1515/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1516/// how template argument deduction is performed.
1517///
1518/// \param PartialOrdering Whether we're performing template argument deduction
1519/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1520///
1521/// \returns the result of template argument deduction so far. Note that a
1522/// "success" result means that template argument deduction has not yet failed,
1523/// but it may still fail, later, for other reasons.
1525 Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
1527 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1528 bool PartialOrdering, bool DeducedFromArrayBound) {
1529
1530 // If the argument type is a pack expansion, look at its pattern.
1531 // This isn't explicitly called out
1532 if (const auto *AExp = dyn_cast<PackExpansionType>(A))
1533 A = AExp->getPattern();
1534 assert(!isa<PackExpansionType>(A.getCanonicalType()));
1535
1536 if (PartialOrdering) {
1537 // C++11 [temp.deduct.partial]p5:
1538 // Before the partial ordering is done, certain transformations are
1539 // performed on the types used for partial ordering:
1540 // - If P is a reference type, P is replaced by the type referred to.
1541 const ReferenceType *PRef = P->getAs<ReferenceType>();
1542 if (PRef)
1543 P = PRef->getPointeeType();
1544
1545 // - If A is a reference type, A is replaced by the type referred to.
1546 const ReferenceType *ARef = A->getAs<ReferenceType>();
1547 if (ARef)
1548 A = A->getPointeeType();
1549
1550 if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
1551 // C++11 [temp.deduct.partial]p9:
1552 // If, for a given type, deduction succeeds in both directions (i.e.,
1553 // the types are identical after the transformations above) and both
1554 // P and A were reference types [...]:
1555 // - if [one type] was an lvalue reference and [the other type] was
1556 // not, [the other type] is not considered to be at least as
1557 // specialized as [the first type]
1558 // - if [one type] is more cv-qualified than [the other type],
1559 // [the other type] is not considered to be at least as specialized
1560 // as [the first type]
1561 // Objective-C ARC adds:
1562 // - [one type] has non-trivial lifetime, [the other type] has
1563 // __unsafe_unretained lifetime, and the types are otherwise
1564 // identical
1565 //
1566 // A is "considered to be at least as specialized" as P iff deduction
1567 // succeeds, so we model this as a deduction failure. Note that
1568 // [the first type] is P and [the other type] is A here; the standard
1569 // gets this backwards.
1570 Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
1571 if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
1572 PQuals.isStrictSupersetOf(AQuals) ||
1573 (PQuals.hasNonTrivialObjCLifetime() &&
1574 AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1575 PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
1576 Info.FirstArg = TemplateArgument(P);
1577 Info.SecondArg = TemplateArgument(A);
1579 }
1580 }
1581 Qualifiers DiscardedQuals;
1582 // C++11 [temp.deduct.partial]p7:
1583 // Remove any top-level cv-qualifiers:
1584 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1585 // version of P.
1586 P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
1587 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1588 // version of A.
1589 A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
1590 } else {
1591 // C++0x [temp.deduct.call]p4 bullet 1:
1592 // - If the original P is a reference type, the deduced A (i.e., the type
1593 // referred to by the reference) can be more cv-qualified than the
1594 // transformed A.
1595 if (TDF & TDF_ParamWithReferenceType) {
1596 Qualifiers Quals;
1597 QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
1599 P = S.Context.getQualifiedType(UnqualP, Quals);
1600 }
1601
1602 if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
1603 // C++0x [temp.deduct.type]p10:
1604 // If P and A are function types that originated from deduction when
1605 // taking the address of a function template (14.8.2.2) or when deducing
1606 // template arguments from a function declaration (14.8.2.6) and Pi and
1607 // Ai are parameters of the top-level parameter-type-list of P and A,
1608 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1609 // is an lvalue reference, in
1610 // which case the type of Pi is changed to be the template parameter
1611 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1612 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1613 // deduced as X&. - end note ]
1614 TDF &= ~TDF_TopLevelParameterTypeList;
1615 if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
1617 P = P->getPointeeType();
1618 }
1619 }
1620
1621 // C++ [temp.deduct.type]p9:
1622 // A template type argument T, a template template argument TT or a
1623 // template non-type argument i can be deduced if P and A have one of
1624 // the following forms:
1625 //
1626 // T
1627 // cv-list T
1628 if (const auto *TTP = P->getAs<TemplateTypeParmType>()) {
1629 // Just skip any attempts to deduce from a placeholder type or a parameter
1630 // at a different depth.
1631 if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
1633
1634 unsigned Index = TTP->getIndex();
1635
1636 // If the argument type is an array type, move the qualifiers up to the
1637 // top level, so they can be matched with the qualifiers on the parameter.
1638 if (A->isArrayType()) {
1639 Qualifiers Quals;
1640 A = S.Context.getUnqualifiedArrayType(A, Quals);
1641 if (Quals)
1642 A = S.Context.getQualifiedType(A, Quals);
1643 }
1644
1645 // The argument type can not be less qualified than the parameter
1646 // type.
1647 if (!(TDF & TDF_IgnoreQualifiers) &&
1649 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1650 Info.FirstArg = TemplateArgument(P);
1651 Info.SecondArg = TemplateArgument(A);
1653 }
1654
1655 // Do not match a function type with a cv-qualified type.
1656 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1657 if (A->isFunctionType() && P.hasQualifiers())
1659
1660 assert(TTP->getDepth() == Info.getDeducedDepth() &&
1661 "saw template type parameter with wrong depth");
1662 assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&
1663 "Unresolved overloaded function");
1665
1666 // Remove any qualifiers on the parameter from the deduced type.
1667 // We checked the qualifiers for consistency above.
1668 Qualifiers DeducedQs = DeducedType.getQualifiers();
1669 Qualifiers ParamQs = P.getQualifiers();
1670 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1671 if (ParamQs.hasObjCGCAttr())
1672 DeducedQs.removeObjCGCAttr();
1673 if (ParamQs.hasAddressSpace())
1674 DeducedQs.removeAddressSpace();
1675 if (ParamQs.hasObjCLifetime())
1676 DeducedQs.removeObjCLifetime();
1677
1678 // Objective-C ARC:
1679 // If template deduction would produce a lifetime qualifier on a type
1680 // that is not a lifetime type, template argument deduction fails.
1681 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1683 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1684 Info.FirstArg = TemplateArgument(P);
1685 Info.SecondArg = TemplateArgument(A);
1687 }
1688
1689 // Objective-C ARC:
1690 // If template deduction would produce an argument type with lifetime type
1691 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1692 if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
1693 !DeducedQs.hasObjCLifetime())
1695
1696 DeducedType =
1697 S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
1698
1699 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1701 checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
1702 if (Result.isNull()) {
1703 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1704 Info.FirstArg = Deduced[Index];
1705 Info.SecondArg = NewDeduced;
1707 }
1708
1709 Deduced[Index] = Result;
1711 }
1712
1713 // Set up the template argument deduction information for a failure.
1714 Info.FirstArg = TemplateArgument(P);
1715 Info.SecondArg = TemplateArgument(A);
1716
1717 // If the parameter is an already-substituted template parameter
1718 // pack, do nothing: we don't know which of its arguments to look
1719 // at, so we have to wait until all of the parameter packs in this
1720 // expansion have arguments.
1721 if (P->getAs<SubstTemplateTypeParmPackType>())
1723
1724 // Check the cv-qualifiers on the parameter and argument types.
1725 if (!(TDF & TDF_IgnoreQualifiers)) {
1726 if (TDF & TDF_ParamWithReferenceType) {
1729 } else if (TDF & TDF_ArgWithReferenceType) {
1730 // C++ [temp.deduct.conv]p4:
1731 // If the original A is a reference type, A can be more cv-qualified
1732 // than the deduced A
1733 if (!A.getQualifiers().compatiblyIncludes(P.getQualifiers()))
1735
1736 // Strip out all extra qualifiers from the argument to figure out the
1737 // type we're converting to, prior to the qualification conversion.
1738 Qualifiers Quals;
1739 A = S.Context.getUnqualifiedArrayType(A, Quals);
1740 A = S.Context.getQualifiedType(A, P.getQualifiers());
1741 } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
1742 if (P.getCVRQualifiers() != A.getCVRQualifiers())
1744 }
1745 }
1746
1747 // If the parameter type is not dependent, there is nothing to deduce.
1748 if (!P->isDependentType()) {
1749 if (TDF & TDF_SkipNonDependent)
1752 : S.Context.hasSameType(P, A))
1757 if (!(TDF & TDF_IgnoreQualifiers))
1759 // Otherwise, when ignoring qualifiers, the types not having the same
1760 // unqualified type does not mean they do not match, so in this case we
1761 // must keep going and analyze with a non-dependent parameter type.
1762 }
1763
1764 switch (P.getCanonicalType()->getTypeClass()) {
1765 // Non-canonical types cannot appear here.
1766#define NON_CANONICAL_TYPE(Class, Base) \
1767 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1768#define TYPE(Class, Base)
1769#include "clang/AST/TypeNodes.inc"
1770
1771 case Type::TemplateTypeParm:
1772 case Type::SubstTemplateTypeParmPack:
1773 llvm_unreachable("Type nodes handled above");
1774
1775 case Type::Auto:
1776 // C++23 [temp.deduct.funcaddr]/3:
1777 // A placeholder type in the return type of a function template is a
1778 // non-deduced context.
1779 // There's no corresponding wording for [temp.deduct.decl], but we treat
1780 // it the same to match other compilers.
1781 if (P->isDependentType())
1783 [[fallthrough]];
1784 case Type::Builtin:
1785 case Type::VariableArray:
1786 case Type::Vector:
1787 case Type::FunctionNoProto:
1788 case Type::Record:
1789 case Type::Enum:
1790 case Type::ObjCObject:
1791 case Type::ObjCInterface:
1792 case Type::ObjCObjectPointer:
1793 case Type::BitInt:
1794 return (TDF & TDF_SkipNonDependent) ||
1795 ((TDF & TDF_IgnoreQualifiers)
1797 : S.Context.hasSameType(P, A))
1800
1801 // _Complex T [placeholder extension]
1802 case Type::Complex: {
1803 const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
1804 if (!CA)
1807 S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
1808 Deduced, TDF);
1809 }
1810
1811 // _Atomic T [extension]
1812 case Type::Atomic: {
1813 const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
1814 if (!AA)
1817 S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
1818 Deduced, TDF);
1819 }
1820
1821 // T *
1822 case Type::Pointer: {
1823 QualType PointeeType;
1824 if (const auto *PA = A->getAs<PointerType>()) {
1825 PointeeType = PA->getPointeeType();
1826 } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
1827 PointeeType = PA->getPointeeType();
1828 } else {
1830 }
1832 S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
1833 PointeeType, Info, Deduced,
1835 }
1836
1837 // T &
1838 case Type::LValueReference: {
1839 const auto *RP = P->castAs<LValueReferenceType>(),
1840 *RA = A->getAs<LValueReferenceType>();
1841 if (!RA)
1843
1845 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1846 Deduced, 0);
1847 }
1848
1849 // T && [C++0x]
1850 case Type::RValueReference: {
1851 const auto *RP = P->castAs<RValueReferenceType>(),
1852 *RA = A->getAs<RValueReferenceType>();
1853 if (!RA)
1855
1857 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1858 Deduced, 0);
1859 }
1860
1861 // T [] (implied, but not stated explicitly)
1862 case Type::IncompleteArray: {
1863 const auto *IAA = S.Context.getAsIncompleteArrayType(A);
1864 if (!IAA)
1866
1867 const auto *IAP = S.Context.getAsIncompleteArrayType(P);
1868 assert(IAP && "Template parameter not of incomplete array type");
1869
1871 S, TemplateParams, IAP->getElementType(), IAA->getElementType(), Info,
1872 Deduced, TDF & TDF_IgnoreQualifiers);
1873 }
1874
1875 // T [integer-constant]
1876 case Type::ConstantArray: {
1877 const auto *CAA = S.Context.getAsConstantArrayType(A),
1879 assert(CAP);
1880 if (!CAA || CAA->getSize() != CAP->getSize())
1882
1884 S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
1885 Deduced, TDF & TDF_IgnoreQualifiers);
1886 }
1887
1888 // type [i]
1889 case Type::DependentSizedArray: {
1890 const auto *AA = S.Context.getAsArrayType(A);
1891 if (!AA)
1893
1894 // Check the element type of the arrays
1895 const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
1896 assert(DAP);
1898 S, TemplateParams, DAP->getElementType(), AA->getElementType(),
1899 Info, Deduced, TDF & TDF_IgnoreQualifiers);
1901 return Result;
1902
1903 // Determine the array bound is something we can deduce.
1904 const NonTypeTemplateParmDecl *NTTP =
1905 getDeducedParameterFromExpr(Info, DAP->getSizeExpr());
1906 if (!NTTP)
1908
1909 // We can perform template argument deduction for the given non-type
1910 // template parameter.
1911 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1912 "saw non-type template parameter with wrong depth");
1913 if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
1914 llvm::APSInt Size(CAA->getSize());
1916 S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
1917 /*ArrayBound=*/true, Info, Deduced);
1918 }
1919 if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
1920 if (DAA->getSizeExpr())
1922 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info, Deduced);
1923
1924 // Incomplete type does not match a dependently-sized array type
1926 }
1927
1928 // type(*)(T)
1929 // T(*)()
1930 // T(*)(T)
1931 case Type::FunctionProto: {
1932 const auto *FPP = P->castAs<FunctionProtoType>(),
1933 *FPA = A->getAs<FunctionProtoType>();
1934 if (!FPA)
1936
1937 if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
1938 FPP->getRefQualifier() != FPA->getRefQualifier() ||
1939 FPP->isVariadic() != FPA->isVariadic())
1941
1942 // Check return types.
1944 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
1945 Info, Deduced, 0,
1946 /*PartialOrdering=*/false,
1947 /*DeducedFromArrayBound=*/false);
1949 return Result;
1950
1951 // Check parameter types.
1953 S, TemplateParams, FPP->param_type_begin(), FPP->getNumParams(),
1954 FPA->param_type_begin(), FPA->getNumParams(), Info, Deduced,
1957 return Result;
1958
1961
1962 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1963 // deducing through the noexcept-specifier if it's part of the canonical
1964 // type. libstdc++ relies on this.
1965 Expr *NoexceptExpr = FPP->getNoexceptExpr();
1966 if (const NonTypeTemplateParmDecl *NTTP =
1967 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
1968 : nullptr) {
1969 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1970 "saw non-type template parameter with wrong depth");
1971
1972 llvm::APSInt Noexcept(1);
1973 switch (FPA->canThrow()) {
1974 case CT_Cannot:
1975 Noexcept = 1;
1976 [[fallthrough]];
1977
1978 case CT_Can:
1979 // We give E in noexcept(E) the "deduced from array bound" treatment.
1980 // FIXME: Should we?
1982 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
1983 /*DeducedFromArrayBound=*/true, Info, Deduced);
1984
1985 case CT_Dependent:
1986 if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
1988 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
1989 // Can't deduce anything from throw(T...).
1990 break;
1991 }
1992 }
1993 // FIXME: Detect non-deduced exception specification mismatches?
1994 //
1995 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
1996 // top-level differences in noexcept-specifications.
1997
1999 }
2000
2001 case Type::InjectedClassName:
2002 // Treat a template's injected-class-name as if the template
2003 // specialization type had been used.
2004
2005 // template-name<T> (where template-name refers to a class template)
2006 // template-name<i>
2007 // TT<T>
2008 // TT<i>
2009 // TT<>
2010 case Type::TemplateSpecialization: {
2011 // When Arg cannot be a derived class, we can just try to deduce template
2012 // arguments from the template-id.
2013 if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
2014 return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
2015 Deduced);
2016
2017 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
2018 Deduced.end());
2019
2020 auto Result =
2021 DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info, Deduced);
2023 return Result;
2024
2025 // We cannot inspect base classes as part of deduction when the type
2026 // is incomplete, so either instantiate any templates necessary to
2027 // complete the type, or skip over it if it cannot be completed.
2028 if (!S.isCompleteType(Info.getLocation(), A))
2029 return Result;
2030
2031 if (getCanonicalRD(A)->isInvalidDecl())
2032 return Result;
2033
2034 // Reset the incorrectly deduced argument from above.
2035 Deduced = DeducedOrig;
2036
2037 // Check bases according to C++14 [temp.deduct.call] p4b3:
2039 TemplateParams, P, Info, Deduced);
2041 : Result;
2042 }
2043
2044 // T type::*
2045 // T T::*
2046 // T (type::*)()
2047 // type (T::*)()
2048 // type (type::*)(T)
2049 // type (T::*)(T)
2050 // T (type::*)(T)
2051 // T (T::*)()
2052 // T (T::*)(T)
2053 case Type::MemberPointer: {
2054 const auto *MPP = P->castAs<MemberPointerType>(),
2055 *MPA = A->getAs<MemberPointerType>();
2056 if (!MPA)
2058
2059 QualType PPT = MPP->getPointeeType();
2060 if (PPT->isFunctionType())
2061 S.adjustMemberFunctionCC(PPT, /*HasThisPointer=*/false,
2062 /*IsCtorOrDtor=*/false, Info.getLocation());
2063 QualType APT = MPA->getPointeeType();
2064 if (APT->isFunctionType())
2065 S.adjustMemberFunctionCC(APT, /*HasThisPointer=*/false,
2066 /*IsCtorOrDtor=*/false, Info.getLocation());
2067
2068 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
2070 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF);
2072 return Result;
2074 S, TemplateParams, QualType(MPP->getClass(), 0),
2075 QualType(MPA->getClass(), 0), Info, Deduced, SubTDF);
2076 }
2077
2078 // (clang extension)
2079 //
2080 // type(^)(T)
2081 // T(^)()
2082 // T(^)(T)
2083 case Type::BlockPointer: {
2084 const auto *BPP = P->castAs<BlockPointerType>(),
2085 *BPA = A->getAs<BlockPointerType>();
2086 if (!BPA)
2089 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
2090 Deduced, 0);
2091 }
2092
2093 // (clang extension)
2094 //
2095 // T __attribute__(((ext_vector_type(<integral constant>))))
2096 case Type::ExtVector: {
2097 const auto *VP = P->castAs<ExtVectorType>();
2098 QualType ElementType;
2099 if (const auto *VA = A->getAs<ExtVectorType>()) {
2100 // Make sure that the vectors have the same number of elements.
2101 if (VP->getNumElements() != VA->getNumElements())
2103 ElementType = VA->getElementType();
2104 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2105 // We can't check the number of elements, since the argument has a
2106 // dependent number of elements. This can only occur during partial
2107 // ordering.
2108 ElementType = VA->getElementType();
2109 } else {
2111 }
2112 // Perform deduction on the element types.
2114 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
2115 TDF);
2116 }
2117
2118 case Type::DependentVector: {
2119 const auto *VP = P->castAs<DependentVectorType>();
2120
2121 if (const auto *VA = A->getAs<VectorType>()) {
2122 // Perform deduction on the element types.
2124 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2125 Info, Deduced, TDF);
2127 return Result;
2128
2129 // Perform deduction on the vector size, if we can.
2130 const NonTypeTemplateParmDecl *NTTP =
2131 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2132 if (!NTTP)
2134
2135 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2136 ArgSize = VA->getNumElements();
2137 // Note that we use the "array bound" rules here; just like in that
2138 // case, we don't have any particular type for the vector size, but
2139 // we can provide one if necessary.
2140 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2141 S.Context.UnsignedIntTy, true,
2142 Info, Deduced);
2143 }
2144
2145 if (const auto *VA = A->getAs<DependentVectorType>()) {
2146 // Perform deduction on the element types.
2148 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2149 Info, Deduced, TDF);
2151 return Result;
2152
2153 // Perform deduction on the vector size, if we can.
2154 const NonTypeTemplateParmDecl *NTTP =
2155 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2156 if (!NTTP)
2158
2159 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2160 VA->getSizeExpr(), Info, Deduced);
2161 }
2162
2164 }
2165
2166 // (clang extension)
2167 //
2168 // T __attribute__(((ext_vector_type(N))))
2169 case Type::DependentSizedExtVector: {
2170 const auto *VP = P->castAs<DependentSizedExtVectorType>();
2171
2172 if (const auto *VA = A->getAs<ExtVectorType>()) {
2173 // Perform deduction on the element types.
2175 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2176 Info, Deduced, TDF);
2178 return Result;
2179
2180 // Perform deduction on the vector size, if we can.
2181 const NonTypeTemplateParmDecl *NTTP =
2182 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2183 if (!NTTP)
2185
2186 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2187 ArgSize = VA->getNumElements();
2188 // Note that we use the "array bound" rules here; just like in that
2189 // case, we don't have any particular type for the vector size, but
2190 // we can provide one if necessary.
2191 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2192 S.Context.IntTy, true, Info,
2193 Deduced);
2194 }
2195
2196 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2197 // Perform deduction on the element types.
2199 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2200 Info, Deduced, TDF);
2202 return Result;
2203
2204 // Perform deduction on the vector size, if we can.
2205 const NonTypeTemplateParmDecl *NTTP =
2206 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2207 if (!NTTP)
2209
2210 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2211 VA->getSizeExpr(), Info, Deduced);
2212 }
2213
2215 }
2216
2217 // (clang extension)
2218 //
2219 // T __attribute__((matrix_type(<integral constant>,
2220 // <integral constant>)))
2221 case Type::ConstantMatrix: {
2222 const auto *MP = P->castAs<ConstantMatrixType>(),
2223 *MA = A->getAs<ConstantMatrixType>();
2224 if (!MA)
2226
2227 // Check that the dimensions are the same
2228 if (MP->getNumRows() != MA->getNumRows() ||
2229 MP->getNumColumns() != MA->getNumColumns()) {
2231 }
2232 // Perform deduction on element types.
2234 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2235 Deduced, TDF);
2236 }
2237
2238 case Type::DependentSizedMatrix: {
2239 const auto *MP = P->castAs<DependentSizedMatrixType>();
2240 const auto *MA = A->getAs<MatrixType>();
2241 if (!MA)
2243
2244 // Check the element type of the matrixes.
2246 S, TemplateParams, MP->getElementType(), MA->getElementType(),
2247 Info, Deduced, TDF);
2249 return Result;
2250
2251 // Try to deduce a matrix dimension.
2252 auto DeduceMatrixArg =
2253 [&S, &Info, &Deduced, &TemplateParams](
2254 Expr *ParamExpr, const MatrixType *A,
2255 unsigned (ConstantMatrixType::*GetArgDimension)() const,
2256 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2257 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2258 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
2259 if (!ParamExpr->isValueDependent()) {
2260 std::optional<llvm::APSInt> ParamConst =
2261 ParamExpr->getIntegerConstantExpr(S.Context);
2262 if (!ParamConst)
2264
2265 if (ACM) {
2266 if ((ACM->*GetArgDimension)() == *ParamConst)
2269 }
2270
2271 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2272 if (std::optional<llvm::APSInt> ArgConst =
2273 ArgExpr->getIntegerConstantExpr(S.Context))
2274 if (*ArgConst == *ParamConst)
2277 }
2278
2279 const NonTypeTemplateParmDecl *NTTP =
2280 getDeducedParameterFromExpr(Info, ParamExpr);
2281 if (!NTTP)
2283
2284 if (ACM) {
2285 llvm::APSInt ArgConst(
2287 ArgConst = (ACM->*GetArgDimension)();
2289 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
2290 /*ArrayBound=*/true, Info, Deduced);
2291 }
2292
2293 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2294 (ADM->*GetArgDimensionExpr)(),
2295 Info, Deduced);
2296 };
2297
2298 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
2302 return Result;
2303
2304 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2307 }
2308
2309 // (clang extension)
2310 //
2311 // T __attribute__(((address_space(N))))
2312 case Type::DependentAddressSpace: {
2313 const auto *ASP = P->castAs<DependentAddressSpaceType>();
2314
2315 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
2316 // Perform deduction on the pointer type.
2318 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2319 Info, Deduced, TDF);
2321 return Result;
2322
2323 // Perform deduction on the address space, if we can.
2324 const NonTypeTemplateParmDecl *NTTP =
2325 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2326 if (!NTTP)
2328
2330 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info, Deduced);
2331 }
2332
2334 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2335 false);
2336 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
2337
2338 // Perform deduction on the pointer types.
2340 S, TemplateParams, ASP->getPointeeType(),
2341 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF);
2343 return Result;
2344
2345 // Perform deduction on the address space, if we can.
2346 const NonTypeTemplateParmDecl *NTTP =
2347 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2348 if (!NTTP)
2350
2351 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2352 ArgAddressSpace, S.Context.IntTy,
2353 true, Info, Deduced);
2354 }
2355
2357 }
2358 case Type::DependentBitInt: {
2359 const auto *IP = P->castAs<DependentBitIntType>();
2360
2361 if (const auto *IA = A->getAs<BitIntType>()) {
2362 if (IP->isUnsigned() != IA->isUnsigned())
2364
2365 const NonTypeTemplateParmDecl *NTTP =
2366 getDeducedParameterFromExpr(Info, IP->getNumBitsExpr());
2367 if (!NTTP)
2369
2370 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2371 ArgSize = IA->getNumBits();
2372
2373 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2374 S.Context.IntTy, true, Info,
2375 Deduced);
2376 }
2377
2378 if (const auto *IA = A->getAs<DependentBitIntType>()) {
2379 if (IP->isUnsigned() != IA->isUnsigned())
2382 }
2383
2385 }
2386
2387 case Type::TypeOfExpr:
2388 case Type::TypeOf:
2389 case Type::DependentName:
2390 case Type::UnresolvedUsing:
2391 case Type::Decltype:
2392 case Type::UnaryTransform:
2393 case Type::DeducedTemplateSpecialization:
2394 case Type::DependentTemplateSpecialization:
2395 case Type::PackExpansion:
2396 case Type::Pipe:
2397 case Type::ArrayParameter:
2398 // No template argument deduction for these types
2400
2401 case Type::PackIndexing: {
2402 const PackIndexingType *PIT = P->getAs<PackIndexingType>();
2403 if (PIT->hasSelectedType()) {
2405 S, TemplateParams, PIT->getSelectedType(), A, Info, Deduced, TDF);
2406 }
2408 }
2409 }
2410
2411 llvm_unreachable("Invalid Type Class!");
2412}
2413
2419 // If the template argument is a pack expansion, perform template argument
2420 // deduction against the pattern of that expansion. This only occurs during
2421 // partial ordering.
2422 if (A.isPackExpansion())
2424
2425 switch (P.getKind()) {
2427 llvm_unreachable("Null template argument in parameter list");
2428
2432 S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0);
2433 Info.FirstArg = P;
2434 Info.SecondArg = A;
2436
2439 return DeduceTemplateArguments(S, TemplateParams, P.getAsTemplate(),
2440 A.getAsTemplate(), Info,
2441 /*DefaultArguments=*/{}, Deduced);
2442 Info.FirstArg = P;
2443 Info.SecondArg = A;
2445
2447 llvm_unreachable("caller should handle pack expansions");
2448
2451 isSameDeclaration(P.getAsDecl(), A.getAsDecl()))
2453
2454 Info.FirstArg = P;
2455 Info.SecondArg = A;
2457
2460 S.Context.hasSameType(P.getNullPtrType(), A.getNullPtrType()))
2462
2463 Info.FirstArg = P;
2464 Info.SecondArg = A;
2466
2469 if (hasSameExtendedValue(P.getAsIntegral(), A.getAsIntegral()))
2471 }
2472 Info.FirstArg = P;
2473 Info.SecondArg = A;
2475
2480
2481 Info.FirstArg = P;
2482 Info.SecondArg = A;
2484
2486 if (const NonTypeTemplateParmDecl *NTTP =
2487 getDeducedParameterFromExpr(Info, P.getAsExpr())) {
2488 switch (A.getKind()) {
2493 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2494 A.getNonTypeTemplateArgumentType(), Info, Deduced);
2495
2497 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
2498 A.getNullPtrType(), Info, Deduced);
2499
2502 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
2503 Info, Deduced);
2504
2510 Info.FirstArg = P;
2511 Info.SecondArg = A;
2513 }
2514 llvm_unreachable("Unknown template argument kind");
2515 }
2516
2517 // Can't deduce anything, but that's okay.
2520 llvm_unreachable("Argument packs should be expanded by the caller!");
2521 }
2522
2523 llvm_unreachable("Invalid TemplateArgument Kind!");
2524}
2525
2526/// Determine whether there is a template argument to be used for
2527/// deduction.
2528///
2529/// This routine "expands" argument packs in-place, overriding its input
2530/// parameters so that \c Args[ArgIdx] will be the available template argument.
2531///
2532/// \returns true if there is another template argument (which will be at
2533/// \c Args[ArgIdx]), false otherwise.
2535 unsigned &ArgIdx) {
2536 if (ArgIdx == Args.size())
2537 return false;
2538
2539 const TemplateArgument &Arg = Args[ArgIdx];
2540 if (Arg.getKind() != TemplateArgument::Pack)
2541 return true;
2542
2543 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2544 Args = Arg.pack_elements();
2545 ArgIdx = 0;
2546 return ArgIdx < Args.size();
2547}
2548
2549/// Determine whether the given set of template arguments has a pack
2550/// expansion that is not the last template argument.
2552 bool FoundPackExpansion = false;
2553 for (const auto &A : Args) {
2554 if (FoundPackExpansion)
2555 return true;
2556
2557 if (A.getKind() == TemplateArgument::Pack)
2558 return hasPackExpansionBeforeEnd(A.pack_elements());
2559
2560 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2561 // templates, it should not be treated as a pack expansion.
2562 if (A.isPackExpansion())
2563 FoundPackExpansion = true;
2564 }
2565
2566 return false;
2567}
2568
2575 bool NumberOfArgumentsMustMatch, PackFold PackFold) {
2576 if (PackFold == PackFold::ArgumentToParameter)
2577 std::swap(Ps, As);
2578 // C++0x [temp.deduct.type]p9:
2579 // If the template argument list of P contains a pack expansion that is not
2580 // the last template argument, the entire template argument list is a
2581 // non-deduced context.
2584
2585 // C++0x [temp.deduct.type]p9:
2586 // If P has a form that contains <T> or <i>, then each argument Pi of the
2587 // respective template argument list P is compared with the corresponding
2588 // argument Ai of the corresponding template argument list of A.
2589 unsigned ArgIdx = 0, ParamIdx = 0;
2591 const TemplateArgument &P = Ps[ParamIdx];
2592 if (!P.isPackExpansion()) {
2593 // The simple case: deduce template arguments by matching Pi and Ai.
2594
2595 // Check whether we have enough arguments.
2596 if (!hasTemplateArgumentForDeduction(As, ArgIdx))
2597 return NumberOfArgumentsMustMatch
2600
2601 // C++1z [temp.deduct.type]p9:
2602 // During partial ordering, if Ai was originally a pack expansion [and]
2603 // Pi is not a pack expansion, template argument deduction fails.
2604 if (As[ArgIdx].isPackExpansion())
2606
2607 // Perform deduction for this Pi/Ai pair.
2608 TemplateArgument Pi = P, Ai = As[ArgIdx];
2609 if (PackFold == PackFold::ArgumentToParameter)
2610 std::swap(Pi, Ai);
2611 if (auto Result =
2612 DeduceTemplateArguments(S, TemplateParams, Pi, Ai, Info, Deduced);
2614 return Result;
2615
2616 // Move to the next argument.
2617 ++ArgIdx;
2618 continue;
2619 }
2620
2621 // The parameter is a pack expansion.
2622
2623 // C++0x [temp.deduct.type]p9:
2624 // If Pi is a pack expansion, then the pattern of Pi is compared with
2625 // each remaining argument in the template argument list of A. Each
2626 // comparison deduces template arguments for subsequent positions in the
2627 // template parameter packs expanded by Pi.
2628 TemplateArgument Pattern = P.getPackExpansionPattern();
2629
2630 // Prepare to deduce the packs within the pattern.
2631 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2632
2633 // Keep track of the deduced template arguments for each parameter pack
2634 // expanded by this pack expansion (the outer index) and for each
2635 // template argument (the inner SmallVectors).
2636 for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
2637 PackScope.hasNextElement();
2638 ++ArgIdx) {
2639 TemplateArgument Pi = Pattern, Ai = As[ArgIdx];
2640 if (PackFold == PackFold::ArgumentToParameter)
2641 std::swap(Pi, Ai);
2642 // Deduce template arguments from the pattern.
2643 if (auto Result =
2644 DeduceTemplateArguments(S, TemplateParams, Pi, Ai, Info, Deduced);
2646 return Result;
2647
2648 PackScope.nextPackElement();
2649 }
2650
2651 // Build argument packs for each of the parameter packs expanded by this
2652 // pack expansion.
2653 if (auto Result = PackScope.finish();
2655 return Result;
2656 }
2657
2659}
2660
2665 bool NumberOfArgumentsMustMatch) {
2666 return ::DeduceTemplateArguments(*this, TemplateParams, Ps, As, Info, Deduced,
2667 NumberOfArgumentsMustMatch);
2668}
2669
2670/// Determine whether two template arguments are the same.
2671static bool isSameTemplateArg(ASTContext &Context,
2673 const TemplateArgument &Y,
2674 bool PartialOrdering,
2675 bool PackExpansionMatchesPack = false) {
2676 // If we're checking deduced arguments (X) against original arguments (Y),
2677 // we will have flattened packs to non-expansions in X.
2678 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2679 X = X.getPackExpansionPattern();
2680
2681 if (X.getKind() != Y.getKind())
2682 return false;
2683
2684 switch (X.getKind()) {
2686 llvm_unreachable("Comparing NULL template argument");
2687
2689 return Context.getCanonicalType(X.getAsType()) ==
2690 Context.getCanonicalType(Y.getAsType());
2691
2693 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
2694
2696 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2697
2700 return Context.getCanonicalTemplateName(
2701 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2704
2706 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2707
2709 return X.structurallyEquals(Y);
2710
2712 llvm::FoldingSetNodeID XID, YID;
2713 X.getAsExpr()->Profile(XID, Context, true);
2714 Y.getAsExpr()->Profile(YID, Context, true);
2715 return XID == YID;
2716 }
2717
2719 unsigned PackIterationSize = X.pack_size();
2720 if (X.pack_size() != Y.pack_size()) {
2721 if (!PartialOrdering)
2722 return false;
2723
2724 // C++0x [temp.deduct.type]p9:
2725 // During partial ordering, if Ai was originally a pack expansion:
2726 // - if P does not contain a template argument corresponding to Ai
2727 // then Ai is ignored;
2728 bool XHasMoreArg = X.pack_size() > Y.pack_size();
2729 if (!(XHasMoreArg && X.pack_elements().back().isPackExpansion()) &&
2730 !(!XHasMoreArg && Y.pack_elements().back().isPackExpansion()))
2731 return false;
2732
2733 if (XHasMoreArg)
2734 PackIterationSize = Y.pack_size();
2735 }
2736
2737 ArrayRef<TemplateArgument> XP = X.pack_elements();
2739 for (unsigned i = 0; i < PackIterationSize; ++i)
2740 if (!isSameTemplateArg(Context, XP[i], YP[i], PartialOrdering,
2741 PackExpansionMatchesPack))
2742 return false;
2743 return true;
2744 }
2745 }
2746
2747 llvm_unreachable("Invalid TemplateArgument Kind!");
2748}
2749
2752 QualType NTTPType, SourceLocation Loc,
2754 switch (Arg.getKind()) {
2756 llvm_unreachable("Can't get a NULL template argument here");
2757
2759 return TemplateArgumentLoc(
2761
2763 if (NTTPType.isNull())
2764 NTTPType = Arg.getParamTypeForDecl();
2767 .getAs<Expr>();
2769 }
2770
2772 if (NTTPType.isNull())
2773 NTTPType = Arg.getNullPtrType();
2775 .getAs<Expr>();
2776 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2777 E);
2778 }
2779
2784 }
2785
2791 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2792 else if (QualifiedTemplateName *QTN =
2793 Template.getAsQualifiedTemplateName())
2794 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2795
2797 return TemplateArgumentLoc(Context, Arg,
2798 Builder.getWithLocInContext(Context), Loc);
2799
2800 return TemplateArgumentLoc(
2801 Context, Arg, Builder.getWithLocInContext(Context), Loc, Loc);
2802 }
2803
2805 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2806
2809 }
2810
2811 llvm_unreachable("Invalid TemplateArgument Kind!");
2812}
2813
2816 SourceLocation Location) {
2818 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2819}
2820
2821/// Convert the given deduced template argument and add it to the set of
2822/// fully-converted template arguments.
2824 Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template,
2825 TemplateDeductionInfo &Info, bool IsDeduced,
2826 SmallVectorImpl<TemplateArgument> &SugaredOutput,
2827 SmallVectorImpl<TemplateArgument> &CanonicalOutput) {
2828 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2829 unsigned ArgumentPackIndex) {
2830 // Convert the deduced template argument into a template
2831 // argument that we can check, almost as if the user had written
2832 // the template argument explicitly.
2834 Arg, QualType(), Info.getLocation(), Param);
2835
2836 // Check the template argument, converting it as necessary.
2837 return S.CheckTemplateArgument(
2838 Param, ArgLoc, Template, Template->getLocation(),
2839 Template->getSourceRange().getEnd(), ArgumentPackIndex, SugaredOutput,
2840 CanonicalOutput,
2841 IsDeduced
2845 };
2846
2847 if (Arg.getKind() == TemplateArgument::Pack) {
2848 // This is a template argument pack, so check each of its arguments against
2849 // the template parameter.
2850 SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
2851 CanonicalPackedArgsBuilder;
2852 for (const auto &P : Arg.pack_elements()) {
2853 // When converting the deduced template argument, append it to the
2854 // general output list. We need to do this so that the template argument
2855 // checking logic has all of the prior template arguments available.
2856 DeducedTemplateArgument InnerArg(P);
2858 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2859 "deduced nested pack");
2860 if (P.isNull()) {
2861 // We deduced arguments for some elements of this pack, but not for
2862 // all of them. This happens if we get a conditionally-non-deduced
2863 // context in a pack expansion (such as an overload set in one of the
2864 // arguments).
2865 S.Diag(Param->getLocation(),
2866 diag::err_template_arg_deduced_incomplete_pack)
2867 << Arg << Param;
2868 return true;
2869 }
2870 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
2871 return true;
2872
2873 // Move the converted template argument into our argument pack.
2874 SugaredPackedArgsBuilder.push_back(SugaredOutput.pop_back_val());
2875 CanonicalPackedArgsBuilder.push_back(CanonicalOutput.pop_back_val());
2876 }
2877
2878 // If the pack is empty, we still need to substitute into the parameter
2879 // itself, in case that substitution fails.
2880 if (SugaredPackedArgsBuilder.empty()) {
2882 MultiLevelTemplateArgumentList Args(Template, SugaredOutput,
2883 /*Final=*/true);
2884
2885 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2886 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2887 NTTP, SugaredOutput,
2888 Template->getSourceRange());
2889 if (Inst.isInvalid() ||
2890 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2891 NTTP->getDeclName()).isNull())
2892 return true;
2893 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2894 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2895 TTP, SugaredOutput,
2896 Template->getSourceRange());
2897 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2898 return true;
2899 }
2900 // For type parameters, no substitution is ever required.
2901 }
2902
2903 // Create the resulting argument pack.
2904 SugaredOutput.push_back(
2905 TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
2906 CanonicalOutput.push_back(TemplateArgument::CreatePackCopy(
2907 S.Context, CanonicalPackedArgsBuilder));
2908 return false;
2909 }
2910
2911 return ConvertArg(Arg, 0);
2912}
2913
2914// FIXME: This should not be a template, but
2915// ClassTemplatePartialSpecializationDecl sadly does not derive from
2916// TemplateDecl.
2917template <typename TemplateDeclT>
2919 Sema &S, TemplateDeclT *Template, bool IsDeduced,
2922 SmallVectorImpl<TemplateArgument> &SugaredBuilder,
2923 SmallVectorImpl<TemplateArgument> &CanonicalBuilder,
2924 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2925 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2926 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2927
2928 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2929 NamedDecl *Param = TemplateParams->getParam(I);
2930
2931 // C++0x [temp.arg.explicit]p3:
2932 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2933 // be deduced to an empty sequence of template arguments.
2934 // FIXME: Where did the word "trailing" come from?
2935 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
2936 if (auto Result =
2937 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish();
2939 return Result;
2940 }
2941
2942 if (!Deduced[I].isNull()) {
2943 if (I < NumAlreadyConverted) {
2944 // We may have had explicitly-specified template arguments for a
2945 // template parameter pack (that may or may not have been extended
2946 // via additional deduced arguments).
2947 if (Param->isParameterPack() && CurrentInstantiationScope &&
2948 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2949 // Forget the partially-substituted pack; its substitution is now
2950 // complete.
2951 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2952 // We still need to check the argument in case it was extended by
2953 // deduction.
2954 } else {
2955 // We have already fully type-checked and converted this
2956 // argument, because it was explicitly-specified. Just record the
2957 // presence of this argument.
2958 SugaredBuilder.push_back(Deduced[I]);
2959 CanonicalBuilder.push_back(
2961 continue;
2962 }
2963 }
2964
2965 // We may have deduced this argument, so it still needs to be
2966 // checked and converted.
2967 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2968 IsDeduced, SugaredBuilder,
2969 CanonicalBuilder)) {
2970 Info.Param = makeTemplateParameter(Param);
2971 // FIXME: These template arguments are temporary. Free them!
2972 Info.reset(
2973 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
2974 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
2976 }
2977
2978 continue;
2979 }
2980
2981 // Substitute into the default template argument, if available.
2982 bool HasDefaultArg = false;
2983 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2984 if (!TD) {
2985 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2986 isa<VarTemplatePartialSpecializationDecl>(Template));
2988 }
2989
2990 TemplateArgumentLoc DefArg;
2991 {
2992 Qualifiers ThisTypeQuals;
2993 CXXRecordDecl *ThisContext = nullptr;
2994 if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
2995 if (Rec->isLambda())
2996 if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
2997 ThisContext = Method->getParent();
2998 ThisTypeQuals = Method->getMethodQualifiers();
2999 }
3000
3001 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
3002 S.getLangOpts().CPlusPlus17);
3003
3005 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param,
3006 SugaredBuilder, CanonicalBuilder, HasDefaultArg);
3007 }
3008
3009 // If there was no default argument, deduction is incomplete.
3010 if (DefArg.getArgument().isNull()) {
3012 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
3013 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3014 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3015 if (PartialOverloading) break;
3016
3019 }
3020
3021 // Check whether we can actually use the default argument.
3023 Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
3024 0, SugaredBuilder, CanonicalBuilder, Sema::CTAK_Specified)) {
3026 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
3027 // FIXME: These template arguments are temporary. Free them!
3028 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3029 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3031 }
3032
3033 // If we get here, we successfully used the default template argument.
3034 }
3035
3037}
3038
3040 if (auto *DC = dyn_cast<DeclContext>(D))
3041 return DC;
3042 return D->getDeclContext();
3043}
3044
3045template<typename T> struct IsPartialSpecialization {
3046 static constexpr bool value = false;
3047};
3048template<>
3050 static constexpr bool value = true;
3051};
3052template<>
3054 static constexpr bool value = true;
3055};
3056template <typename TemplateDeclT>
3057static bool DeducedArgsNeedReplacement(TemplateDeclT *Template) {
3058 return false;
3059}
3060template <>
3063 return !Spec->isClassScopeExplicitSpecialization();
3064}
3065template <>
3068 return !Spec->isClassScopeExplicitSpecialization();
3069}
3070
3071template <typename TemplateDeclT>
3073CheckDeducedArgumentConstraints(Sema &S, TemplateDeclT *Template,
3074 ArrayRef<TemplateArgument> SugaredDeducedArgs,
3075 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
3076 TemplateDeductionInfo &Info) {
3077 llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
3078 Template->getAssociatedConstraints(AssociatedConstraints);
3079
3080 std::optional<ArrayRef<TemplateArgument>> Innermost;
3081 // If we don't need to replace the deduced template arguments,
3082 // we can add them immediately as the inner-most argument list.
3083 if (!DeducedArgsNeedReplacement(Template))
3084 Innermost = CanonicalDeducedArgs;
3085
3087 Template, Template->getDeclContext(), /*Final=*/false, Innermost,
3088 /*RelativeToPrimary=*/true, /*Pattern=*/
3089 nullptr, /*ForConstraintInstantiation=*/true);
3090
3091 // getTemplateInstantiationArgs picks up the non-deduced version of the
3092 // template args when this is a variable template partial specialization and
3093 // not class-scope explicit specialization, so replace with Deduced Args
3094 // instead of adding to inner-most.
3095 if (!Innermost)
3096 MLTAL.replaceInnermostTemplateArguments(Template, CanonicalDeducedArgs);
3097
3098 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
3099 Info.getLocation(),
3102 Info.reset(
3103 TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
3104 TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
3106 }
3108}
3109
3110/// Complete template argument deduction for a partial specialization.
3111template <typename T>
3112static std::enable_if_t<IsPartialSpecialization<T>::value,
3115 Sema &S, T *Partial, bool IsPartialOrdering,
3116 ArrayRef<TemplateArgument> TemplateArgs,
3118 TemplateDeductionInfo &Info) {
3119 // Unevaluated SFINAE context.
3122 Sema::SFINAETrap Trap(S);
3123
3124 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
3125
3126 // C++ [temp.deduct.type]p2:
3127 // [...] or if any template argument remains neither deduced nor
3128 // explicitly specified, template argument deduction fails.
3129 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3131 S, Partial, IsPartialOrdering, Deduced, Info, SugaredBuilder,
3132 CanonicalBuilder);
3134 return Result;
3135
3136 // Form the template argument list from the deduced template arguments.
3137 TemplateArgumentList *SugaredDeducedArgumentList =
3138 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
3139 TemplateArgumentList *CanonicalDeducedArgumentList =
3140 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
3141
3142 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3143
3144 // Substitute the deduced template arguments into the template
3145 // arguments of the class template partial specialization, and
3146 // verify that the instantiated template arguments are both valid
3147 // and are equivalent to the template arguments originally provided
3148 // to the class template.
3149 LocalInstantiationScope InstScope(S);
3150 auto *Template = Partial->getSpecializedTemplate();
3151 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
3152 Partial->getTemplateArgsAsWritten();
3153
3154 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
3155 PartialTemplArgInfo->RAngleLoc);
3156
3157 if (S.SubstTemplateArguments(PartialTemplArgInfo->arguments(),
3159 SugaredBuilder,
3160 /*Final=*/true),
3161 InstArgs)) {
3162 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
3163 if (ParamIdx >= Partial->getTemplateParameters()->size())
3164 ParamIdx = Partial->getTemplateParameters()->size() - 1;
3165
3166 Decl *Param = const_cast<NamedDecl *>(
3167 Partial->getTemplateParameters()->getParam(ParamIdx));
3168 Info.Param = makeTemplateParameter(Param);
3169 Info.FirstArg = (*PartialTemplArgInfo)[ArgIdx].getArgument();
3171 }
3172
3174 SmallVector<TemplateArgument, 4> SugaredConvertedInstArgs,
3175 CanonicalConvertedInstArgs;
3177 Template, Partial->getLocation(), InstArgs, false,
3178 SugaredConvertedInstArgs, CanonicalConvertedInstArgs,
3179 /*UpdateArgsWithConversions=*/true, &ConstraintsNotSatisfied))
3183
3184 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3185 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3186 TemplateArgument InstArg = SugaredConvertedInstArgs.data()[I];
3187 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
3188 IsPartialOrdering)) {
3189 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3190 Info.FirstArg = TemplateArgs[I];
3191 Info.SecondArg = InstArg;
3193 }
3194 }
3195
3196 if (Trap.hasErrorOccurred())
3198
3199 if (auto Result = CheckDeducedArgumentConstraints(S, Partial, SugaredBuilder,
3200 CanonicalBuilder, Info);
3202 return Result;
3203
3205}
3206
3207/// Complete template argument deduction for a class or variable template,
3208/// when partial ordering against a partial specialization.
3209// FIXME: Factor out duplication with partial specialization version above.
3211 Sema &S, TemplateDecl *Template, bool PartialOrdering,
3212 ArrayRef<TemplateArgument> TemplateArgs,
3214 TemplateDeductionInfo &Info) {
3215 // Unevaluated SFINAE context.
3218 Sema::SFINAETrap Trap(S);
3219
3220 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
3221
3222 // C++ [temp.deduct.type]p2:
3223 // [...] or if any template argument remains neither deduced nor
3224 // explicitly specified, template argument deduction fails.
3225 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3227 S, Template, /*IsDeduced*/ PartialOrdering, Deduced, Info,
3228 SugaredBuilder, CanonicalBuilder,
3229 /*CurrentInstantiationScope=*/nullptr,
3230 /*NumAlreadyConverted=*/0U, /*PartialOverloading=*/false);
3232 return Result;
3233
3234 // Check that we produced the correct argument list.
3235 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3236 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3237 TemplateArgument InstArg = CanonicalBuilder[I];
3238 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg, PartialOrdering,
3239 /*PackExpansionMatchesPack=*/true)) {
3240 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3241 Info.FirstArg = TemplateArgs[I];
3242 Info.SecondArg = InstArg;
3244 }
3245 }
3246
3247 if (Trap.hasErrorOccurred())
3249
3250 if (auto Result = CheckDeducedArgumentConstraints(S, Template, SugaredBuilder,
3251 CanonicalBuilder, Info);
3253 return Result;
3254
3256}
3257/// Complete template argument deduction for DeduceTemplateArgumentsFromType.
3258/// FIXME: this is mostly duplicated with the above two versions. Deduplicate
3259/// the three implementations.
3261 Sema &S, TemplateDecl *TD,
3263 TemplateDeductionInfo &Info) {
3264 // Unevaluated SFINAE context.
3267 Sema::SFINAETrap Trap(S);
3268
3270
3271 // C++ [temp.deduct.type]p2:
3272 // [...] or if any template argument remains neither deduced nor
3273 // explicitly specified, template argument deduction fails.
3274 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3276 S, TD, /*IsPartialOrdering=*/false, Deduced, Info, SugaredBuilder,
3277 CanonicalBuilder);
3279 return Result;
3280
3281 if (Trap.hasErrorOccurred())
3283
3284 if (auto Result = CheckDeducedArgumentConstraints(S, TD, SugaredBuilder,
3285 CanonicalBuilder, Info);
3287 return Result;
3288
3290}
3291
3292/// Perform template argument deduction to determine whether the given template
3293/// arguments match the given class or variable template partial specialization
3294/// per C++ [temp.class.spec.match].
3295template <typename T>
3296static std::enable_if_t<IsPartialSpecialization<T>::value,
3299 ArrayRef<TemplateArgument> TemplateArgs,
3300 TemplateDeductionInfo &Info) {
3301 if (Partial->isInvalidDecl())
3303
3304 // C++ [temp.class.spec.match]p2:
3305 // A partial specialization matches a given actual template
3306 // argument list if the template arguments of the partial
3307 // specialization can be deduced from the actual template argument
3308 // list (14.8.2).
3309
3310 // Unevaluated SFINAE context.
3313 Sema::SFINAETrap Trap(S);
3314
3315 // This deduction has no relation to any outer instantiation we might be
3316 // performing.
3317 LocalInstantiationScope InstantiationScope(S);
3318
3320 Deduced.resize(Partial->getTemplateParameters()->size());
3322 S, Partial->getTemplateParameters(),
3323 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3324 /*NumberOfArgumentsMustMatch=*/false);
3326 return Result;
3327
3328 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3329 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs,
3330 Info);
3331 if (Inst.isInvalid())
3333
3334 if (Trap.hasErrorOccurred())
3336
3339 Result = ::FinishTemplateArgumentDeduction(S, Partial,
3340 /*IsPartialOrdering=*/false,
3341 TemplateArgs, Deduced, Info);
3342 });
3343 return Result;
3344}
3345
3348 ArrayRef<TemplateArgument> TemplateArgs,
3349 TemplateDeductionInfo &Info) {
3350 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3351}
3354 ArrayRef<TemplateArgument> TemplateArgs,
3355 TemplateDeductionInfo &Info) {
3356 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3357}
3358
3362 if (TD->isInvalidDecl())
3364
3365 QualType PType;
3366 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
3367 // Use the InjectedClassNameType.
3368 PType = Context.getTypeDeclType(CTD->getTemplatedDecl());
3369 } else if (const auto *AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(TD)) {
3370 PType = AliasTemplate->getTemplatedDecl()
3371 ->getUnderlyingType()
3372 .getCanonicalType();
3373 } else {
3374 assert(false && "Expected a class or alias template");
3375 }
3376
3377 // Unevaluated SFINAE context.
3380 SFINAETrap Trap(*this);
3381
3382 // This deduction has no relation to any outer instantiation we might be
3383 // performing.
3384 LocalInstantiationScope InstantiationScope(*this);
3385
3387 TD->getTemplateParameters()->size());
3390 if (auto DeducedResult = DeduceTemplateArguments(
3391 TD->getTemplateParameters(), PArgs, AArgs, Info, Deduced, false);
3392 DeducedResult != TemplateDeductionResult::Success) {
3393 return DeducedResult;
3394 }
3395
3396 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3397 InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs, Info);
3398 if (Inst.isInvalid())
3400
3401 if (Trap.hasErrorOccurred())
3403
3406 Result = ::FinishTemplateArgumentDeduction(*this, TD, Deduced, Info);
3407 });
3408 return Result;
3409}
3410
3411/// Determine whether the given type T is a simple-template-id type.
3413 if (const TemplateSpecializationType *Spec
3415 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
3416
3417 // C++17 [temp.local]p2:
3418 // the injected-class-name [...] is equivalent to the template-name followed
3419 // by the template-arguments of the class template specialization or partial
3420 // specialization enclosed in <>
3421 // ... which means it's equivalent to a simple-template-id.
3422 //
3423 // This only arises during class template argument deduction for a copy
3424 // deduction candidate, where it permits slicing.
3426 return true;
3427
3428 return false;
3429}
3430
3432 FunctionTemplateDecl *FunctionTemplate,
3433 TemplateArgumentListInfo &ExplicitTemplateArgs,
3436 TemplateDeductionInfo &Info) {
3437 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3438 TemplateParameterList *TemplateParams
3439 = FunctionTemplate->getTemplateParameters();
3440
3441 if (ExplicitTemplateArgs.size() == 0) {
3442 // No arguments to substitute; just copy over the parameter types and
3443 // fill in the function type.
3444 for (auto *P : Function->parameters())
3445 ParamTypes.push_back(P->getType());
3446
3447 if (FunctionType)
3448 *FunctionType = Function->getType();
3450 }
3451
3452 // Unevaluated SFINAE context.
3455 SFINAETrap Trap(*this);
3456
3457 // C++ [temp.arg.explicit]p3:
3458 // Template arguments that are present shall be specified in the
3459 // declaration order of their corresponding template-parameters. The
3460 // template argument list shall not specify more template-arguments than
3461 // there are corresponding template-parameters.
3462 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3463
3464 // Enter a new template instantiation context where we check the
3465 // explicitly-specified template arguments against this function template,
3466 // and then substitute them into the function parameter types.
3469 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3471 if (Inst.isInvalid())
3473
3475 ExplicitTemplateArgs, true, SugaredBuilder,
3476 CanonicalBuilder,
3477 /*UpdateArgsWithConversions=*/false) ||
3478 Trap.hasErrorOccurred()) {
3479 unsigned Index = SugaredBuilder.size();
3480 if (Index >= TemplateParams->size())
3482 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3484 }
3485
3486 // Form the template argument list from the explicitly-specified
3487 // template arguments.
3488 TemplateArgumentList *SugaredExplicitArgumentList =
3490 TemplateArgumentList *CanonicalExplicitArgumentList =
3491 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3492 Info.setExplicitArgs(SugaredExplicitArgumentList,
3493 CanonicalExplicitArgumentList);
3494
3495 // Template argument deduction and the final substitution should be
3496 // done in the context of the templated declaration. Explicit
3497 // argument substitution, on the other hand, needs to happen in the
3498 // calling context.
3499 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3500
3501 // If we deduced template arguments for a template parameter pack,
3502 // note that the template argument pack is partially substituted and record
3503 // the explicit template arguments. They'll be used as part of deduction
3504 // for this template parameter pack.
3505 unsigned PartiallySubstitutedPackIndex = -1u;
3506 if (!CanonicalBuilder.empty()) {
3507 const TemplateArgument &Arg = CanonicalBuilder.back();
3508 if (Arg.getKind() == TemplateArgument::Pack) {
3509 auto *Param = TemplateParams->getParam(CanonicalBuilder.size() - 1);
3510 // If this is a fully-saturated fixed-size pack, it should be
3511 // fully-substituted, not partially-substituted.
3512 std::optional<unsigned> Expansions = getExpandedPackSize(Param);
3513 if (!Expansions || Arg.pack_size() < *Expansions) {
3514 PartiallySubstitutedPackIndex = CanonicalBuilder.size() - 1;
3516 Param, Arg.pack_begin(), Arg.pack_size());
3517 }
3518 }
3519 }
3520
3521 const FunctionProtoType *Proto
3522 = Function->getType()->getAs<FunctionProtoType>();
3523 assert(Proto && "Function template does not have a prototype?");
3524
3525 // Isolate our substituted parameters from our caller.
3526 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3527
3528 ExtParameterInfoBuilder ExtParamInfos;
3529
3531 SugaredExplicitArgumentList->asArray(),
3532 /*Final=*/true);
3533
3534 // Instantiate the types of each of the function parameters given the
3535 // explicitly-specified template arguments. If the function has a trailing
3536 // return type, substitute it after the arguments to ensure we substitute
3537 // in lexical order.
3538 if (Proto->hasTrailingReturn()) {
3539 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3540 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3541 /*params=*/nullptr, ExtParamInfos))
3543 }
3544
3545 // Instantiate the return type.
3546 QualType ResultType;
3547 {
3548 // C++11 [expr.prim.general]p3:
3549 // If a declaration declares a member function or member function
3550 // template of a class X, the expression this is a prvalue of type
3551 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3552 // and the end of the function-definition, member-declarator, or
3553 // declarator.
3554 Qualifiers ThisTypeQuals;
3555 CXXRecordDecl *ThisContext = nullptr;
3556 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3557 ThisContext = Method->getParent();
3558 ThisTypeQuals = Method->getMethodQualifiers();
3559 }
3560
3561 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3563
3564 ResultType =
3565 SubstType(Proto->getReturnType(), MLTAL,
3566 Function->getTypeSpecStartLoc(), Function->getDeclName());
3567 if (ResultType.isNull() || Trap.hasErrorOccurred())
3569 // CUDA: Kernel function must have 'void' return type.
3570 if (getLangOpts().CUDA)
3571 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3572 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3573 << Function->getType() << Function->getSourceRange();
3575 }
3576 }
3577
3578 // Instantiate the types of each of the function parameters given the
3579 // explicitly-specified template arguments if we didn't do so earlier.
3580 if (!Proto->hasTrailingReturn() &&
3581 SubstParmTypes(Function->getLocation(), Function->parameters(),
3582 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3583 /*params*/ nullptr, ExtParamInfos))
3585
3586 if (FunctionType) {
3587 auto EPI = Proto->getExtProtoInfo();
3588 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3589 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3590 Function->getLocation(),
3591 Function->getDeclName(),
3592 EPI);
3593 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3595 }
3596
3597 // C++ [temp.arg.explicit]p2:
3598 // Trailing template arguments that can be deduced (14.8.2) may be
3599 // omitted from the list of explicit template-arguments. If all of the
3600 // template arguments can be deduced, they may all be omitted; in this
3601 // case, the empty template argument list <> itself may also be omitted.
3602 //
3603 // Take all of the explicitly-specified arguments and put them into
3604 // the set of deduced template arguments. The partially-substituted
3605 // parameter pack, however, will be set to NULL since the deduction
3606 // mechanism handles the partially-substituted argument pack directly.
3607 Deduced.reserve(TemplateParams->size());
3608 for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3609 const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
3610 if (I == PartiallySubstitutedPackIndex)
3611 Deduced.push_back(DeducedTemplateArgument());
3612 else
3613 Deduced.push_back(Arg);
3614 }
3615
3617}
3618
3619/// Check whether the deduced argument type for a call to a function
3620/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3623 Sema::OriginalCallArg OriginalArg,
3624 QualType DeducedA) {
3625 ASTContext &Context = S.Context;
3626
3627 auto Failed = [&]() -> TemplateDeductionResult {
3628 Info.FirstArg = TemplateArgument(DeducedA);
3629 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3630 Info.CallArgIndex = OriginalArg.ArgIdx;
3631 return OriginalArg.DecomposedParam
3634 };
3635
3636 QualType A = OriginalArg.OriginalArgType;
3637 QualType OriginalParamType = OriginalArg.OriginalParamType;
3638
3639 // Check for type equality (top-level cv-qualifiers are ignored).
3640 if (Context.hasSameUnqualifiedType(A, DeducedA))
3642
3643 // Strip off references on the argument types; they aren't needed for
3644 // the following checks.
3645 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3646 DeducedA = DeducedARef->getPointeeType();
3647 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3648 A = ARef->getPointeeType();
3649
3650 // C++ [temp.deduct.call]p4:
3651 // [...] However, there are three cases that allow a difference:
3652 // - If the original P is a reference type, the deduced A (i.e., the
3653 // type referred to by the reference) can be more cv-qualified than
3654 // the transformed A.
3655 if (const ReferenceType *OriginalParamRef
3656 = OriginalParamType->getAs<ReferenceType>()) {
3657 // We don't want to keep the reference around any more.
3658 OriginalParamType = OriginalParamRef->getPointeeType();
3659
3660 // FIXME: Resolve core issue (no number yet): if the original P is a
3661 // reference type and the transformed A is function type "noexcept F",
3662 // the deduced A can be F.
3663 QualType Tmp;
3664 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
3666
3667 Qualifiers AQuals = A.getQualifiers();
3668 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3669
3670 // Under Objective-C++ ARC, the deduced type may have implicitly
3671 // been given strong or (when dealing with a const reference)
3672 // unsafe_unretained lifetime. If so, update the original
3673 // qualifiers to include this lifetime.
3674 if (S.getLangOpts().ObjCAutoRefCount &&
3675 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3677 (DeducedAQuals.hasConst() &&
3678 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3679 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3680 }
3681
3682 if (AQuals == DeducedAQuals) {
3683 // Qualifiers match; there's nothing to do.
3684 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
3685 return Failed();
3686 } else {
3687 // Qualifiers are compatible, so have the argument type adopt the
3688 // deduced argument type's qualifiers as if we had performed the
3689 // qualification conversion.
3690 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3691 }
3692 }
3693
3694 // - The transformed A can be another pointer or pointer to member
3695 // type that can be converted to the deduced A via a function pointer
3696 // conversion and/or a qualification conversion.
3697 //
3698 // Also allow conversions which merely strip __attribute__((noreturn)) from
3699 // function types (recursively).
3700 bool ObjCLifetimeConversion = false;
3701 QualType ResultTy;
3702 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3703 (S.IsQualificationConversion(A, DeducedA, false,
3704 ObjCLifetimeConversion) ||
3705 S.IsFunctionConversion(A, DeducedA, ResultTy)))
3707
3708 // - If P is a class and P has the form simple-template-id, then the
3709 // transformed A can be a derived class of the deduced A. [...]
3710 // [...] Likewise, if P is a pointer to a class of the form
3711 // simple-template-id, the transformed A can be a pointer to a
3712 // derived class pointed to by the deduced A.
3713 if (const PointerType *OriginalParamPtr
3714 = OriginalParamType->getAs<PointerType>()) {
3715 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3716 if (const PointerType *APtr = A->getAs<PointerType>()) {
3717 if (A->getPointeeType()->isRecordType()) {
3718 OriginalParamType = OriginalParamPtr->getPointeeType();
3719 DeducedA = DeducedAPtr->getPointeeType();
3720 A = APtr->getPointeeType();
3721 }
3722 }
3723 }
3724 }
3725
3726 if (Context.hasSameUnqualifiedType(A, DeducedA))
3728
3729 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3730 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3732
3733 return Failed();
3734}
3735
3736/// Find the pack index for a particular parameter index in an instantiation of
3737/// a function template with specific arguments.
3738///
3739/// \return The pack index for whichever pack produced this parameter, or -1
3740/// if this was not produced by a parameter. Intended to be used as the
3741/// ArgumentPackSubstitutionIndex for further substitutions.
3742// FIXME: We should track this in OriginalCallArgs so we don't need to
3743// reconstruct it here.
3744static unsigned getPackIndexForParam(Sema &S,
3745 FunctionTemplateDecl *FunctionTemplate,
3747 unsigned ParamIdx) {
3748 unsigned Idx = 0;
3749 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3750 if (PD->isParameterPack()) {
3751 unsigned NumExpansions =
3752 S.getNumArgumentsInExpansion(PD->getType(), Args).value_or(1);
3753 if (Idx + NumExpansions > ParamIdx)
3754 return ParamIdx - Idx;
3755 Idx += NumExpansions;
3756 } else {
3757 if (Idx == ParamIdx)
3758 return -1; // Not a pack expansion
3759 ++Idx;
3760 }
3761 }
3762
3763 llvm_unreachable("parameter index would not be produced from template");
3764}
3765
3766// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`,
3767// we'll try to instantiate and update its explicit specifier after constraint
3768// checking.
3771 const MultiLevelTemplateArgumentList &SubstArgs,
3772 TemplateDeductionInfo &Info, FunctionTemplateDecl *FunctionTemplate,
3773 ArrayRef<TemplateArgument> DeducedArgs) {
3774 auto GetExplicitSpecifier = [](FunctionDecl *D) {
3775 return isa<CXXConstructorDecl>(D)
3776 ? cast<CXXConstructorDecl>(D)->getExplicitSpecifier()
3777 : cast<CXXConversionDecl>(D)->getExplicitSpecifier();
3778 };
3779 auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) {
3780 isa<CXXConstructorDecl>(D)
3781 ? cast<CXXConstructorDecl>(D)->setExplicitSpecifier(ES)
3782 : cast<CXXConversionDecl>(D)->setExplicitSpecifier(ES);
3783 };
3784
3785 ExplicitSpecifier ES = GetExplicitSpecifier(Specialization);
3786 Expr *ExplicitExpr = ES.getExpr();
3787 if (!ExplicitExpr)
3789 if (!ExplicitExpr->isValueDependent())
3791
3793 S, Info.getLocation(), FunctionTemplate, DeducedArgs,
3795 if (Inst.isInvalid())
3797 Sema::SFINAETrap Trap(S);
3798 const ExplicitSpecifier InstantiatedES =
3799 S.instantiateExplicitSpecifier(SubstArgs, ES);
3800 if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) {
3801 Specialization->setInvalidDecl(true);
3803 }
3804 SetExplicitSpecifier(Specialization, InstantiatedES);
3806}
3807
3809 FunctionTemplateDecl *FunctionTemplate,
3811 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3813 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3814 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
3815 // Unevaluated SFINAE context.
3818 SFINAETrap Trap(*this);
3819
3820 // Enter a new template instantiation context while we instantiate the
3821 // actual function declaration.
3822 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3824 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3826 if (Inst.isInvalid())
3828
3829 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3830
3831 // C++ [temp.deduct.type]p2:
3832 // [...] or if any template argument remains neither deduced nor
3833 // explicitly specified, template argument deduction fails.
3834 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3836 *this, FunctionTemplate, /*IsDeduced*/ true, Deduced, Info,
3837 SugaredBuilder, CanonicalBuilder, CurrentInstantiationScope,
3838 NumExplicitlySpecified, PartialOverloading);
3840 return Result;
3841
3842 // C++ [temp.deduct.call]p10: [DR1391]
3843 // If deduction succeeds for all parameters that contain
3844 // template-parameters that participate in template argument deduction,
3845 // and all template arguments are explicitly specified, deduced, or
3846 // obtained from default template arguments, remaining parameters are then
3847 // compared with the corresponding arguments. For each remaining parameter
3848 // P with a type that was non-dependent before substitution of any
3849 // explicitly-specified template arguments, if the corresponding argument
3850 // A cannot be implicitly converted to P, deduction fails.
3851 if (CheckNonDependent())
3853
3854 // Form the template argument list from the deduced template arguments.
3855 TemplateArgumentList *SugaredDeducedArgumentList =
3857 TemplateArgumentList *CanonicalDeducedArgumentList =
3858 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3859 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3860
3861 // Substitute the deduced template arguments into the function template
3862 // declaration to produce the function template specialization.
3863 DeclContext *Owner = FunctionTemplate->getDeclContext();
3864 if (FunctionTemplate->getFriendObjectKind())
3865 Owner = FunctionTemplate->getLexicalDeclContext();
3866 FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
3867 // additional check for inline friend,
3868 // ```
3869 // template <class F1> int foo(F1 X);
3870 // template <int A1> struct A {
3871 // template <class F1> friend int foo(F1 X) { return A1; }
3872 // };
3873 // template struct A<1>;
3874 // int a = foo(1.0);
3875 // ```
3876 const FunctionDecl *FDFriend;
3878 FD->isDefined(FDFriend, /*CheckForPendingFriendDefinition*/ true) &&
3880 FD = const_cast<FunctionDecl *>(FDFriend);
3881 Owner = FD->getLexicalDeclContext();
3882 }
3884 FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
3885 /*Final=*/false);
3886 Specialization = cast_or_null<FunctionDecl>(
3887 SubstDecl(FD, Owner, SubstArgs));
3888 if (!Specialization || Specialization->isInvalidDecl())
3890
3891 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
3892 FunctionTemplate->getCanonicalDecl());
3893
3894 // If the template argument list is owned by the function template
3895 // specialization, release it.
3896 if (Specialization->getTemplateSpecializationArgs() ==
3897 CanonicalDeducedArgumentList &&
3898 !Trap.hasErrorOccurred())
3899 Info.takeCanonical();
3900
3901 // There may have been an error that did not prevent us from constructing a
3902 // declaration. Mark the declaration invalid and return with a substitution
3903 // failure.
3904 if (Trap.hasErrorOccurred()) {
3905 Specialization->setInvalidDecl(true);
3907 }
3908
3909 // C++2a [temp.deduct]p5
3910 // [...] When all template arguments have been deduced [...] all uses of
3911 // template parameters [...] are replaced with the corresponding deduced
3912 // or default argument values.
3913 // [...] If the function template has associated constraints
3914 // ([temp.constr.decl]), those constraints are checked for satisfaction
3915 // ([temp.constr.constr]). If the constraints are not satisfied, type
3916 // deduction fails.
3917 if (!PartialOverloading ||
3918 (CanonicalBuilder.size() ==
3919 FunctionTemplate->getTemplateParameters()->size())) {
3921 Info.getLocation(), Specialization, CanonicalBuilder,
3924
3926 Info.reset(Info.takeSugared(),
3927 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder));
3929 }
3930 }
3931
3932 // We skipped the instantiation of the explicit-specifier during the
3933 // substitution of `FD` before. So, we try to instantiate it back if
3934 // `Specialization` is either a constructor or a conversion function.
3935 if (isa<CXXConstructorDecl, CXXConversionDecl>(Specialization)) {
3938 Info, FunctionTemplate,
3939 DeducedArgs)) {
3941 }
3942 }
3943
3944 if (OriginalCallArgs) {
3945 // C++ [temp.deduct.call]p4:
3946 // In general, the deduction process attempts to find template argument
3947 // values that will make the deduced A identical to A (after the type A
3948 // is transformed as described above). [...]
3949 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
3950 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3951 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
3952
3953 auto ParamIdx = OriginalArg.ArgIdx;
3954 unsigned ExplicitOffset =
3955 Specialization->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
3956 if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset)
3957 // FIXME: This presumably means a pack ended up smaller than we
3958 // expected while deducing. Should this not result in deduction
3959 // failure? Can it even happen?
3960 continue;
3961
3962 QualType DeducedA;
3963 if (!OriginalArg.DecomposedParam) {
3964 // P is one of the function parameters, just look up its substituted
3965 // type.
3966 DeducedA =
3967 Specialization->getParamDecl(ParamIdx + ExplicitOffset)->getType();
3968 } else {
3969 // P is a decomposed element of a parameter corresponding to a
3970 // braced-init-list argument. Substitute back into P to find the
3971 // deduced A.
3972 QualType &CacheEntry =
3973 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3974 if (CacheEntry.isNull()) {
3976 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3977 ParamIdx));
3978 CacheEntry =
3979 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3980 Specialization->getTypeSpecStartLoc(),
3981 Specialization->getDeclName());
3982 }
3983 DeducedA = CacheEntry;
3984 }
3985
3986 if (auto TDK =
3987 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
3989 return TDK;
3990 }
3991 }
3992
3993 // If we suppressed any diagnostics while performing template argument
3994 // deduction, and if we haven't already instantiated this declaration,
3995 // keep track of these diagnostics. They'll be emitted if this specialization
3996 // is actually used.
3997 if (Info.diag_begin() != Info.diag_end()) {
3998 SuppressedDiagnosticsMap::iterator
3999 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
4000 if (Pos == SuppressedDiagnostics.end())
4001 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
4002 .append(Info.diag_begin(), Info.diag_end());
4003 }
4004
4006}
4007
4008/// Gets the type of a function for template-argument-deducton
4009/// purposes when it's considered as part of an overload set.
4011 FunctionDecl *Fn) {
4012 // We may need to deduce the return type of the function now.
4013 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
4014 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
4015 return {};
4016
4017 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
4018 if (Method->isImplicitObjectMemberFunction()) {
4019 // An instance method that's referenced in a form that doesn't
4020 // look like a member pointer is just invalid.
4022 return {};
4023
4024 return S.Context.getMemberPointerType(Fn->getType(),
4025 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
4026 }
4027
4028 if (!R.IsAddressOfOperand) return Fn->getType();
4029 return S.Context.getPointerType(Fn->getType());
4030}
4031
4032/// Apply the deduction rules for overload sets.
4033///
4034/// \return the null type if this argument should be treated as an
4035/// undeduced context
4036static QualType
4038 Expr *Arg, QualType ParamType,
4039 bool ParamWasReference,
4040 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4041
4043
4044 OverloadExpr *Ovl = R.Expression;
4045
4046 // C++0x [temp.deduct.call]p4
4047 unsigned TDF = 0;
4048 if (ParamWasReference)
4050 if (R.IsAddressOfOperand)
4051 TDF |= TDF_IgnoreQualifiers;
4052
4053 // C++0x [temp.deduct.call]p6:
4054 // When P is a function type, pointer to function type, or pointer
4055 // to member function type:
4056
4057 if (!ParamType->isFunctionType() &&
4058 !ParamType->isFunctionPointerType() &&
4059 !ParamType->isMemberFunctionPointerType()) {
4060 if (Ovl->hasExplicitTemplateArgs()) {
4061 // But we can still look for an explicit specialization.
4062 if (FunctionDecl *ExplicitSpec =
4064 Ovl, /*Complain=*/false,
4065 /*FoundDeclAccessPair=*/nullptr, FailedTSC))
4066 return GetTypeOfFunction(S, R, ExplicitSpec);
4067 }
4068
4069 DeclAccessPair DAP;
4070 if (FunctionDecl *Viable =
4072 return GetTypeOfFunction(S, R, Viable);
4073
4074 return {};
4075 }
4076
4077 // Gather the explicit template arguments, if any.
4078 TemplateArgumentListInfo ExplicitTemplateArgs;
4079 if (Ovl->hasExplicitTemplateArgs())
4080 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4081 QualType Match;
4082 for (UnresolvedSetIterator I = Ovl->decls_begin(),
4083 E = Ovl->decls_end(); I != E; ++I) {
4084 NamedDecl *D = (*I)->getUnderlyingDecl();
4085
4086 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
4087 // - If the argument is an overload set containing one or more
4088 // function templates, the parameter is treated as a
4089 // non-deduced context.
4090 if (!Ovl->hasExplicitTemplateArgs())
4091 return {};
4092
4093 // Otherwise, see if we can resolve a function type
4094 FunctionDecl *Specialization = nullptr;
4095 TemplateDeductionInfo Info(Ovl->getNameLoc());
4096 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
4099 continue;
4100
4101 D = Specialization;
4102 }
4103
4104 FunctionDecl *Fn = cast<FunctionDecl>(D);
4105 QualType ArgType = GetTypeOfFunction(S, R, Fn);
4106 if (ArgType.isNull()) continue;
4107
4108 // Function-to-pointer conversion.
4109 if (!ParamWasReference && ParamType->isPointerType() &&
4110 ArgType->isFunctionType())
4111 ArgType = S.Context.getPointerType(ArgType);
4112
4113 // - If the argument is an overload set (not containing function
4114 // templates), trial argument deduction is attempted using each
4115 // of the members of the set. If deduction succeeds for only one
4116 // of the overload set members, that member is used as the
4117 // argument value for the deduction. If deduction succeeds for
4118 // more than one member of the overload set the parameter is
4119 // treated as a non-deduced context.
4120
4121 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
4122 // Type deduction is done independently for each P/A pair, and
4123 // the deduced template argument values are then combined.
4124 // So we do not reject deductions which were made elsewhere.
4126 Deduced(TemplateParams->size());
4127 TemplateDeductionInfo Info(Ovl->getNameLoc());
4129 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF);
4131 continue;
4132 if (!Match.isNull())
4133 return {};
4134 Match = ArgType;
4135 }
4136
4137 return Match;
4138}
4139
4140/// Perform the adjustments to the parameter and argument types
4141/// described in C++ [temp.deduct.call].
4142///
4143/// \returns true if the caller should not attempt to perform any template
4144/// argument deduction based on this P/A pair because the argument is an
4145/// overloaded function set that could not be resolved.
4147 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4148 QualType &ParamType, QualType &ArgType,
4149 Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
4150 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4151 // C++0x [temp.deduct.call]p3:
4152 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
4153 // are ignored for type deduction.
4154 if (ParamType.hasQualifiers())
4155 ParamType = ParamType.getUnqualifiedType();
4156
4157 // [...] If P is a reference type, the type referred to by P is
4158 // used for type deduction.
4159 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
4160 if (ParamRefType)
4161 ParamType = ParamRefType->getPointeeType();
4162
4163 // Overload sets usually make this parameter an undeduced context,
4164 // but there are sometimes special circumstances. Typically
4165 // involving a template-id-expr.
4166 if (ArgType == S.Context.OverloadTy) {
4167 assert(Arg && "expected a non-null arg expression");
4168 ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType,
4169 ParamRefType != nullptr, FailedTSC);
4170 if (ArgType.isNull())
4171 return true;
4172 }
4173
4174 if (ParamRefType) {
4175 // If the argument has incomplete array type, try to complete its type.
4176 if (ArgType->isIncompleteArrayType()) {
4177 assert(Arg && "expected a non-null arg expression");
4178 ArgType = S.getCompletedType(Arg);
4179 }
4180
4181 // C++1z [temp.deduct.call]p3:
4182 // If P is a forwarding reference and the argument is an lvalue, the type
4183 // "lvalue reference to A" is used in place of A for type deduction.
4184 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
4185 ArgClassification.isLValue()) {
4186 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
4187 ArgType = S.Context.getAddrSpaceQualType(
4189 ArgType = S.Context.getLValueReferenceType(ArgType);
4190 }
4191 } else {
4192 // C++ [temp.deduct.call]p2:
4193 // If P is not a reference type:
4194 // - If A is an array type, the pointer type produced by the
4195 // array-to-pointer standard conversion (4.2) is used in place of
4196 // A for type deduction; otherwise,
4197 // - If A is a function type, the pointer type produced by the
4198 // function-to-pointer standard conversion (4.3) is used in place
4199 // of A for type deduction; otherwise,
4200 if (ArgType->canDecayToPointerType())
4201 ArgType = S.Context.getDecayedType(ArgType);
4202 else {
4203 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
4204 // type are ignored for type deduction.
4205 ArgType = ArgType.getUnqualifiedType();
4206 }
4207 }
4208
4209 // C++0x [temp.deduct.call]p4:
4210 // In general, the deduction process attempts to find template argument
4211 // values that will make the deduced A identical to A (after the type A
4212 // is transformed as described above). [...]
4214
4215 // - If the original P is a reference type, the deduced A (i.e., the
4216 // type referred to by the reference) can be more cv-qualified than
4217 // the transformed A.
4218 if (ParamRefType)
4220 // - The transformed A can be another pointer or pointer to member
4221 // type that can be converted to the deduced A via a qualification
4222 // conversion (4.4).
4223 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
4224 ArgType->isObjCObjectPointerType())
4225 TDF |= TDF_IgnoreQualifiers;
4226 // - If P is a class and P has the form simple-template-id, then the
4227 // transformed A can be a derived class of the deduced A. Likewise,
4228 // if P is a pointer to a class of the form simple-template-id, the
4229 // transformed A can be a pointer to a derived class pointed to by
4230 // the deduced A.
4231 if (isSimpleTemplateIdType(ParamType) ||
4232 (isa<PointerType>(ParamType) &&
4234 ParamType->castAs<PointerType>()->getPointeeType())))
4235 TDF |= TDF_DerivedClass;
4236
4237 return false;
4238}
4239
4240static bool
4242 QualType T);
4243
4245 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4246 QualType ParamType, QualType ArgType,
4247 Expr::Classification ArgClassification, Expr *Arg,
4251 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4252 TemplateSpecCandidateSet *FailedTSC = nullptr);
4253
4254/// Attempt template argument deduction from an initializer list
4255/// deemed to be an argument in a function call.
4257 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
4260 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
4261 unsigned TDF) {
4262 // C++ [temp.deduct.call]p1: (CWG 1591)
4263 // If removing references and cv-qualifiers from P gives
4264 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
4265 // a non-empty initializer list, then deduction is performed instead for
4266 // each element of the initializer list, taking P0 as a function template
4267 // parameter type and the initializer element as its argument
4268 //
4269 // We've already removed references and cv-qualifiers here.
4270 if (!ILE->getNumInits())
4272
4273 QualType ElTy;
4274 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
4275 if (ArrTy)
4276 ElTy = ArrTy->getElementType();
4277 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
4278 // Otherwise, an initializer list argument causes the parameter to be
4279 // considered a non-deduced context
4281 }
4282
4283 // Resolving a core issue: a braced-init-list containing any designators is
4284 // a non-deduced context.
4285 for (Expr *E : ILE->inits())
4286 if (isa<DesignatedInitExpr>(E))
4288
4289 // Deduction only needs to be done for dependent types.
4290 if (ElTy->isDependentType()) {
4291 for (Expr *E : ILE->inits()) {
4293 S, TemplateParams, 0, ElTy, E->getType(),
4294 E->Classify(S.getASTContext()), E, Info, Deduced,
4295 OriginalCallArgs, true, ArgIdx, TDF);
4297 return Result;
4298 }
4299 }
4300
4301 // in the P0[N] case, if N is a non-type template parameter, N is deduced
4302 // from the length of the initializer list.
4303 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
4304 // Determine the array bound is something we can deduce.
4305 if (const NonTypeTemplateParmDecl *NTTP =
4306 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
4307 // We can perform template argument deduction for the given non-type
4308 // template parameter.
4309 // C++ [temp.deduct.type]p13:
4310 // The type of N in the type T[N] is std::size_t.
4312 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
4314 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
4315 /*ArrayBound=*/true, Info, Deduced);
4317 return Result;
4318 }
4319 }
4320
4322}
4323
4324/// Perform template argument deduction per [temp.deduct.call] for a
4325/// single parameter / argument pair.
4327 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4328 QualType ParamType, QualType ArgType,
4329 Expr::Classification ArgClassification, Expr *Arg,
4333 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4334 TemplateSpecCandidateSet *FailedTSC) {
4335
4336 QualType OrigParamType = ParamType;
4337
4338 // If P is a reference type [...]
4339 // If P is a cv-qualified type [...]
4341 S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
4342 ArgClassification, Arg, TDF, FailedTSC))
4344
4345 // If [...] the argument is a non-empty initializer list [...]
4346 if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
4347 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
4348 Deduced, OriginalCallArgs, ArgIdx, TDF);
4349
4350 // [...] the deduction process attempts to find template argument values
4351 // that will make the deduced A identical to A
4352 //
4353 // Keep track of the argument type and corresponding parameter index,
4354 // so we can check for compatibility between the deduced A and A.
4355 if (Arg)
4356 OriginalCallArgs.push_back(
4357 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
4358 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
4359 ArgType, Info, Deduced, TDF);
4360}
4361
4363 FunctionTemplateDecl *FunctionTemplate,
4364 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4366 bool PartialOverloading, bool AggregateDeductionCandidate,
4367 QualType ObjectType, Expr::Classification ObjectClassification,
4368 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
4369 if (FunctionTemplate->isInvalidDecl())
4371
4372 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4373 unsigned NumParams = Function->getNumParams();
4374 bool HasExplicitObject = false;
4375 int ExplicitObjectOffset = 0;
4376 if (Function->hasCXXExplicitFunctionObjectParameter()) {
4377 HasExplicitObject = true;
4378 ExplicitObjectOffset = 1;
4379 }
4380
4381 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
4382
4383 // C++ [temp.deduct.call]p1:
4384 // Template argument deduction is done by comparing each function template
4385 // parameter type (call it P) with the type of the corresponding argument
4386 // of the call (call it A) as described below.
4387 if (Args.size() < Function->getMinRequiredExplicitArguments() &&
4388 !PartialOverloading)
4390 else if (TooManyArguments(NumParams, Args.size() + ExplicitObjectOffset,
4391 PartialOverloading)) {
4392 const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
4393 if (Proto->isTemplateVariadic())
4394 /* Do nothing */;
4395 else if (!Proto->isVariadic())
4397 }
4398
4399 // The types of the parameters from which we will perform template argument
4400 // deduction.
4401 LocalInstantiationScope InstScope(*this);
4402 TemplateParameterList *TemplateParams
4403 = FunctionTemplate->getTemplateParameters();
4405 SmallVector<QualType, 8> ParamTypes;
4406 unsigned NumExplicitlySpecified = 0;
4407 if (ExplicitTemplateArgs) {
4410 Result = SubstituteExplicitTemplateArguments(
4411 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4412 Info);
4413 });
4415 return Result;
4416
4417 NumExplicitlySpecified = Deduced.size();
4418 } else {
4419 // Just fill in the parameter types from the function declaration.
4420 for (unsigned I = 0; I != NumParams; ++I)
4421 ParamTypes.push_back(Function->getParamDecl(I)->getType());
4422 }
4423
4424 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
4425
4426 // Deduce an argument of type ParamType from an expression with index ArgIdx.
4427 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx,
4428 bool ExplicitObjectArgument) {
4429 // C++ [demp.deduct.call]p1: (DR1391)
4430 // Template argument deduction is done by comparing each function template
4431 // parameter that contains template-parameters that participate in
4432 // template argument deduction ...
4433 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4435
4436 if (ExplicitObjectArgument) {
4437 // ... with the type of the corresponding argument
4439 *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
4440 ObjectClassification,
4441 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4442 /*Decomposed*/ false, ArgIdx, /*TDF*/ 0);
4443 }
4444
4445 // ... with the type of the corresponding argument
4447 *this, TemplateParams, FirstInnerIndex, ParamType,
4448 Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()),
4449 Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false,
4450 ArgIdx, /*TDF*/ 0);
4451 };
4452
4453 // Deduce template arguments from the function parameters.
4454 Deduced.resize(TemplateParams->size());
4455 SmallVector<QualType, 8> ParamTypesForArgChecking;
4456 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4457 ParamIdx != NumParamTypes; ++ParamIdx) {
4458 QualType ParamType = ParamTypes[ParamIdx];
4459
4460 const PackExpansionType *ParamExpansion =
4461 dyn_cast<PackExpansionType>(ParamType);
4462 if (!ParamExpansion) {
4463 // Simple case: matching a function parameter to a function argument.
4464 if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0))
4465 break;
4466
4467 ParamTypesForArgChecking.push_back(ParamType);
4468
4469 if (ParamIdx == 0 && HasExplicitObject) {
4470 if (auto Result = DeduceCallArgument(ParamType, 0,
4471 /*ExplicitObjectArgument=*/true);
4473 return Result;
4474 continue;
4475 }
4476
4477 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4478 /*ExplicitObjectArgument=*/false);
4480 return Result;
4481
4482 continue;
4483 }
4484
4485 bool IsTrailingPack = ParamIdx + 1 == NumParamTypes;
4486
4487 QualType ParamPattern = ParamExpansion->getPattern();
4488 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
4489 ParamPattern,
4490 AggregateDeductionCandidate && IsTrailingPack);
4491
4492 // C++0x [temp.deduct.call]p1:
4493 // For a function parameter pack that occurs at the end of the
4494 // parameter-declaration-list, the type A of each remaining argument of
4495 // the call is compared with the type P of the declarator-id of the
4496 // function parameter pack. Each comparison deduces template arguments
4497 // for subsequent positions in the template parameter packs expanded by
4498 // the function parameter pack. When a function parameter pack appears
4499 // in a non-deduced context [not at the end of the list], the type of
4500 // that parameter pack is never deduced.
4501 //
4502 // FIXME: The above rule allows the size of the parameter pack to change
4503 // after we skip it (in the non-deduced case). That makes no sense, so
4504 // we instead notionally deduce the pack against N arguments, where N is
4505 // the length of the explicitly-specified pack if it's expanded by the
4506 // parameter pack and 0 otherwise, and we treat each deduction as a
4507 // non-deduced context.
4508 if (IsTrailingPack || PackScope.hasFixedArity()) {
4509 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4510 PackScope.nextPackElement(), ++ArgIdx) {
4511 ParamTypesForArgChecking.push_back(ParamPattern);
4512 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4513 /*ExplicitObjectArgument=*/false);
4515 return Result;
4516 }
4517 } else {
4518 // If the parameter type contains an explicitly-specified pack that we
4519 // could not expand, skip the number of parameters notionally created
4520 // by the expansion.
4521 std::optional<unsigned> NumExpansions =
4522 ParamExpansion->getNumExpansions();
4523 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4524 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4525 ++I, ++ArgIdx) {
4526 ParamTypesForArgChecking.push_back(ParamPattern);
4527 // FIXME: Should we add OriginalCallArgs for these? What if the
4528 // corresponding argument is a list?
4529 PackScope.nextPackElement();
4530 }
4531 } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4532 PackScope.isDeducedFromEarlierParameter()) {
4533 // [temp.deduct.general#3]
4534 // When all template arguments have been deduced
4535 // or obtained from default template arguments, all uses of template
4536 // parameters in the template parameter list of the template are
4537 // replaced with the corresponding deduced or default argument values
4538 //
4539 // If we have a trailing parameter pack, that has been deduced
4540 // previously we substitute the pack here in a similar fashion as
4541 // above with the trailing parameter packs. The main difference here is
4542 // that, in this case we are not processing all of the remaining
4543 // arguments. We are only process as many arguments as we have in
4544 // the already deduced parameter.
4545 std::optional<unsigned> ArgPosAfterSubstitution =
4546 PackScope.getSavedPackSizeIfAllEqual();
4547 if (!ArgPosAfterSubstitution)
4548 continue;
4549
4550 unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4551 for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4552 ParamTypesForArgChecking.push_back(ParamPattern);
4553 if (auto Result =
4554 DeduceCallArgument(ParamPattern, ArgIdx,
4555 /*ExplicitObjectArgument=*/false);
4557 return Result;
4558
4559 PackScope.nextPackElement();
4560 }
4561 }
4562 }
4563
4564 // Build argument packs for each of the parameter packs expanded by this
4565 // pack expansion.
4566 if (auto Result = PackScope.finish();
4568 return Result;
4569 }
4570
4571 // Capture the context in which the function call is made. This is the context
4572 // that is needed when the accessibility of template arguments is checked.
4573 DeclContext *CallingCtx = CurContext;
4574
4577 Result = FinishTemplateArgumentDeduction(
4578 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4579 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
4580 ContextRAII SavedContext(*this, CallingCtx);
4581 return CheckNonDependent(ParamTypesForArgChecking);
4582 });
4583 });
4584 return Result;
4585}
4586
4589 bool AdjustExceptionSpec) {
4590 if (ArgFunctionType.isNull())
4591 return ArgFunctionType;
4592
4593 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4594 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4595 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4596 bool Rebuild = false;
4597
4598 CallingConv CC = FunctionTypeP->getCallConv();
4599 if (EPI.ExtInfo.getCC() != CC) {
4600 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4601 Rebuild = true;
4602 }
4603
4604 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4605 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4606 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4607 Rebuild = true;
4608 }
4609
4610 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4611 ArgFunctionTypeP->hasExceptionSpec())) {
4612 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4613 Rebuild = true;
4614 }
4615
4616 if (!Rebuild)
4617 return ArgFunctionType;
4618
4619 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4620 ArgFunctionTypeP->getParamTypes(), EPI);
4621}
4622
4624 FunctionTemplateDecl *FunctionTemplate,
4625 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4627 bool IsAddressOfFunction) {
4628 if (FunctionTemplate->isInvalidDecl())
4630
4631 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4632 TemplateParameterList *TemplateParams
4633 = FunctionTemplate->getTemplateParameters();
4634 QualType FunctionType = Function->getType();
4635
4636 // Substitute any explicit template arguments.
4637 LocalInstantiationScope InstScope(*this);
4639 unsigned NumExplicitlySpecified = 0;
4640 SmallVector<QualType, 4> ParamTypes;
4641 if (ExplicitTemplateArgs) {
4644 Result = SubstituteExplicitTemplateArguments(
4645 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4646 &FunctionType, Info);
4647 });
4649 return Result;
4650
4651 NumExplicitlySpecified = Deduced.size();
4652 }
4653
4654 // When taking the address of a function, we require convertibility of
4655 // the resulting function type. Otherwise, we allow arbitrary mismatches
4656 // of calling convention and noreturn.
4657 if (!IsAddressOfFunction)
4658 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4659 /*AdjustExceptionSpec*/false);
4660
4661 // Unevaluated SFINAE context.
4664 SFINAETrap Trap(*this);
4665
4666 Deduced.resize(TemplateParams->size());
4667
4668 // If the function has a deduced return type, substitute it for a dependent
4669 // type so that we treat it as a non-deduced context in what follows.
4670 bool HasDeducedReturnType = false;
4671 if (getLangOpts().CPlusPlus14 &&
4672 Function->getReturnType()->getContainedAutoType()) {
4674 HasDeducedReturnType = true;
4675 }
4676
4677 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
4678 unsigned TDF =
4680 // Deduce template arguments from the function type.
4682 *this, TemplateParams, FunctionType, ArgFunctionType, Info, Deduced,
4683 TDF);
4685 return Result;
4686 }
4687
4690 Result = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
4691 NumExplicitlySpecified,
4692 Specialization, Info);
4693 });
4695 return Result;
4696
4697 // If the function has a deduced return type, deduce it now, so we can check
4698 // that the deduced function type matches the requested type.
4699 if (HasDeducedReturnType && IsAddressOfFunction &&
4700 Specialization->getReturnType()->isUndeducedType() &&
4703
4704 // [C++26][expr.const]/p17
4705 // An expression or conversion is immediate-escalating if it is not initially
4706 // in an immediate function context and it is [...]
4707 // a potentially-evaluated id-expression that denotes an immediate function.
4708 if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
4709 Specialization->isImmediateEscalating() &&
4710 parentEvaluationContext().isPotentiallyEvaluated() &&
4712 Info.getLocation()))
4714
4715 // Adjust the exception specification of the argument to match the
4716 // substituted and resolved type we just formed. (Calling convention and
4717 // noreturn can't be dependent, so we don't actually need this for them
4718 // right now.)
4719 QualType SpecializationType = Specialization->getType();
4720 if (!IsAddressOfFunction) {
4721 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4722 /*AdjustExceptionSpec*/true);
4723
4724 // Revert placeholder types in the return type back to undeduced types so
4725 // that the comparison below compares the declared return types.
4726 if (HasDeducedReturnType) {
4727 SpecializationType = SubstAutoType(SpecializationType, QualType());
4728 ArgFunctionType = SubstAutoType(ArgFunctionType, QualType());
4729 }
4730 }
4731
4732 // If the requested function type does not match the actual type of the
4733 // specialization with respect to arguments of compatible pointer to function
4734 // types, template argument deduction fails.
4735 if (!ArgFunctionType.isNull()) {
4736 if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
4737 Context.getCanonicalType(SpecializationType),
4738 Context.getCanonicalType(ArgFunctionType))
4740 SpecializationType, ArgFunctionType)) {
4741 Info.FirstArg = TemplateArgument(SpecializationType);
4742 Info.SecondArg = TemplateArgument(ArgFunctionType);
4744 }
4745 }
4746
4748}
4749
4751 FunctionTemplateDecl *ConversionTemplate, QualType ObjectType,
4752 Expr::Classification ObjectClassification, QualType ToType,
4754 if (ConversionTemplate->isInvalidDecl())
4756
4757 CXXConversionDecl *ConversionGeneric
4758 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4759
4760 QualType FromType = ConversionGeneric->getConversionType();
4761
4762 // Canonicalize the types for deduction.
4763 QualType P = Context.getCanonicalType(FromType);
4764 QualType A = Context.getCanonicalType(ToType);
4765
4766 // C++0x [temp.deduct.conv]p2:
4767 // If P is a reference type, the type referred to by P is used for
4768 // type deduction.
4769 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4770 P = PRef->getPointeeType();
4771
4772 // C++0x [temp.deduct.conv]p4:
4773 // [...] If A is a reference type, the type referred to by A is used
4774 // for type deduction.
4775 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4776 A = ARef->getPointeeType();
4777 // We work around a defect in the standard here: cv-qualifiers are also
4778 // removed from P and A in this case, unless P was a reference type. This
4779 // seems to mostly match what other compilers are doing.
4780 if (!FromType->getAs<ReferenceType>()) {
4781 A = A.getUnqualifiedType();
4782 P = P.getUnqualifiedType();
4783 }
4784
4785 // C++ [temp.deduct.conv]p3:
4786 //
4787 // If A is not a reference type:
4788 } else {
4789 assert(!A->isReferenceType() && "Reference types were handled above");
4790
4791 // - If P is an array type, the pointer type produced by the
4792 // array-to-pointer standard conversion (4.2) is used in place
4793 // of P for type deduction; otherwise,
4794 if (P->isArrayType())
4796 // - If P is a function type, the pointer type produced by the
4797 // function-to-pointer standard conversion (4.3) is used in
4798 // place of P for type deduction; otherwise,
4799 else if (P->isFunctionType())
4801 // - If P is a cv-qualified type, the top level cv-qualifiers of
4802 // P's type are ignored for type deduction.
4803 else
4804 P = P.getUnqualifiedType();
4805
4806 // C++0x [temp.deduct.conv]p4:
4807 // If A is a cv-qualified type, the top level cv-qualifiers of A's
4808 // type are ignored for type deduction. If A is a reference type, the type
4809 // referred to by A is used for type deduction.
4810 A = A.getUnqualifiedType();
4811 }
4812
4813 // Unevaluated SFINAE context.
4816 SFINAETrap Trap(*this);
4817
4818 // C++ [temp.deduct.conv]p1:
4819 // Template argument deduction is done by comparing the return
4820 // type of the template conversion function (call it P) with the
4821 // type that is required as the result of the conversion (call it
4822 // A) as described in 14.8.2.4.
4823 TemplateParameterList *TemplateParams
4824 = ConversionTemplate->getTemplateParameters();
4826 Deduced.resize(TemplateParams->size());
4827
4828 // C++0x [temp.deduct.conv]p4:
4829 // In general, the deduction process attempts to find template
4830 // argument values that will make the deduced A identical to
4831 // A. However, there are two cases that allow a difference:
4832 unsigned TDF = 0;
4833 // - If the original A is a reference type, A can be more
4834 // cv-qualified than the deduced A (i.e., the type referred to
4835 // by the reference)
4836 if (ToType->isReferenceType())
4838 // - The deduced A can be another pointer or pointer to member
4839 // type that can be converted to A via a qualification
4840 // conversion.
4841 //
4842 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4843 // both P and A are pointers or member pointers. In this case, we
4844 // just ignore cv-qualifiers completely).
4845 if ((P->isPointerType() && A->isPointerType()) ||
4846 (P->isMemberPointerType() && A->isMemberPointerType()))
4847 TDF |= TDF_IgnoreQualifiers;
4848
4850 if (ConversionGeneric->isExplicitObjectMemberFunction()) {
4851 QualType ParamType = ConversionGeneric->getParamDecl(0)->getType();
4854 *this, TemplateParams, getFirstInnerIndex(ConversionTemplate),
4855 ParamType, ObjectType, ObjectClassification,
4856 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4857 /*Decomposed*/ false, 0, /*TDF*/ 0);
4859 return Result;
4860 }
4861
4863 *this, TemplateParams, P, A, Info, Deduced, TDF);
4865 return Result;
4866
4867 // Create an Instantiation Scope for finalizing the operator.
4868 LocalInstantiationScope InstScope(*this);
4869 // Finish template argument deduction.
4870 FunctionDecl *ConversionSpecialized = nullptr;
4873 Result = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
4874 ConversionSpecialized, Info,
4875 &OriginalCallArgs);
4876 });
4877 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
4878 return Result;
4879}
4880
4883 TemplateArgumentListInfo *ExplicitTemplateArgs,
4886 bool IsAddressOfFunction) {
4887 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
4888 QualType(), Specialization, Info,
4889 IsAddressOfFunction);
4890}
4891
4892namespace {
4893 struct DependentAuto { bool IsPack; };
4894
4895 /// Substitute the 'auto' specifier or deduced template specialization type
4896 /// specifier within a type for a given replacement type.
4897 class SubstituteDeducedTypeTransform :
4898 public TreeTransform<SubstituteDeducedTypeTransform> {
4899 QualType Replacement;
4900 bool ReplacementIsPack;
4901 bool UseTypeSugar;
4903
4904 public:
4905 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
4906 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4907 ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
4908
4909 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4910 bool UseTypeSugar = true)
4911 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4912 Replacement(Replacement), ReplacementIsPack(false),
4913 UseTypeSugar(UseTypeSugar) {}
4914
4915 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4916 assert(isa<TemplateTypeParmType>(Replacement) &&
4917 "unexpected unsugared replacement kind");
4918 QualType Result = Replacement;
4920 NewTL.setNameLoc(TL.getNameLoc());
4921 return Result;
4922 }
4923
4924 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4925 // If we're building the type pattern to deduce against, don't wrap the
4926 // substituted type in an AutoType. Certain template deduction rules
4927 // apply only when a template type parameter appears directly (and not if
4928 // the parameter is found through desugaring). For instance:
4929 // auto &&lref = lvalue;
4930 // must transform into "rvalue reference to T" not "rvalue reference to
4931 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
4932 //
4933 // FIXME: Is this still necessary?
4934 if (!UseTypeSugar)
4935 return TransformDesugared(TLB, TL);
4936
4937 QualType Result = SemaRef.Context.getAutoType(
4938 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
4939 ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(),
4941 auto NewTL = TLB.push<AutoTypeLoc>(Result);
4942 NewTL.copy(TL);
4943 return Result;
4944 }
4945
4946 QualType TransformDeducedTemplateSpecializationType(
4948 if (!UseTypeSugar)
4949 return TransformDesugared(TLB, TL);
4950
4951 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
4953 Replacement, Replacement.isNull());
4954 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
4955 NewTL.setNameLoc(TL.getNameLoc());
4956 return Result;
4957 }
4958
4959 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4960 // Lambdas never need to be transformed.
4961 return E;
4962 }
4963 bool TransformExceptionSpec(SourceLocation Loc,
4965 SmallVectorImpl<QualType> &Exceptions,
4966 bool &Changed) {
4967 if (ESI.Type == EST_Uninstantiated) {
4968 ESI.instantiate();
4969 Changed = true;
4970 }
4971 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
4972 }
4973
4974 QualType Apply(TypeLoc TL) {
4975 // Create some scratch storage for the transformed type locations.
4976 // FIXME: We're just going to throw this information away. Don't build it.
4977 TypeLocBuilder TLB;
4978 TLB.reserve(TL.getFullDataSize());
4979 return TransformType(TLB, TL);
4980 }
4981 };
4982
4983} // namespace
4984
4987 QualType Deduced) {
4988 ConstraintSatisfaction Satisfaction;
4989 ConceptDecl *Concept = Type.getTypeConstraintConcept();
4990 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
4991 TypeLoc.getRAngleLoc());
4992 TemplateArgs.addArgument(
4995 Deduced, TypeLoc.getNameLoc())));
4996 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
4997 TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
4998
4999 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
5000 if (S.CheckTemplateArgumentList(Concept, SourceLocation(), TemplateArgs,
5001 /*PartialTemplateArgs=*/false,
5002 SugaredConverted, CanonicalConverted))
5003 return true;
5004 MultiLevelTemplateArgumentList MLTAL(Concept, CanonicalConverted,
5005 /*Final=*/false);
5006 // Build up an EvaluationContext with an ImplicitConceptSpecializationDecl so
5007 // that the template arguments of the constraint can be preserved. For
5008 // example:
5009 //
5010 // template <class T>
5011 // concept C = []<D U = void>() { return true; }();
5012 //
5013 // We need the argument for T while evaluating type constraint D in
5014 // building the CallExpr to the lambda.
5018 S.getASTContext(), Concept->getDeclContext(), Concept->getLocation(),
5019 CanonicalConverted));
5020 if (S.CheckConstraintSatisfaction(Concept, {Concept->getConstraintExpr()},
5022 Satisfaction))
5023 return true;
5024 if (!Satisfaction.IsSatisfied) {
5025 std::string Buf;
5026 llvm::raw_string_ostream OS(Buf);
5027 OS << "'" << Concept->getName();
5028 if (TypeLoc.hasExplicitTemplateArgs()) {
5030 OS, Type.getTypeConstraintArguments(), S.getPrintingPolicy(),
5031 Type.getTypeConstraintConcept()->getTemplateParameters());
5032 }
5033 OS << "'";
5034 OS.flush();
5035 S.Diag(TypeLoc.getConceptNameLoc(),
5036 diag::err_placeholder_constraints_not_satisfied)
5037 << Deduced << Buf << TypeLoc.getLocalSourceRange();
5038 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
5039 return true;
5040 }
5041 return false;
5042}
5043
5046 TemplateDeductionInfo &Info, bool DependentDeduction,
5047 bool IgnoreConstraints,
5048 TemplateSpecCandidateSet *FailedTSC) {
5049 assert(DependentDeduction || Info.getDeducedDepth() == 0);
5050 if (Init->containsErrors())
5052
5053 const AutoType *AT = Type.getType()->getContainedAutoType();
5054 assert(AT);
5055
5056 if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
5057 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
5058 if (NonPlaceholder.isInvalid())
5060 Init = NonPlaceholder.get();
5061 }
5062
5063 DependentAuto DependentResult = {
5064 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
5065
5066 if (!DependentDeduction &&
5067 (Type.getType()->isDependentType() || Init->isTypeDependent() ||
5068 Init->containsUnexpandedParameterPack())) {
5069 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5070 assert(!Result.isNull() && "substituting DependentTy can't fail");
5072 }
5073
5074 // Make sure that we treat 'char[]' equaly as 'char*' in C23 mode.
5075 auto *String = dyn_cast<StringLiteral>(Init);
5076 if (getLangOpts().C23 && String && Type.getType()->isArrayType()) {
5077 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5078 TypeLoc TL = TypeLoc(Init->getType(), Type.getOpaqueData());
5079 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(TL);
5080 assert(!Result.isNull() && "substituting DependentTy can't fail");
5082 }
5083
5084 // Emit a warning if 'auto*' is used in pedantic and in C23 mode.
5085 if (getLangOpts().C23 && Type.getType()->isPointerType()) {
5086 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5087 }
5088
5089 auto *InitList = dyn_cast<InitListExpr>(Init);
5090 if (!getLangOpts().CPlusPlus && InitList) {
5091 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c)
5092 << (int)AT->getKeyword() << getLangOpts().C23;
5094 }
5095
5096 // Deduce type of TemplParam in Func(Init)
5098 Deduced.resize(1);
5099
5100 // If deduction failed, don't diagnose if the initializer is dependent; it
5101 // might acquire a matching type in the instantiation.
5102 auto DeductionFailed = [&](TemplateDeductionResult TDK) {
5103 if (Init->isTypeDependent()) {
5104 Result =
5105 SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5106 assert(!Result.isNull() && "substituting DependentTy can't fail");
5108 }
5109 return TDK;
5110 };
5111
5112 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
5113
5115 // If this is a 'decltype(auto)' specifier, do the decltype dance.
5116 if (AT->isDecltypeAuto()) {
5117 if (InitList) {
5118 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
5120 }
5121
5123 assert(!DeducedType.isNull());
5124 } else {
5125 LocalInstantiationScope InstScope(*this);
5126
5127 // Build template<class TemplParam> void Func(FuncParam);
5128 SourceLocation Loc = Init->getExprLoc();
5130 Context, nullptr, SourceLocation(), Loc, Info.getDeducedDepth(), 0,
5131 nullptr, false, false, false);
5132 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
5133 NamedDecl *TemplParamPtr = TemplParam;
5135 Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
5136
5137 if (InitList) {
5138 // Notionally, we substitute std::initializer_list<T> for 'auto' and
5139 // deduce against that. Such deduction only succeeds if removing
5140 // cv-qualifiers and references results in std::initializer_list<T>.
5141 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
5143
5144 SourceRange DeducedFromInitRange;
5145 for (Expr *Init : InitList->inits()) {
5146 // Resolving a core issue: a braced-init-list containing any designators
5147 // is a non-deduced context.
5148 if (isa<DesignatedInitExpr>(Init))
5151 *this, TemplateParamsSt.get(), 0, TemplArg, Init->getType(),
5152 Init->Classify(getASTContext()), Init, Info, Deduced,
5153 OriginalCallArgs, /*Decomposed=*/true,
5154 /*ArgIdx=*/0, /*TDF=*/0);
5157 Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction)
5158 << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
5159 << Init->getSourceRange();
5160 return DeductionFailed(TemplateDeductionResult::AlreadyDiagnosed);
5161 }
5162 return DeductionFailed(TDK);
5163 }
5164
5165 if (DeducedFromInitRange.isInvalid() &&
5166 Deduced[0].getKind() != TemplateArgument::Null)
5167 DeducedFromInitRange = Init->getSourceRange();
5168 }
5169 } else {
5170 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
5171 Diag(Loc, diag::err_auto_bitfield);
5173 }
5174 QualType FuncParam =
5175 SubstituteDeducedTypeTransform(*this, TemplArg).Apply(Type);
5176 assert(!FuncParam.isNull() &&
5177 "substituting template parameter for 'auto' failed");
5179 *this, TemplateParamsSt.get(), 0, FuncParam, Init->getType(),
5180 Init->Classify(getASTContext()), Init, Info, Deduced,
5181 OriginalCallArgs, /*Decomposed=*/false, /*ArgIdx=*/0, /*TDF=*/0,
5182 FailedTSC);
5184 return DeductionFailed(TDK);
5185 }
5186
5187 // Could be null if somehow 'auto' appears in a non-deduced context.
5188 if (Deduced[0].getKind() != TemplateArgument::Type)
5189 return DeductionFailed(TemplateDeductionResult::Incomplete);
5190 DeducedType = Deduced[0].getAsType();
5191
5192 if (InitList) {
5194 if (DeducedType.isNull())
5196 }
5197 }
5198
5199 if (!Result.isNull()) {
5201 Info.FirstArg = Result;
5202 Info.SecondArg = DeducedType;
5203 return DeductionFailed(TemplateDeductionResult::Inconsistent);
5204 }
5206 }
5207
5208 if (AT->isConstrained() && !IgnoreConstraints &&
5210 *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType))
5212
5213 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
5214 if (Result.isNull())
5216
5217 // Check that the deduced argument type is compatible with the original
5218 // argument type per C++ [temp.deduct.call]p4.
5219 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
5220 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
5221 assert((bool)InitList == OriginalArg.DecomposedParam &&
5222 "decomposed non-init-list in auto deduction?");
5223 if (auto TDK =
5224 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
5226 Result = QualType();
5227 return DeductionFailed(TDK);
5228 }
5229 }
5230
5232}
5233
5235 QualType TypeToReplaceAuto) {
5236 assert(TypeToReplaceAuto != Context.DependentTy);
5237 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5238 .TransformType(TypeWithAuto);
5239}
5240
5242 QualType TypeToReplaceAuto) {
5243 assert(TypeToReplaceAuto != Context.DependentTy);
5244 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5245 .TransformType(TypeWithAuto);
5246}
5247
5249 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5250 .TransformType(TypeWithAuto);
5251}
5252
5255 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5256 .TransformType(TypeWithAuto);
5257}
5258
5260 QualType TypeToReplaceAuto) {
5261 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5262 /*UseTypeSugar*/ false)
5263 .TransformType(TypeWithAuto);
5264}
5265
5267 QualType TypeToReplaceAuto) {
5268 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5269 /*UseTypeSugar*/ false)
5270 .TransformType(TypeWithAuto);
5271}
5272
5274 const Expr *Init) {
5275 if (isa<InitListExpr>(Init))
5276 Diag(VDecl->getLocation(),
5277 VDecl->isInitCapture()
5278 ? diag::err_init_capture_deduction_failure_from_init_list
5279 : diag::err_auto_var_deduction_failure_from_init_list)
5280 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
5281 else
5282 Diag(VDecl->getLocation(),
5283 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
5284 : diag::err_auto_var_deduction_failure)
5285 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5286 << Init->getSourceRange();
5287}
5288
5290 bool Diagnose) {
5291 assert(FD->getReturnType()->isUndeducedType());
5292
5293 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
5294 // within the return type from the call operator's type.
5296 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5297 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5298
5299 // For a generic lambda, instantiate the call operator if needed.
5300 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5302 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5303 if (!CallOp || CallOp->isInvalidDecl())
5304 return true;
5305
5306 // We might need to deduce the return type by instantiating the definition
5307 // of the operator() function.
5308 if (CallOp->getReturnType()->isUndeducedType()) {
5311 });
5312 }
5313 }
5314
5315 if (CallOp->isInvalidDecl())
5316 return true;
5317 assert(!CallOp->getReturnType()->isUndeducedType() &&
5318 "failed to deduce lambda return type");
5319
5320 // Build the new return type from scratch.
5321 CallingConv RetTyCC = FD->getReturnType()
5322 ->getPointeeType()
5323 ->castAs<FunctionType>()
5324 ->getCallConv();
5326 CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
5327 if (FD->getReturnType()->getAs<PointerType>())
5328 RetType = Context.getPointerType(RetType);
5329 else {
5330 assert(FD->getReturnType()->getAs<BlockPointerType>());
5331 RetType = Context.getBlockPointerType(RetType);
5332 }
5334 return false;
5335 }
5336
5340 });
5341 }
5342
5343 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
5344 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
5345 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
5346 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
5347 }
5348
5349 return StillUndeduced;
5350}
5351
5354 assert(FD->isImmediateEscalating());
5355
5357 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5358 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5359
5360 // For a generic lambda, instantiate the call operator if needed.
5361 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5363 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5364 if (!CallOp || CallOp->isInvalidDecl())
5365 return true;
5367 Loc, [&] { InstantiateFunctionDefinition(Loc, CallOp); });
5368 }
5369 return CallOp->isInvalidDecl();
5370 }
5371
5374 Loc, [&] { InstantiateFunctionDefinition(Loc, FD); });
5375 }
5376 return false;
5377}
5378
5380 const CXXMethodDecl *Method,
5381 QualType RawType,
5382 bool IsOtherRvr) {
5383 // C++20 [temp.func.order]p3.1, p3.2:
5384 // - The type X(M) is "rvalue reference to cv A" if the optional
5385 // ref-qualifier of M is && or if M has no ref-qualifier and the
5386 // positionally-corresponding parameter of the other transformed template
5387 // has rvalue reference type; if this determination depends recursively
5388 // upon whether X(M) is an rvalue reference type, it is not considered to
5389 // have rvalue reference type.
5390 //
5391 // - Otherwise, X(M) is "lvalue reference to cv A".
5392 assert(Method && !Method->isExplicitObjectMemberFunction() &&
5393 "expected a member function with no explicit object parameter");
5394
5395 RawType = Context.getQualifiedType(RawType, Method->getMethodQualifiers());
5396 if (Method->getRefQualifier() == RQ_RValue ||
5397 (IsOtherRvr && Method->getRefQualifier() == RQ_None))
5398 return Context.getRValueReferenceType(RawType);
5399 return Context.getLValueReferenceType(RawType);
5400}
5401
5402/// Determine whether the function template \p FT1 is at least as
5403/// specialized as \p FT2.
5405 const FunctionTemplateDecl *FT1,
5406 const FunctionTemplateDecl *FT2,
5408 bool Reversed,
5409 const SmallVector<QualType> &Args1,
5410 const SmallVector<QualType> &Args2) {
5411 assert(!Reversed || TPOC == TPOC_Call);
5412
5413 FunctionDecl *FD1 = FT1->getTemplatedDecl();
5414 FunctionDecl *FD2 = FT2->getTemplatedDecl();
5415 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
5416 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
5417
5418 assert(Proto1 && Proto2 && "Function templates must have prototypes");
5419 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
5421 Deduced.resize(TemplateParams->size());
5422
5423 // C++0x [temp.deduct.partial]p3:
5424 // The types used to determine the ordering depend on the context in which
5425 // the partial ordering is done:
5427 switch (TPOC) {
5428 case TPOC_Call:
5429 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
5430 Args1.data(), Args1.size(), Info, Deduced,
5431 TDF_None, /*PartialOrdering=*/true) !=
5433 return false;
5434
5435 break;
5436
5437 case TPOC_Conversion:
5438 // - In the context of a call to a conversion operator, the return types
5439 // of the conversion function templates are used.
5441 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
5442 Info, Deduced, TDF_None,
5443 /*PartialOrdering=*/true) != TemplateDeductionResult::Success)
5444 return false;
5445 break;
5446
5447 case TPOC_Other:
5448 // - In other contexts (14.6.6.2) the function template's function type
5449 // is used.
5451 S, TemplateParams, FD2->getType(), FD1->getType(), Info, Deduced,
5453 /*PartialOrdering=*/true) != TemplateDeductionResult::Success)
5454 return false;
5455 break;
5456 }
5457
5458 // C++0x [temp.deduct.partial]p11:
5459 // In most cases, all template parameters must have values in order for
5460 // deduction to succeed, but for partial ordering purposes a template
5461 // parameter may remain without a value provided it is not used in the
5462 // types being used for partial ordering. [ Note: a template parameter used
5463 // in a non-deduced context is considered used. -end note]
5464 unsigned ArgIdx = 0, NumArgs = Deduced.size();
5465 for (; ArgIdx != NumArgs; ++ArgIdx)
5466 if (Deduced[ArgIdx].isNull())
5467 break;
5468
5469 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
5470 // to substitute the deduced arguments back into the template and check that
5471 // we get the right type.
5472
5473 if (ArgIdx == NumArgs) {
5474 // All template arguments were deduced. FT1 is at least as specialized
5475 // as FT2.
5476 return true;
5477 }
5478
5479 // Figure out which template parameters were used.
5480 llvm::SmallBitVector UsedParameters(TemplateParams->size());
5481 switch (TPOC) {
5482 case TPOC_Call:
5483 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
5484 ::MarkUsedTemplateParameters(S.Context, Args2[I], /*OnlyDeduced=*/false,
5485 TemplateParams->getDepth(), UsedParameters);
5486 break;
5487
5488 case TPOC_Conversion:
5489 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(),
5490 /*OnlyDeduced=*/false,
5491 TemplateParams->getDepth(), UsedParameters);
5492 break;
5493
5494 case TPOC_Other:
5495 // We do not deduce template arguments from the exception specification
5496 // when determining the primary template of a function template
5497 // specialization or when taking the address of a function template.
5498 // Therefore, we do not mark template parameters in the exception
5499 // specification as used during partial ordering to prevent the following
5500 // from being ambiguous:
5501 //
5502 // template<typename T, typename U>
5503 // void f(U) noexcept(noexcept(T())); // #1
5504 //
5505 // template<typename T>
5506 // void f(T*) noexcept; // #2
5507 //
5508 // template<>
5509 // void f<int>(int*) noexcept; // explicit specialization of #2
5510 //
5511 // Although there is no corresponding wording in the standard, this seems
5512 // to be the intended behavior given the definition of
5513 // 'deduction substitution loci' in [temp.deduct].
5515 S.Context,
5517 /*OnlyDeduced=*/false, TemplateParams->getDepth(), UsedParameters);
5518 break;
5519 }
5520
5521 for (; ArgIdx != NumArgs; ++ArgIdx)
5522 // If this argument had no value deduced but was used in one of the types
5523 // used for partial ordering, then deduction fails.
5524 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
5525 return false;
5526
5527 return true;
5528}
5529
5532 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
5533 QualType RawObj1Ty, QualType RawObj2Ty, bool Reversed) {
5536 const FunctionDecl *FD1 = FT1->getTemplatedDecl();
5537 const FunctionDecl *FD2 = FT2->getTemplatedDecl();
5538 bool ShouldConvert1 = false;
5539 bool ShouldConvert2 = false;
5540 QualType Obj1Ty;
5541 QualType Obj2Ty;
5542 if (TPOC == TPOC_Call) {
5543 const FunctionProtoType *Proto1 =
5544 FD1->getType()->castAs<FunctionProtoType>();
5545 const FunctionProtoType *Proto2 =
5546 FD2->getType()->castAs<FunctionProtoType>();
5547
5548 // - In the context of a function call, the function parameter types are
5549 // used.
5550 const CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
5551 const CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
5552 // C++20 [temp.func.order]p3
5553 // [...] Each function template M that is a member function is
5554 // considered to have a new first parameter of type
5555 // X(M), described below, inserted in its function parameter list.
5556 //
5557 // Note that we interpret "that is a member function" as
5558 // "that is a member function with no expicit object argument".
5559 // Otherwise the ordering rules for methods with expicit objet arguments
5560 // against anything else make no sense.
5561 ShouldConvert1 = Method1 && !Method1->isExplicitObjectMemberFunction();
5562 ShouldConvert2 = Method2 && !Method2->isExplicitObjectMemberFunction();
5563 if (ShouldConvert1) {
5564 bool IsRValRef2 =
5565 ShouldConvert2
5566 ? Method2->getRefQualifier() == RQ_RValue
5567 : Proto2->param_type_begin()[0]->isRValueReferenceType();
5568 // Compare 'this' from Method1 against first parameter from Method2.
5569 Obj1Ty = GetImplicitObjectParameterType(this->Context, Method1, RawObj1Ty,
5570 IsRValRef2);
5571 Args1.push_back(Obj1Ty);
5572 }
5573 if (ShouldConvert2) {
5574 bool IsRValRef1 =
5575 ShouldConvert1
5576 ? Method1->getRefQualifier() == RQ_RValue
5577 : Proto1->param_type_begin()[0]->isRValueReferenceType();
5578 // Compare 'this' from Method2 against first parameter from Method1.
5579 Obj2Ty = GetImplicitObjectParameterType(this->Context, Method2, RawObj2Ty,
5580 IsRValRef1);
5581 Args2.push_back(Obj2Ty);
5582 }
5583 size_t NumComparedArguments = NumCallArguments1;
5584 // Either added an argument above or the prototype includes an explicit
5585 // object argument we need to count
5586 if (Method1)
5587 ++NumComparedArguments;
5588
5589 Args1.insert(Args1.end(), Proto1->param_type_begin(),
5590 Proto1->param_type_end());
5591 Args2.insert(Args2.end(), Proto2->param_type_begin(),
5592 Proto2->param_type_end());
5593
5594 // C++ [temp.func.order]p5:
5595 // The presence of unused ellipsis and default arguments has no effect on
5596 // the partial ordering of function templates.
5597 Args1.resize(std::min(Args1.size(), NumComparedArguments));
5598 Args2.resize(std::min(Args2.size(), NumComparedArguments));
5599
5600 if (Reversed)
5601 std::reverse(Args2.begin(), Args2.end());
5602 }
5603 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, Reversed,
5604 Args1, Args2);
5605 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, Reversed,
5606 Args2, Args1);
5607 // C++ [temp.deduct.partial]p10:
5608 // F is more specialized than G if F is at least as specialized as G and G
5609 // is not at least as specialized as F.
5610 if (Better1 != Better2) // We have a clear winner
5611 return Better1 ? FT1 : FT2;
5612
5613 if (!Better1 && !Better2) // Neither is better than the other
5614 return nullptr;
5615
5616 // C++ [temp.deduct.partial]p11:
5617 // ... and if G has a trailing function parameter pack for which F does not
5618 // have a corresponding parameter, and if F does not have a trailing
5619 // function parameter pack, then F is more specialized than G.
5620
5621 SmallVector<QualType> Param1;
5622 Param1.reserve(FD1->param_size() + ShouldConvert1);
5623 if (ShouldConvert1)
5624 Param1.push_back(Obj1Ty);
5625 for (const auto &P : FD1->parameters())
5626 Param1.push_back(P->getType());
5627
5628 SmallVector<QualType> Param2;
5629 Param2.reserve(FD2->param_size() + ShouldConvert2);
5630 if (ShouldConvert2)
5631 Param2.push_back(Obj2Ty);
5632 for (const auto &P : FD2->parameters())
5633 Param2.push_back(P->getType());
5634
5635 unsigned NumParams1 = Param1.size();
5636 unsigned NumParams2 = Param2.size();
5637
5638 bool Variadic1 =
5639 FD1->param_size() && FD1->parameters().back()->isParameterPack();
5640 bool Variadic2 =
5641 FD2->param_size() && FD2->parameters().back()->isParameterPack();
5642 if (Variadic1 != Variadic2) {
5643 if (Variadic1 && NumParams1 > NumParams2)
5644 return FT2;
5645 if (Variadic2 && NumParams2 > NumParams1)
5646 return FT1;
5647 }
5648
5649 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
5650 // there is no wording or even resolution for this issue.
5651 for (int i = 0, e = std::min(NumParams1, NumParams2); i < e; ++i) {
5652 QualType T1 = Param1[i].getCanonicalType();
5653 QualType T2 = Param2[i].getCanonicalType();
5654 auto *TST1 = dyn_cast<TemplateSpecializationType>(T1);
5655 auto *TST2 = dyn_cast<TemplateSpecializationType>(T2);
5656 if (!TST1 || !TST2)
5657 continue;
5658 const TemplateArgument &TA1 = TST1->template_arguments().back();
5659 if (TA1.getKind() == TemplateArgument::Pack) {
5660 assert(TST1->template_arguments().size() ==
5661 TST2->template_arguments().size());
5662 const TemplateArgument &TA2 = TST2->template_arguments().back();
5663 assert(TA2.getKind() == TemplateArgument::Pack);
5664 unsigned PackSize1 = TA1.pack_size();
5665 unsigned PackSize2 = TA2.pack_size();
5666 bool IsPackExpansion1 =
5667 PackSize1 && TA1.pack_elements().back().isPackExpansion();
5668 bool IsPackExpansion2 =
5669 PackSize2 && TA2.pack_elements().back().isPackExpansion();
5670 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
5671 if (PackSize1 > PackSize2 && IsPackExpansion1)
5672 return FT2;
5673 if (PackSize1 < PackSize2 && IsPackExpansion2)
5674 return FT1;
5675 }
5676 }
5677 }
5678
5679 if (!Context.getLangOpts().CPlusPlus20)
5680 return nullptr;
5681
5682 // Match GCC on not implementing [temp.func.order]p6.2.1.
5683
5684 // C++20 [temp.func.order]p6:
5685 // If deduction against the other template succeeds for both transformed
5686 // templates, constraints can be considered as follows:
5687
5688 // C++20 [temp.func.order]p6.1:
5689 // If their template-parameter-lists (possibly including template-parameters
5690 // invented for an abbreviated function template ([dcl.fct])) or function
5691 // parameter lists differ in length, neither template is more specialized
5692 // than the other.
5695 if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
5696 return nullptr;
5697
5698 // C++20 [temp.func.order]p6.2.2:
5699 // Otherwise, if the corresponding template-parameters of the
5700 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
5701 // function parameters that positionally correspond between the two
5702 // templates are not of the same type, neither template is more specialized
5703 // than the other.
5704 if (!TemplateParameterListsAreEqual(TPL1, TPL2, false,
5706 return nullptr;
5707
5708 // [dcl.fct]p5:
5709 // Any top-level cv-qualifiers modifying a parameter type are deleted when
5710 // forming the function type.
5711 for (unsigned i = 0; i < NumParams1; ++i)
5712 if (!Context.hasSameUnqualifiedType(Param1[i], Param2[i]))
5713 return nullptr;
5714
5715 // C++20 [temp.func.order]p6.3:
5716 // Otherwise, if the context in which the partial ordering is done is
5717 // that of a call to a conversion function and the return types of the
5718 // templates are not the same, then neither template is more specialized
5719 // than the other.
5720 if (TPOC == TPOC_Conversion &&
5722 return nullptr;
5723
5725 FT1->getAssociatedConstraints(AC1);
5726 FT2->getAssociatedConstraints(AC2);
5727 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
5728 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
5729 return nullptr;
5730 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
5731 return nullptr;
5732 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
5733 return nullptr;
5734 return AtLeastAsConstrained1 ? FT1 : FT2;
5735}
5736
5737/// Determine if the two templates are equivalent.
5739 if (T1 == T2)
5740 return true;
5741
5742 if (!T1 || !T2)
5743 return false;
5744
5745 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
5746}
5747
5750 TemplateSpecCandidateSet &FailedCandidates,
5751 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
5752 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
5753 bool Complain, QualType TargetType) {
5754 if (SpecBegin == SpecEnd) {
5755 if (Complain) {
5756 Diag(Loc, NoneDiag);
5757 FailedCandidates.NoteCandidates(*this, Loc);
5758 }
5759 return SpecEnd;
5760 }
5761
5762 if (SpecBegin + 1 == SpecEnd)
5763 return SpecBegin;
5764
5765 // Find the function template that is better than all of the templates it
5766 // has been compared to.
5767 UnresolvedSetIterator Best = SpecBegin;
5768 FunctionTemplateDecl *BestTemplate
5769 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
5770 assert(BestTemplate && "Not a function template specialization?");
5771 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
5772 FunctionTemplateDecl *Challenger
5773 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
5774 assert(Challenger && "Not a function template specialization?");
5775 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger, Loc,
5776 TPOC_Other, 0),
5777 Challenger)) {
5778 Best = I;
5779 BestTemplate = Challenger;
5780 }
5781 }
5782
5783 // Make sure that the "best" function template is more specialized than all
5784 // of the others.
5785 bool Ambiguous = false;
5786 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
5787 FunctionTemplateDecl *Challenger
5788 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
5789 if (I != Best &&
5790 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
5791 Loc, TPOC_Other, 0),
5792 BestTemplate)) {
5793 Ambiguous = true;
5794 break;
5795 }
5796 }
5797
5798 if (!Ambiguous) {
5799 // We found an answer. Return it.
5800 return Best;
5801 }
5802
5803 // Diagnose the ambiguity.
5804 if (Complain) {
5805 Diag(Loc, AmbigDiag);
5806
5807 // FIXME: Can we order the candidates in some sane way?
5808 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
5809 PartialDiagnostic PD = CandidateDiag;
5810 const auto *FD = cast<FunctionDecl>(*I);
5812 FD->getPrimaryTemplate()->getTemplateParameters(),
5813 *FD->getTemplateSpecializationArgs());
5814 if (!TargetType.isNull())
5815 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
5816 Diag((*I)->getLocation(), PD);
5817 }
5818 }
5819
5820 return SpecEnd;
5821}
5822
5824 FunctionDecl *FD2) {
5825 assert(!FD1->getDescribedTemplate() && !FD2->getDescribedTemplate() &&
5826 "not for function templates");
5827 FunctionDecl *F1 = FD1;
5829 F1 = MF;
5830 FunctionDecl *F2 = FD2;
5832 F2 = MF;
5834 F1->getAssociatedConstraints(AC1);
5835 F2->getAssociatedConstraints(AC2);
5836 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
5837 if (IsAtLeastAsConstrained(F1, AC1, F2, AC2, AtLeastAsConstrained1))
5838 return nullptr;
5839 if (IsAtLeastAsConstrained(F2, AC2, F1, AC1, AtLeastAsConstrained2))
5840 return nullptr;
5841 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
5842 return nullptr;
5843 return AtLeastAsConstrained1 ? FD1 : FD2;
5844}
5845
5846/// Determine whether one partial specialization, P1, is at least as
5847/// specialized than another, P2.
5848///
5849/// \tparam TemplateLikeDecl The kind of P2, which must be a
5850/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
5851/// \param T1 The injected-class-name of P1 (faked for a variable template).
5852/// \param T2 The injected-class-name of P2 (faked for a variable template).
5853template<typename TemplateLikeDecl>
5855 TemplateLikeDecl *P2,
5856 TemplateDeductionInfo &Info) {
5857 // C++ [temp.class.order]p1:
5858 // For two class template partial specializations, the first is at least as
5859 // specialized as the second if, given the following rewrite to two
5860 // function templates, the first function template is at least as
5861 // specialized as the second according to the ordering rules for function
5862 // templates (14.6.6.2):
5863 // - the first function template has the same template parameters as the
5864 // first partial specialization and has a single function parameter
5865 // whose type is a class template specialization with the template
5866 // arguments of the first partial specialization, and
5867 // - the second function template has the same template parameters as the
5868 // second partial specialization and has a single function parameter
5869 // whose type is a class template specialization with the template
5870 // arguments of the second partial specialization.
5871 //
5872 // Rather than synthesize function templates, we merely perform the
5873 // equivalent partial ordering by performing deduction directly on
5874 // the template arguments of the class template partial
5875 // specializations. This computation is slightly simpler than the
5876 // general problem of function template partial ordering, because
5877 // class template partial specializations are more constrained. We
5878 // know that every template parameter is deducible from the class
5879 // template partial specialization's template arguments, for
5880 // example.
5882
5883 // Determine whether P1 is at least as specialized as P2.
5884 Deduced.resize(P2->getTemplateParameters()->size());
5886 S, P2->getTemplateParameters(), T2, T1, Info, Deduced, TDF_None,
5887 /*PartialOrdering=*/true) != TemplateDeductionResult::Success)
5888 return false;
5889
5890 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
5891 Deduced.end());
5892 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
5893 Info);
5894 if (Inst.isInvalid())
5895 return false;
5896
5897 const auto *TST1 = cast<TemplateSpecializationType>(T1);
5898 bool AtLeastAsSpecialized;
5900 AtLeastAsSpecialized =
5901 FinishTemplateArgumentDeduction(
5902 S, P2, /*IsPartialOrdering=*/true, TST1->template_arguments(),
5903 Deduced, Info) == TemplateDeductionResult::Success;
5904 });
5905 return AtLeastAsSpecialized;
5906}
5907
5908namespace {
5909// A dummy class to return nullptr instead of P2 when performing "more
5910// specialized than primary" check.
5911struct GetP2 {
5912 template <typename T1, typename T2,
5913 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
5914 T2 *operator()(T1 *, T2 *P2) {
5915 return P2;
5916 }
5917 template <typename T1, typename T2,
5918 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
5919 T1 *operator()(T1 *, T2 *) {
5920 return nullptr;
5921 }
5922};
5923
5924// The assumption is that two template argument lists have the same size.
5925struct TemplateArgumentListAreEqual {
5926 ASTContext &Ctx;
5927 TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
5928
5929 template <typename T1, typename T2,
5930 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
5931 bool operator()(T1 *PS1, T2 *PS2) {
5932 ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
5933 Args2 = PS2->getTemplateArgs().asArray();
5934
5935 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
5936 // We use profile, instead of structural comparison of the arguments,
5937 // because canonicalization can't do the right thing for dependent
5938 // expressions.
5939 llvm::FoldingSetNodeID IDA, IDB;
5940 Args1[I].Profile(IDA, Ctx);
5941 Args2[I].Profile(IDB, Ctx);
5942 if (IDA != IDB)
5943 return false;
5944 }
5945 return true;
5946 }
5947
5948 template <typename T1, typename T2,
5949 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
5950 bool operator()(T1 *Spec, T2 *Primary) {
5951 ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
5952 Args2 = Primary->getInjectedTemplateArgs();
5953
5954 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
5955 // We use profile, instead of structural comparison of the arguments,
5956 // because canonicalization can't do the right thing for dependent
5957 // expressions.
5958 llvm::FoldingSetNodeID IDA, IDB;
5959 Args1[I].Profile(IDA, Ctx);
5960 // Unlike the specialization arguments, the injected arguments are not
5961 // always canonical.
5962 Ctx.getCanonicalTemplateArgument(Args2[I]).Profile(IDB, Ctx);
5963 if (IDA != IDB)
5964 return false;
5965 }
5966 return true;
5967 }
5968};
5969} // namespace
5970
5971/// Returns the more specialized template specialization between T1/P1 and
5972/// T2/P2.
5973/// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
5974/// specialization and T2/P2 is the primary template.
5975/// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
5976///
5977/// \param T1 the type of the first template partial specialization
5978///
5979/// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
5980/// template partial specialization; otherwise, the type of the
5981/// primary template.
5982///
5983/// \param P1 the first template partial specialization
5984///
5985/// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
5986/// partial specialization; otherwise, the primary template.
5987///
5988/// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
5989/// more specialized, returns nullptr if P1 is not more specialized.
5990/// - otherwise, returns the more specialized template partial
5991/// specialization. If neither partial specialization is more
5992/// specialized, returns NULL.
5993template <typename TemplateLikeDecl, typename PrimaryDel>
5994static TemplateLikeDecl *
5995getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
5996 PrimaryDel *P2, TemplateDeductionInfo &Info) {
5997 constexpr bool IsMoreSpecialThanPrimaryCheck =
5998 !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
5999
6000 bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, Info);
6001 if (IsMoreSpecialThanPrimaryCheck && !Better1)
6002 return nullptr;
6003
6004 bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1, Info);
6005 if (IsMoreSpecialThanPrimaryCheck && !Better2)
6006 return P1;
6007
6008 // C++ [temp.deduct.partial]p10:
6009 // F is more specialized than G if F is at least as specialized as G and G
6010 // is not at least as specialized as F.
6011 if (Better1 != Better2) // We have a clear winner
6012 return Better1 ? P1 : GetP2()(P1, P2);
6013
6014 if (!Better1 && !Better2)
6015 return nullptr;
6016
6017 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
6018 // there is no wording or even resolution for this issue.
6019 auto *TST1 = cast<TemplateSpecializationType>(T1);
6020 auto *TST2 = cast<TemplateSpecializationType>(T2);
6021 const TemplateArgument &TA1 = TST1->template_arguments().back();
6022 if (TA1.getKind() == TemplateArgument::Pack) {
6023 assert(TST1->template_arguments().size() ==
6024 TST2->template_arguments().size());
6025 const TemplateArgument &TA2 = TST2->template_arguments().back();
6026 assert(TA2.getKind() == TemplateArgument::Pack);
6027 unsigned PackSize1 = TA1.pack_size();
6028 unsigned PackSize2 = TA2.pack_size();
6029 bool IsPackExpansion1 =
6030 PackSize1 && TA1.pack_elements().back().isPackExpansion();
6031 bool IsPackExpansion2 =
6032 PackSize2 && TA2.pack_elements().back().isPackExpansion();
6033 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
6034 if (PackSize1 > PackSize2 && IsPackExpansion1)
6035 return GetP2()(P1, P2);
6036 if (PackSize1 < PackSize2 && IsPackExpansion2)
6037 return P1;
6038 }
6039 }
6040
6041 if (!S.Context.getLangOpts().CPlusPlus20)
6042 return nullptr;
6043
6044 // Match GCC on not implementing [temp.func.order]p6.2.1.
6045
6046 // C++20 [temp.func.order]p6:
6047 // If deduction against the other template succeeds for both transformed
6048 // templates, constraints can be considered as follows:
6049
6050 TemplateParameterList *TPL1 = P1->getTemplateParameters();
6051 TemplateParameterList *TPL2 = P2->getTemplateParameters();
6052 if (TPL1->size() != TPL2->size())
6053 return nullptr;
6054
6055 // C++20 [temp.func.order]p6.2.2:
6056 // Otherwise, if the corresponding template-parameters of the
6057 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6058 // function parameters that positionally correspond between the two
6059 // templates are not of the same type, neither template is more specialized
6060 // than the other.
6061 if (!S.TemplateParameterListsAreEqual(TPL1, TPL2, false,
6063 return nullptr;
6064
6065 if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
6066 return nullptr;
6067
6069 P1->getAssociatedConstraints(AC1);
6070 P2->getAssociatedConstraints(AC2);
6071 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6072 if (S.IsAtLeastAsConstrained(P1, AC1, P2, AC2, AtLeastAsConstrained1) ||
6073 (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
6074 return nullptr;
6075 if (S.IsAtLeastAsConstrained(P2, AC2, P1, AC1, AtLeastAsConstrained2))
6076 return nullptr;
6077 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6078 return nullptr;
6079 return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
6080}
6081
6089
6091 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6092}
6093
6096 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
6097 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
6098 QualType PartialT = Spec->getInjectedSpecializationType();
6099
6101 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6102 if (MaybeSpec)
6103 Info.clearSFINAEDiagnostic();
6104 return MaybeSpec;
6105}
6106
6111 // Pretend the variable template specializations are class template
6112 // specializations and form a fake injected class name type for comparison.
6113 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
6114 "the partial specializations being compared should specialize"
6115 " the same template.");
6117 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6119 CanonTemplate, PS1->getTemplateArgs().asArray());
6121 CanonTemplate, PS2->getTemplateArgs().asArray());
6122
6124 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6125}
6126
6129 VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
6130 TemplateName CanonTemplate =
6133 CanonTemplate, Primary->getInjectedTemplateArgs());
6135 CanonTemplate, Spec->getTemplateArgs().asArray());
6136
6138 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6139 if (MaybeSpec)
6140 Info.clearSFINAEDiagnostic();
6141 return MaybeSpec;
6142}
6143
6146 bool IsDeduced) {
6147 // C++1z [temp.arg.template]p4: (DR 150)
6148 // A template template-parameter P is at least as specialized as a
6149 // template template-argument A if, given the following rewrite to two
6150 // function templates...
6151
6152 // Rather than synthesize function templates, we merely perform the
6153 // equivalent partial ordering by performing deduction directly on
6154 // the template parameter lists of the template template parameters.
6155 //
6157
6158 // Given an invented class template X with the template parameter list of
6159 // A (including default arguments):
6160 // - Each function template has a single function parameter whose type is
6161 // a specialization of X with template arguments corresponding to the
6162 // template parameters from the respective function template
6165
6166 // Check P's arguments against A's parameter list. This will fill in default
6167 // template arguments as needed. AArgs are already correct by construction.
6168 // We can't just use CheckTemplateIdType because that will expand alias
6169 // templates.
6171 {
6172 SFINAETrap Trap(*this);
6173
6175 TemplateArgumentListInfo PArgList(P->getLAngleLoc(),
6176 P->getRAngleLoc());
6177 for (unsigned I = 0, N = P->size(); I != N; ++I) {
6178 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
6179 // expansions, to form an "as written" argument list.
6180 TemplateArgument Arg = PArgs[I];
6181 if (Arg.getKind() == TemplateArgument::Pack) {
6182 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
6183 Arg = *Arg.pack_begin();
6184 }
6186 Arg, QualType(), P->getParam(I)->getLocation()));
6187 }
6188 PArgs.clear();
6189
6190 // C++1z [temp.arg.template]p3:
6191 // If the rewrite produces an invalid type, then P is not at least as
6192 // specialized as A.
6194 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, SugaredPArgs,
6195 PArgs, /*UpdateArgsWithConversions=*/true,
6196 /*ConstraintsNotSatisfied=*/nullptr,
6197 /*PartialOrderTTP=*/true) ||
6198 Trap.hasErrorOccurred())
6199 return false;
6200 }
6201
6202 // Determine whether P1 is at least as specialized as P2.
6205 Deduced.resize(A->size());
6206
6207 // ... the function template corresponding to P is at least as specialized
6208 // as the function template corresponding to A according to the partial
6209 // ordering rules for function templates.
6210
6211 // Provisional resolution for CWG2398: Regarding temp.arg.template]p4, when
6212 // applying the partial ordering rules for function templates on
6213 // the rewritten template template parameters:
6214 // - In a deduced context, the matching of packs versus fixed-size needs to
6215 // be inverted between Ps and As. On non-deduced context, matching needs to
6216 // happen both ways, according to [temp.arg.template]p3, but this is
6217 // currently implemented as a special case elsewhere.
6218 if (::DeduceTemplateArguments(*this, A, AArgs, PArgs, Info, Deduced,
6219 /*NumberOfArgumentsMustMatch=*/false,
6220 IsDeduced ? PackFold::ArgumentToParameter
6221 : PackFold::ParameterToArgument) !=
6223 return false;
6224
6225 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
6226 Sema::InstantiatingTemplate Inst(*this, Info.getLocation(), AArg, DeducedArgs,
6227 Info);
6228 if (Inst.isInvalid())
6229 return false;
6230
6231 bool AtLeastAsSpecialized;
6233 AtLeastAsSpecialized =
6234 ::FinishTemplateArgumentDeduction(
6235 *this, AArg, /*IsPartialOrdering=*/true, PArgs, Deduced, Info) ==
6236 TemplateDeductionResult::Success;
6237 });
6238 return AtLeastAsSpecialized;
6239}
6240
6241namespace {
6242struct MarkUsedTemplateParameterVisitor :
6243 RecursiveASTVisitor<MarkUsedTemplateParameterVisitor> {
6244 llvm::SmallBitVector &Used;
6245 unsigned Depth;
6246
6247 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used,
6248 unsigned Depth)
6249 : Used(Used), Depth(Depth) { }
6250
6251 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
6252 if (T->getDepth() == Depth)
6253 Used[T->getIndex()] = true;
6254 return true;
6255 }
6256
6257 bool TraverseTemplateName(TemplateName Template) {
6258 if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
6259 Template.getAsTemplateDecl()))
6260 if (TTP->getDepth() == Depth)
6261 Used[TTP->getIndex()] = true;
6263 TraverseTemplateName(Template);
6264 return true;
6265 }
6266
6267 bool VisitDeclRefExpr(DeclRefExpr *E) {
6268 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
6269 if (NTTP->getDepth() == Depth)
6270 Used[NTTP->getIndex()] = true;
6271 return true;
6272 }
6273};
6274}
6275
6276/// Mark the template parameters that are used by the given
6277/// expression.
6278static void
6280 const Expr *E,
6281 bool OnlyDeduced,
6282 unsigned Depth,
6283 llvm::SmallBitVector &Used) {
6284 if (!OnlyDeduced) {
6285 MarkUsedTemplateParameterVisitor(Used, Depth)
6286 .TraverseStmt(const_cast<Expr *>(E));
6287 return;
6288 }
6289
6290 // We can deduce from a pack expansion.
6291 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
6292 E = Expansion->getPattern();
6293
6295 if (!NTTP)
6296 return;
6297
6298 if (NTTP->getDepth() == Depth)
6299 Used[NTTP->getIndex()] = true;
6300
6301 // In C++17 mode, additional arguments may be deduced from the type of a
6302 // non-type argument.
6303 if (Ctx.getLangOpts().CPlusPlus17)
6304 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
6305}
6306
6307/// Mark the template parameters that are used by the given
6308/// nested name specifier.
6309static void
6312 bool OnlyDeduced,
6313 unsigned Depth,
6314 llvm::SmallBitVector &Used) {
6315 if (!NNS)
6316 return;
6317
6318 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
6319 Used);
6321 OnlyDeduced, Depth, Used);
6322}
6323
6324/// Mark the template parameters that are used by the given
6325/// template name.
6326static void
6328 TemplateName Name,
6329 bool OnlyDeduced,
6330 unsigned Depth,
6331 llvm::SmallBitVector &Used) {
6332 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
6334 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
6335 if (TTP->getDepth() == Depth)
6336 Used[TTP->getIndex()] = true;
6337 }
6338 return;
6339 }
6340
6341 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
6342 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
6343 Depth, Used);
6344 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
6345 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
6346 Depth, Used);
6347}
6348
6349/// Mark the template parameters that are used by the given
6350/// type.
6351static void
6353 bool OnlyDeduced,
6354 unsigned Depth,
6355 llvm::SmallBitVector &Used) {
6356 if (T.isNull())
6357 return;
6358
6359 // Non-dependent types have nothing deducible
6360 if (!T->isDependentType())
6361 return;
6362
6363 T = Ctx.getCanonicalType(T);
6364 switch (T->getTypeClass()) {
6365 case Type::Pointer:
6367 cast<PointerType>(T)->getPointeeType(),
6368 OnlyDeduced,
6369 Depth,
6370 Used);
6371 break;
6372
6373 case Type::BlockPointer:
6375 cast<BlockPointerType>(T)->getPointeeType(),
6376 OnlyDeduced,
6377 Depth,
6378 Used);
6379 break;
6380
6381 case Type::LValueReference:
6382 case Type::RValueReference:
6384 cast<ReferenceType>(T)->getPointeeType(),
6385 OnlyDeduced,
6386 Depth,
6387 Used);
6388 break;
6389
6390 case Type::MemberPointer: {
6391 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
6392 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
6393 Depth, Used);
6394 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
6395 OnlyDeduced, Depth, Used);
6396 break;
6397 }
6398
6399 case Type::DependentSizedArray:
6401 cast<DependentSizedArrayType>(T)->getSizeExpr(),
6402 OnlyDeduced, Depth, Used);
6403 // Fall through to check the element type
6404 [[fallthrough]];
6405
6406 case Type::ConstantArray:
6407 case Type::IncompleteArray:
6408 case Type::ArrayParameter:
6410 cast<ArrayType>(T)->getElementType(),
6411 OnlyDeduced, Depth, Used);
6412 break;
6413 case Type::Vector:
6414 case Type::ExtVector:
6416 cast<VectorType>(T)->getElementType(),
6417 OnlyDeduced, Depth, Used);
6418 break;
6419
6420 case Type::DependentVector: {
6421 const auto *VecType = cast<DependentVectorType>(T);
6422 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6423 Depth, Used);
6424 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
6425 Used);
6426 break;
6427 }
6428 case Type::DependentSizedExtVector: {
6429 const DependentSizedExtVectorType *VecType
6430 = cast<DependentSizedExtVectorType>(T);
6431 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6432 Depth, Used);
6433 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
6434 Depth, Used);
6435 break;
6436 }
6437
6438 case Type::DependentAddressSpace: {
6439 const DependentAddressSpaceType *DependentASType =
6440 cast<DependentAddressSpaceType>(T);
6441 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
6442 OnlyDeduced, Depth, Used);
6444 DependentASType->getAddrSpaceExpr(),
6445 OnlyDeduced, Depth, Used);
6446 break;
6447 }
6448
6449 case Type::ConstantMatrix: {
6450 const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T);
6451 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6452 Depth, Used);
6453 break;
6454 }
6455
6456 case Type::DependentSizedMatrix: {
6457 const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(T);
6458 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6459 Depth, Used);
6460 MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
6461 Used);
6462 MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
6463 Depth, Used);
6464 break;
6465 }
6466
6467 case Type::FunctionProto: {
6468 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
6469 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
6470 Used);
6471 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
6472 // C++17 [temp.deduct.type]p5:
6473 // The non-deduced contexts are: [...]
6474 // -- A function parameter pack that does not occur at the end of the
6475 // parameter-declaration-list.
6476 if (!OnlyDeduced || I + 1 == N ||
6477 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
6478 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
6479 Depth, Used);
6480 } else {
6481 // FIXME: C++17 [temp.deduct.call]p1:
6482 // When a function parameter pack appears in a non-deduced context,
6483 // the type of that pack is never deduced.
6484 //
6485 // We should also track a set of "never deduced" parameters, and
6486 // subtract that from the list of deduced parameters after marking.
6487 }
6488 }
6489 if (auto *E = Proto->getNoexceptExpr())
6490 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
6491 break;
6492 }
6493
6494 case Type::TemplateTypeParm: {
6495 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
6496 if (TTP->getDepth() == Depth)
6497 Used[TTP->getIndex()] = true;
6498 break;
6499 }
6500
6501 case Type::SubstTemplateTypeParmPack: {
6503 = cast<SubstTemplateTypeParmPackType>(T);
6504 if (Subst->getReplacedParameter()->getDepth() == Depth)
6505 Used[Subst->getIndex()] = true;
6507 OnlyDeduced, Depth, Used);
6508 break;
6509 }
6510
6511 case Type::InjectedClassName:
6512 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
6513 [[fallthrough]];
6514
6515 case Type::TemplateSpecialization: {
6516 const TemplateSpecializationType *Spec
6517 = cast<TemplateSpecializationType>(T);
6518 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
6519 Depth, Used);
6520
6521 // C++0x [temp.deduct.type]p9:
6522 // If the template argument list of P contains a pack expansion that is
6523 // not the last template argument, the entire template argument list is a
6524 // non-deduced context.
6525 if (OnlyDeduced &&
6527 break;
6528
6529 for (const auto &Arg : Spec->template_arguments())
6530 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6531 break;
6532 }
6533
6534 case Type::Complex:
6535 if (!OnlyDeduced)
6537 cast<ComplexType>(T)->getElementType(),
6538 OnlyDeduced, Depth, Used);
6539 break;
6540
6541 case Type::Atomic:
6542 if (!OnlyDeduced)
6544 cast<AtomicType>(T)->getValueType(),
6545 OnlyDeduced, Depth, Used);
6546 break;
6547
6548 case Type::DependentName:
6549 if (!OnlyDeduced)
6551 cast<DependentNameType>(T)->getQualifier(),
6552 OnlyDeduced, Depth, Used);
6553 break;
6554
6555 case Type::DependentTemplateSpecialization: {
6556 // C++14 [temp.deduct.type]p5:
6557 // The non-deduced contexts are:
6558 // -- The nested-name-specifier of a type that was specified using a
6559 // qualified-id
6560 //
6561 // C++14 [temp.deduct.type]p6:
6562 // When a type name is specified in a way that includes a non-deduced
6563 // context, all of the types that comprise that type name are also
6564 // non-deduced.
6565 if (OnlyDeduced)
6566 break;
6567
6569 = cast<DependentTemplateSpecializationType>(T);
6570
6572 OnlyDeduced, Depth, Used);
6573
6574 for (const auto &Arg : Spec->template_arguments())
6575 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6576 break;
6577 }
6578
6579 case Type::TypeOf:
6580 if (!OnlyDeduced)
6581 MarkUsedTemplateParameters(Ctx, cast<TypeOfType>(T)->getUnmodifiedType(),
6582 OnlyDeduced, Depth, Used);
6583 break;
6584
6585 case Type::TypeOfExpr:
6586 if (!OnlyDeduced)
6588 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
6589 OnlyDeduced, Depth, Used);
6590 break;
6591
6592 case Type::Decltype:
6593 if (!OnlyDeduced)
6595 cast<DecltypeType>(T)->getUnderlyingExpr(),
6596 OnlyDeduced, Depth, Used);
6597 break;
6598
6599 case Type::PackIndexing:
6600 if (!OnlyDeduced) {
6601 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getPattern(),
6602 OnlyDeduced, Depth, Used);
6603 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getIndexExpr(),
6604 OnlyDeduced, Depth, Used);
6605 }
6606 break;
6607
6608 case Type::UnaryTransform:
6609 if (!OnlyDeduced)
6611 cast<UnaryTransformType>(T)->getUnderlyingType(),
6612 OnlyDeduced, Depth, Used);
6613 break;
6614
6615 case Type::PackExpansion:
6617 cast<PackExpansionType>(T)->getPattern(),
6618 OnlyDeduced, Depth, Used);
6619 break;
6620
6621 case Type::Auto:
6622 case Type::DeducedTemplateSpecialization:
6624 cast<DeducedType>(T)->getDeducedType(),
6625 OnlyDeduced, Depth, Used);
6626 break;
6627 case Type::DependentBitInt:
6629 cast<DependentBitIntType>(T)->getNumBitsExpr(),
6630 OnlyDeduced, Depth, Used);
6631 break;
6632
6633 // None of these types have any template parameters in them.
6634 case Type::Builtin:
6635 case Type::VariableArray:
6636 case Type::FunctionNoProto:
6637 case Type::Record:
6638 case Type::Enum:
6639 case Type::ObjCInterface:
6640 case Type::ObjCObject:
6641 case Type::ObjCObjectPointer:
6642 case Type::UnresolvedUsing:
6643 case Type::Pipe:
6644 case Type::BitInt:
6645#define TYPE(Class, Base)
6646#define ABSTRACT_TYPE(Class, Base)
6647#define DEPENDENT_TYPE(Class, Base)
6648#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6649#include "clang/AST/TypeNodes.inc"
6650 break;
6651 }
6652}
6653
6654/// Mark the template parameters that are used by this
6655/// template argument.
6656static void
6659 bool OnlyDeduced,
6660 unsigned Depth,
6661 llvm::SmallBitVector &Used) {
6662 switch (TemplateArg.getKind()) {
6668 break;
6669
6671 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
6672 Depth, Used);
6673 break;
6674
6678 TemplateArg.getAsTemplateOrTemplatePattern(),
6679 OnlyDeduced, Depth, Used);
6680 break;
6681
6683 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
6684 Depth, Used);
6685 break;
6686
6688 for (const auto &P : TemplateArg.pack_elements())
6689 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
6690 break;
6691 }
6692}
6693
6694void
6695Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
6696 unsigned Depth,
6697 llvm::SmallBitVector &Used) {
6698 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
6699}
6700
6701void
6703 bool OnlyDeduced, unsigned Depth,
6704 llvm::SmallBitVector &Used) {
6705 // C++0x [temp.deduct.type]p9:
6706 // If the template argument list of P contains a pack expansion that is not
6707 // the last template argument, the entire template argument list is a
6708 // non-deduced context.
6709 if (OnlyDeduced &&
6710 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
6711 return;
6712
6713 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6714 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
6715 Depth, Used);
6716}
6717
6719 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
6720 llvm::SmallBitVector &Deduced) {
6721 TemplateParameterList *TemplateParams
6722 = FunctionTemplate->getTemplateParameters();
6723 Deduced.clear();
6724 Deduced.resize(TemplateParams->size());
6725
6726 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
6727 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
6728 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
6729 true, TemplateParams->getDepth(), Deduced);
6730}
6731
6733 FunctionTemplateDecl *FunctionTemplate,
6734 QualType T) {
6735 if (!T->isDependentType())
6736 return false;
6737
6738 TemplateParameterList *TemplateParams
6739 = FunctionTemplate->getTemplateParameters();
6740 llvm::SmallBitVector Deduced(TemplateParams->size());
6741 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
6742 Deduced);
6743
6744 return Deduced.any();
6745}
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:1152
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 CXXRecordDecl * getCanonicalRD(QualType T)
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 bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2)
Determine if the two templates are equivalent.
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:186
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2822
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:2625
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2641
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:2828
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:1146
CanQualType NullPtrTy
Definition: ASTContext.h:1145
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:1634
const LangOptions & getLangOpts() const
Definition: ASTContext.h:796
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:1119
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:1127
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2207
LangAS getDefaultOpenCLPointeeAddrSpace()
Returns default address space based on OpenCL version and enabled features.
Definition: ASTContext.h:1459
CanQualType OverloadTy
Definition: ASTContext.h:1146
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2672
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:2391
CanQualType UnsignedIntTy
Definition: ASTContext.h:1128
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:1612
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:2831
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:6368
ArrayRef< TemplateArgument > getTypeConstraintArguments() const
Definition: Type.h:6378
bool isDecltypeAuto() const
Definition: Type.h:6391
ConceptDecl * getTypeConstraintConcept() const
Definition: Type.h:6383
AutoTypeKeyword getKeyword() const
Definition: Type.h:6399
bool isConstrained() const
Definition: Type.h:6387
A fixed int type of a specified bitwidth.
Definition: Type.h:7626
Pointer to a block type.
Definition: Type.h:3371
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2902
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
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:2457
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2236
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2221
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:619
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1597
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:3108
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:4189
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4210
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4207
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:1425
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2079
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:1205
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:242
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1196
bool isInvalidDecl() const
Definition: DeclBase.h:594
SourceLocation getLocation() const
Definition: DeclBase.h:445
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:232
DeclContext * getDeclContext()
Definition: DeclBase.h:454
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:897
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:957
Kind getKind() const
Definition: DeclBase.h:448
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:433
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:6435
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6334
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3881
Expr * getAddrSpaceExpr() const
Definition: Type.h:3892
QualType getPointeeType() const
Definition: Type.h:3893
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3921
QualType getElementType() const
Definition: Type.h:3936
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4248
Expr * getColumnExpr() const
Definition: Type.h:4261
Expr * getRowExpr() const
Definition: Type.h:4260
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:6888
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6907
NestedNameSpecifier * getQualifier() const
Definition: Type.h:6904
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4043
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6755
RAII object that enters a new expression evaluation context.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1897
bool isInvalid() const
Determine if the explicit specifier is invalid.
Definition: DeclCXX.h:1926
const Expr * getExpr() const
Definition: DeclCXX.h:1906
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:4083
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
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4030
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:4101
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4166
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
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4002
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:4973
param_type_iterator param_type_begin() const
Definition: Type.h:5386
const ExtParameterInfo * getExtParameterInfosOrNull() const
Return a pointer to the beginning of the array of extra parameter information, if present,...
Definition: Type.h:5424
unsigned getNumParams() const
Definition: Type.h:5226
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: Type.h:5366
QualType getParamType(unsigned i) const
Definition: Type.h:5228
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5259
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5237
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:5311
param_type_iterator param_type_end() const
Definition: Type.h:5390
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5233
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:4278
QualType getReturnType() const
Definition: Type.h:4600
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:6605
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3446
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:4153
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4167
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3482
QualType getPointeeType() const
Definition: Type.h:3498
const Type * getClass() const
Definition: Type.h:3512
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:7392
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:4178
Represents a pack expansion of types.
Definition: Type.h:6953
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:6974
std::optional< unsigned > getNumExpansions() const
Retrieve the number of expansions that this pack expansion will generate, if known.
Definition: Type.h:6978
bool hasSelectedType() const
Definition: Type.h:5822
QualType getSelectedType() const
Definition: Type.h:5815
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:3161
QualType getPointeeType() const
Definition: Type.h:3171
A (possibly-)qualified type.
Definition: Type.h:941
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7832
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:7743
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7869
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7783
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:7944
QualType getCanonicalType() const
Definition: Type.h:7795
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7837
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7864
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7789
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:3464
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5936
RecordDecl * getDecl() const
Definition: Type.h:5946
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:3402
QualType getPointeeType() const
Definition: Type.h:3420
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:13186
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8057
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3010
A helper class for building up ExtParameterInfos.
Definition: Sema.h:12608
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:12627
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12080
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12110
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:12637
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:1164
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:6450
@ CTAK_DeducedFromArrayBound
The template argument was deduced from an array bound via template argument deduction.
Definition: Sema.h:11647
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:11639
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition: Sema.h:11643
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition: Sema.h:1002
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:2605
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
ASTContext & getASTContext() const
Definition: Sema.h:600
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:694
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:908
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:11817
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:593
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:14345
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:1137
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition: Sema.h:12143
QualType getDecltypeForExpr(Expr *E)
getDecltypeForExpr - Given an expr, will return the decltype for that expression, according to the ru...
Definition: SemaType.cpp:9397
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20694
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:14915
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:8860
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:566
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:7997
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:12481
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:6276
TemplateArgument getArgumentPack() const
Definition: Type.cpp:4237
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
Definition: Type.h:6302
const TemplateTypeParmDecl * getReplacedParameter() const
Gets the template parameter declaration that was substituted for.
Definition: Type.cpp:4229
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4714
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:6473
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6541
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6539
QualType desugar() const
Definition: Type.h:6550
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:6166
unsigned getDepth() const
Definition: Type.h:6165
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
const Type * getTypeForDecl() const
Definition: Decl.h:3387
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:7714
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
bool isVoidType() const
Definition: Type.h:8295
bool isIncompleteArrayType() const
Definition: Type.h:8072
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:8271
bool isRValueReferenceType() const
Definition: Type.h:8018
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8453
bool isArrayType() const
Definition: Type.h:8064
bool isFunctionPointerType() const
Definition: Type.h:8032
bool isPointerType() const
Definition: Type.h:7996
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8583
bool isReferenceType() const
Definition: Type.h:8010
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:2777
bool isLValueReferenceType() const
Definition: Type.h:8014
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2672
QualType getCanonicalTypeInternal() const
Definition: Type.h:2955
bool isMemberPointerType() const
Definition: Type.h:8046
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4961
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8429
bool isFunctionType() const
Definition: Type.h:7992
bool isObjCObjectPointerType() const
Definition: Type.h:8134
bool isMemberFunctionPointerType() const
Definition: Type.h:8050
bool isAnyPointerType() const
Definition: Type.h:8000
TypeClass getTypeClass() const
Definition: Type.h:2316
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2342
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8516
bool isRecordType() const
Definition: Type.h:8092
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:3991
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
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:275
@ 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:5030
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5032
Extra information about a function prototype.
Definition: Type.h:5058
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:5066
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5059
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition: Sema.h:12675
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:12682
A stack object to be created when performing template instantiation.
Definition: Sema.h:12839
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:12993
brief A function argument from which we performed template argument
Definition: Sema.h:12243
Location information for a TemplateArgument.
Definition: TemplateBase.h:472