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