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