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