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