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