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