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