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 // Substituting the function type can instantiate the trailing return type,
4837 // so handle the same immediate-context substitution failure here.
4838 if (Trap.hasErrorOccurred())
4839 return TemplateDeductionResult::SubstitutionFailure;
4840 }
4841
4842 TemplateDeductionResult Result;
4843 runWithSufficientStackSpace(Loc: Info.getLocation(), Fn: [&] {
4844 Result = FinishTemplateArgumentDeduction(
4845 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4846 /*OriginalCallArgs=*/nullptr, /*PartialOverloading=*/false,
4847 /*PartialOrdering=*/true, ForOverloadSetAddressResolution: IsAddressOfFunction);
4848 });
4849 // Taking the address of a function template forms its function type, and
4850 // substituting into that type can require instantiating a trailing return
4851 // type whose expression selects a deleted function. That is a deduction
4852 // failure, not a hard error:
4853 //
4854 // C++ [temp.deduct.funcaddr]p1:
4855 // [...] If there is a target, the function template's function type and
4856 // the target type are used as the types of P and A, and the deduction is
4857 // done as described in [temp.deduct.type].
4858 //
4859 // C++ [temp.deduct.general]p7:
4860 // [...] The substitution occurs in all types and expressions that are
4861 // used in the deduction substitution loci. The expressions include [...]
4862 // general expressions (i.e., non-constant expressions) inside sizeof,
4863 // decltype, and other contexts that allow non-constant expressions. [...]
4864 //
4865 // C++ [dcl.fct.def.delete]p2:
4866 // A construct that designates a deleted function implicitly or
4867 // explicitly, other than to declare it [...], is ill-formed.
4868 // [Note: [...] It applies even for references in expressions that are not
4869 // potentially evaluated. - end note]
4870 //
4871 // C++ [temp.deduct.general]p8:
4872 // If a substitution results in an invalid type or expression, type
4873 // deduction fails. [...] Invalid types and expressions can result in a
4874 // deduction failure only in the immediate context of the deduction
4875 // substitution loci. [...]
4876 //
4877 // This substitution is in that immediate context, so treat diagnostics
4878 // recorded by the SFINAE trap as deduction failure instead of replaying
4879 // them as hard errors.
4880 if (Trap.hasErrorOccurred()) {
4881 if (Specialization)
4882 Specialization->setInvalidDecl(true);
4883 return TemplateDeductionResult::SubstitutionFailure;
4884 }
4885 if (Result != TemplateDeductionResult::Success)
4886 return Result;
4887
4888 // If the function has a deduced return type, deduce it now, so we can check
4889 // that the deduced function type matches the requested type.
4890 if (HasDeducedReturnType && IsAddressOfFunction &&
4891 Specialization->getReturnType()->isUndeducedType() &&
4892 DeduceReturnType(FD: Specialization, Loc: Info.getLocation(), Diagnose: false))
4893 return TemplateDeductionResult::MiscellaneousDeductionFailure;
4894
4895 // [C++26][expr.const]/p17
4896 // An expression or conversion is immediate-escalating if it is not initially
4897 // in an immediate function context and it is [...]
4898 // a potentially-evaluated id-expression that denotes an immediate function.
4899 if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
4900 Specialization->isImmediateEscalating() && PotentiallyEvaluated &&
4901 CheckIfFunctionSpecializationIsImmediate(FD: Specialization,
4902 Loc: Info.getLocation()))
4903 return TemplateDeductionResult::MiscellaneousDeductionFailure;
4904
4905 // Adjust the exception specification of the argument to match the
4906 // substituted and resolved type we just formed. (Calling convention and
4907 // noreturn can't be dependent, so we don't actually need this for them
4908 // right now.)
4909 QualType SpecializationType = Specialization->getType();
4910 if (!IsAddressOfFunction) {
4911 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType: SpecializationType,
4912 /*AdjustExceptionSpec*/true);
4913
4914 // Revert placeholder types in the return type back to undeduced types so
4915 // that the comparison below compares the declared return types.
4916 if (HasDeducedReturnType) {
4917 SpecializationType = SubstAutoType(TypeWithAuto: SpecializationType, Replacement: QualType());
4918 ArgFunctionType = SubstAutoType(TypeWithAuto: ArgFunctionType, Replacement: QualType());
4919 }
4920 }
4921
4922 // If the requested function type does not match the actual type of the
4923 // specialization with respect to arguments of compatible pointer to function
4924 // types, template argument deduction fails.
4925 if (!ArgFunctionType.isNull()) {
4926 if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
4927 P: SpecializationType, A: ArgFunctionType)
4928 : !Context.hasSameFunctionTypeIgnoringExceptionSpec(
4929 T: SpecializationType, U: ArgFunctionType)) {
4930 Info.FirstArg = TemplateArgument(SpecializationType);
4931 Info.SecondArg = TemplateArgument(ArgFunctionType);
4932 return TemplateDeductionResult::NonDeducedMismatch;
4933 }
4934 }
4935
4936 return TemplateDeductionResult::Success;
4937}
4938
4939TemplateDeductionResult Sema::DeduceTemplateArguments(
4940 FunctionTemplateDecl *ConversionTemplate, QualType ObjectType,
4941 Expr::Classification ObjectClassification, QualType A,
4942 CXXConversionDecl *&Specialization, TemplateDeductionInfo &Info) {
4943 if (ConversionTemplate->isInvalidDecl())
4944 return TemplateDeductionResult::Invalid;
4945
4946 CXXConversionDecl *ConversionGeneric
4947 = cast<CXXConversionDecl>(Val: ConversionTemplate->getTemplatedDecl());
4948
4949 QualType P = ConversionGeneric->getConversionType();
4950 bool IsReferenceP = P->isReferenceType();
4951 bool IsReferenceA = A->isReferenceType();
4952
4953 // C++0x [temp.deduct.conv]p2:
4954 // If P is a reference type, the type referred to by P is used for
4955 // type deduction.
4956 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4957 P = PRef->getPointeeType();
4958
4959 // C++0x [temp.deduct.conv]p4:
4960 // [...] If A is a reference type, the type referred to by A is used
4961 // for type deduction.
4962 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4963 A = ARef->getPointeeType();
4964 // We work around a defect in the standard here: cv-qualifiers are also
4965 // removed from P and A in this case, unless P was a reference type. This
4966 // seems to mostly match what other compilers are doing.
4967 if (!IsReferenceP) {
4968 A = A.getUnqualifiedType();
4969 P = P.getUnqualifiedType();
4970 }
4971
4972 // C++ [temp.deduct.conv]p3:
4973 //
4974 // If A is not a reference type:
4975 } else {
4976 assert(!A->isReferenceType() && "Reference types were handled above");
4977
4978 // - If P is an array type, the pointer type produced by the
4979 // array-to-pointer standard conversion (4.2) is used in place
4980 // of P for type deduction; otherwise,
4981 if (P->isArrayType())
4982 P = Context.getArrayDecayedType(T: P);
4983 // - If P is a function type, the pointer type produced by the
4984 // function-to-pointer standard conversion (4.3) is used in
4985 // place of P for type deduction; otherwise,
4986 else if (P->isFunctionType())
4987 P = Context.getPointerType(T: P);
4988 // - If P is a cv-qualified type, the top level cv-qualifiers of
4989 // P's type are ignored for type deduction.
4990 else
4991 P = P.getUnqualifiedType();
4992
4993 // C++0x [temp.deduct.conv]p4:
4994 // If A is a cv-qualified type, the top level cv-qualifiers of A's
4995 // type are ignored for type deduction. If A is a reference type, the type
4996 // referred to by A is used for type deduction.
4997 A = A.getUnqualifiedType();
4998 }
4999
5000 // Unevaluated SFINAE context.
5001 EnterExpressionEvaluationContext Unevaluated(
5002 *this, Sema::ExpressionEvaluationContext::Unevaluated);
5003 SFINAETrap Trap(*this, Info);
5004
5005 // C++ [temp.deduct.conv]p1:
5006 // Template argument deduction is done by comparing the return
5007 // type of the template conversion function (call it P) with the
5008 // type that is required as the result of the conversion (call it
5009 // A) as described in 14.8.2.4.
5010 TemplateParameterList *TemplateParams
5011 = ConversionTemplate->getTemplateParameters();
5012 SmallVector<DeducedTemplateArgument, 4> Deduced;
5013 Deduced.resize(N: TemplateParams->size());
5014
5015 // C++0x [temp.deduct.conv]p4:
5016 // In general, the deduction process attempts to find template
5017 // argument values that will make the deduced A identical to
5018 // A. However, there are two cases that allow a difference:
5019 unsigned TDF = 0;
5020 // - If the original A is a reference type, A can be more
5021 // cv-qualified than the deduced A (i.e., the type referred to
5022 // by the reference)
5023 if (IsReferenceA)
5024 TDF |= TDF_ArgWithReferenceType;
5025 // - The deduced A can be another pointer or pointer to member
5026 // type that can be converted to A via a qualification
5027 // conversion.
5028 //
5029 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
5030 // both P and A are pointers or member pointers. In this case, we
5031 // just ignore cv-qualifiers completely).
5032 if ((P->isPointerType() && A->isPointerType()) ||
5033 (P->isMemberPointerType() && A->isMemberPointerType()))
5034 TDF |= TDF_IgnoreQualifiers;
5035
5036 SmallVector<Sema::OriginalCallArg, 1> OriginalCallArgs;
5037 if (ConversionGeneric->isExplicitObjectMemberFunction()) {
5038 QualType ParamType = ConversionGeneric->getParamDecl(i: 0)->getType();
5039 if (TemplateDeductionResult Result =
5040 DeduceTemplateArgumentsFromCallArgument(
5041 S&: *this, TemplateParams, FirstInnerIndex: getFirstInnerIndex(FTD: ConversionTemplate),
5042 ParamType, ArgType: ObjectType, ArgClassification: ObjectClassification,
5043 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
5044 /*Decomposed*/ DecomposedParam: false, ArgIdx: 0, /*TDF*/ 0);
5045 Result != TemplateDeductionResult::Success)
5046 return Result;
5047 }
5048
5049 if (TemplateDeductionResult Result = DeduceTemplateArgumentsByTypeMatch(
5050 S&: *this, TemplateParams, P, A, Info, Deduced, TDF,
5051 POK: PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
5052 /*HasDeducedAnyParam=*/nullptr);
5053 Result != TemplateDeductionResult::Success)
5054 return Result;
5055
5056 // Create an Instantiation Scope for finalizing the operator.
5057 LocalInstantiationScope InstScope(*this);
5058 // Finish template argument deduction.
5059 FunctionDecl *ConversionSpecialized = nullptr;
5060 TemplateDeductionResult Result;
5061 runWithSufficientStackSpace(Loc: Info.getLocation(), Fn: [&] {
5062 Result = FinishTemplateArgumentDeduction(
5063 FunctionTemplate: ConversionTemplate, Deduced, NumExplicitlySpecified: 0, Specialization&: ConversionSpecialized, Info,
5064 OriginalCallArgs: &OriginalCallArgs, /*PartialOverloading=*/false,
5065 /*PartialOrdering=*/false, /*ForOverloadSetAddressResolution*/ false);
5066 });
5067 Specialization = cast_or_null<CXXConversionDecl>(Val: ConversionSpecialized);
5068 return Result;
5069}
5070
5071TemplateDeductionResult
5072Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5073 TemplateArgumentListInfo *ExplicitTemplateArgs,
5074 FunctionDecl *&Specialization,
5075 TemplateDeductionInfo &Info,
5076 bool IsAddressOfFunction) {
5077 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
5078 ArgFunctionType: QualType(), Specialization, Info,
5079 IsAddressOfFunction);
5080}
5081
5082namespace {
5083 struct DependentAuto { bool IsPack; };
5084
5085 /// Substitute the 'auto' specifier or deduced template specialization type
5086 /// specifier within a type for a given replacement type.
5087 class SubstituteDeducedTypeTransform :
5088 public TreeTransform<SubstituteDeducedTypeTransform> {
5089 DeducedKind DK;
5090 QualType Replacement;
5091 bool UseTypeSugar;
5092 using inherited = TreeTransform<SubstituteDeducedTypeTransform>;
5093
5094 public:
5095 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
5096 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5097 DK(DA.IsPack ? DeducedKind::DeducedAsPack
5098 : DeducedKind::DeducedAsDependent),
5099 UseTypeSugar(true) {}
5100
5101 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
5102 bool UseTypeSugar = true)
5103 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5104 DK(Replacement.isNull() ? DeducedKind::Undeduced
5105 : DeducedKind::Deduced),
5106 Replacement(Replacement), UseTypeSugar(UseTypeSugar) {
5107 assert((!Replacement.isNull() || UseTypeSugar) &&
5108 "An undeduced auto type is never type sugar");
5109 }
5110
5111 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
5112 assert(isa<TemplateTypeParmType>(Replacement) &&
5113 "unexpected unsugared replacement kind");
5114 QualType Result = Replacement;
5115 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(T: Result);
5116 NewTL.setNameLoc(TL.getNameLoc());
5117 return Result;
5118 }
5119
5120 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
5121 // If we're building the type pattern to deduce against, don't wrap the
5122 // substituted type in an AutoType. Certain template deduction rules
5123 // apply only when a template type parameter appears directly (and not if
5124 // the parameter is found through desugaring). For instance:
5125 // auto &&lref = lvalue;
5126 // must transform into "rvalue reference to T" not "rvalue reference to
5127 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
5128 //
5129 // FIXME: Is this still necessary?
5130 if (!UseTypeSugar)
5131 return TransformDesugared(TLB, TL);
5132
5133 QualType Result = SemaRef.Context.getAutoType(
5134 DK, DeducedAsType: Replacement, Keyword: TL.getTypePtr()->getKeyword(),
5135 TypeConstraintConcept: TL.getTypePtr()->getTypeConstraintConcept(),
5136 TypeConstraintArgs: TL.getTypePtr()->getTypeConstraintArguments());
5137 auto NewTL = TLB.push<AutoTypeLoc>(T: Result);
5138 NewTL.copy(Loc: TL);
5139 return Result;
5140 }
5141
5142 QualType TransformDeducedTemplateSpecializationType(
5143 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
5144 if (!UseTypeSugar)
5145 return TransformDesugared(TLB, TL);
5146
5147 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
5148 DK, DeducedAsType: Replacement, Keyword: TL.getTypePtr()->getKeyword(),
5149 Template: TL.getTypePtr()->getTemplateName());
5150 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T: Result);
5151 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5152 NewTL.setNameLoc(TL.getNameLoc());
5153 NewTL.setQualifierLoc(TL.getQualifierLoc());
5154 return Result;
5155 }
5156
5157 QualType TransformAtomicType(TypeLocBuilder &TLB, AtomicTypeLoc TL) {
5158 // When building the function parameter for placeholder type deduction
5159 // (Replacement is the invented template parameter), dig through _Atomic
5160 // around an auto placeholder so deduction matches the non-atomic
5161 // argument. The _Atomic wrapper is re-applied by the final substitution
5162 // pass, which uses a concrete Replacement and falls through to the
5163 // default transform.
5164 //
5165 // This handles only the simple case where _Atomic wraps auto directly
5166 // (e.g. _Atomic(auto)), which is what the C standard currently permits.
5167 // If more complex forms such as _Atomic(auto*) are ever allowed, the
5168 // correct fix would be to treat _Atomic as a qualifier inside
5169 // DeduceTemplateArgumentsByTypeMatch instead.
5170 if (isa_and_nonnull<TemplateTypeParmType>(Val: Replacement) &&
5171 TL.getValueLoc().getType()->getContainedAutoType())
5172 return getDerived().TransformType(TLB, T: TL.getValueLoc());
5173 return inherited::TransformAtomicType(TLB, TL);
5174 }
5175
5176 ExprResult TransformLambdaExpr(LambdaExpr *E) {
5177 // Lambdas never need to be transformed.
5178 return E;
5179 }
5180 bool TransformExceptionSpec(SourceLocation Loc,
5181 FunctionProtoType::ExceptionSpecInfo &ESI,
5182 SmallVectorImpl<QualType> &Exceptions,
5183 bool &Changed) {
5184 if (ESI.Type == EST_Uninstantiated) {
5185 ESI.instantiate();
5186 Changed = true;
5187 }
5188 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
5189 }
5190
5191 QualType Apply(TypeLoc TL) {
5192 // Create some scratch storage for the transformed type locations.
5193 // FIXME: We're just going to throw this information away. Don't build it.
5194 TypeLocBuilder TLB;
5195 TLB.reserve(Requested: TL.getFullDataSize());
5196 return TransformType(TLB, T: TL);
5197 }
5198 };
5199
5200} // namespace
5201
5202static bool CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type,
5203 AutoTypeLoc TypeLoc,
5204 QualType Deduced) {
5205 ConstraintSatisfaction Satisfaction;
5206 ConceptDecl *Concept = cast<ConceptDecl>(Val: Type.getTypeConstraintConcept());
5207 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
5208 TypeLoc.getRAngleLoc());
5209 TemplateArgs.addArgument(
5210 Loc: TemplateArgumentLoc(TemplateArgument(Deduced),
5211 S.Context.getTrivialTypeSourceInfo(
5212 T: Deduced, Loc: TypeLoc.getNameLoc())));
5213 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
5214 TemplateArgs.addArgument(Loc: TypeLoc.getArgLoc(i: I));
5215
5216 Sema::CheckTemplateArgumentInfo CTAI;
5217 if (S.CheckTemplateArgumentList(Template: Concept, TemplateLoc: TypeLoc.getNameLoc(), TemplateArgs,
5218 /*DefaultArgs=*/{},
5219 /*PartialTemplateArgs=*/false, CTAI))
5220 return true;
5221 MultiLevelTemplateArgumentList MLTAL(Concept, CTAI.SugaredConverted,
5222 /*Final=*/true);
5223 if (S.CheckConstraintSatisfaction(
5224 Entity: Concept, AssociatedConstraints: AssociatedConstraint(Concept->getConstraintExpr()), TemplateArgLists: MLTAL,
5225 TemplateIDRange: TypeLoc.getLocalSourceRange(), Satisfaction))
5226 return true;
5227 if (!Satisfaction.IsSatisfied) {
5228 std::string Buf;
5229 llvm::raw_string_ostream OS(Buf);
5230 OS << "'" << Concept->getName();
5231 if (TypeLoc.hasExplicitTemplateArgs()) {
5232 printTemplateArgumentList(
5233 OS, Args: Type.getTypeConstraintArguments(), Policy: S.getPrintingPolicy(),
5234 TPL: Type.getTypeConstraintConcept()->getTemplateParameters());
5235 }
5236 OS << "'";
5237 S.Diag(Loc: TypeLoc.getConceptNameLoc(),
5238 DiagID: diag::err_placeholder_constraints_not_satisfied)
5239 << Deduced << Buf << TypeLoc.getLocalSourceRange();
5240 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
5241 return true;
5242 }
5243 return false;
5244}
5245
5246TemplateDeductionResult
5247Sema::DeduceAutoType(TypeLoc Type, Expr *Init, QualType &Result,
5248 TemplateDeductionInfo &Info, bool DependentDeduction,
5249 bool IgnoreConstraints,
5250 TemplateSpecCandidateSet *FailedTSC) {
5251 assert(DependentDeduction || Info.getDeducedDepth() == 0);
5252 if (Init->containsErrors())
5253 return TemplateDeductionResult::AlreadyDiagnosed;
5254
5255 const AutoType *AT = Type.getType()->getContainedAutoType();
5256 assert(AT);
5257
5258 if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
5259 ExprResult NonPlaceholder = CheckPlaceholderExpr(E: Init);
5260 if (NonPlaceholder.isInvalid())
5261 return TemplateDeductionResult::AlreadyDiagnosed;
5262 Init = NonPlaceholder.get();
5263 }
5264
5265 DependentAuto DependentResult = {
5266 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
5267
5268 if (!DependentDeduction &&
5269 (Type.getType()->isDependentType() || Init->isTypeDependent() ||
5270 Init->containsUnexpandedParameterPack())) {
5271 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(TL: Type);
5272 assert(!Result.isNull() && "substituting DependentTy can't fail");
5273 return TemplateDeductionResult::Success;
5274 }
5275
5276 auto *InitList = dyn_cast<InitListExpr>(Val: Init);
5277 bool IsArrayType = Type.getType()->isArrayType();
5278 if (!getLangOpts().CPlusPlus && (InitList || IsArrayType)) {
5279 Diag(Loc: Init->getBeginLoc(), DiagID: diag::err_auto_init_list_from_c)
5280 << (int)AT->getKeyword() << IsArrayType;
5281 return TemplateDeductionResult::AlreadyDiagnosed;
5282 }
5283
5284 // Emit a warning if 'auto*' is used in pedantic and in C23 mode.
5285 if (getLangOpts().C23 && Type.getType()->isPointerType()) {
5286 Diag(Loc: Type.getBeginLoc(), DiagID: diag::ext_c23_auto_non_plain_identifier);
5287 }
5288
5289 // Deduce type of TemplParam in Func(Init)
5290 SmallVector<DeducedTemplateArgument, 1> Deduced;
5291 Deduced.resize(N: 1);
5292
5293 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
5294
5295 QualType DeducedType;
5296 // If this is a 'decltype(auto)' specifier, do the decltype dance.
5297 if (AT->isDecltypeAuto()) {
5298 if (InitList) {
5299 Diag(Loc: Init->getBeginLoc(), DiagID: diag::err_decltype_auto_initializer_list);
5300 return TemplateDeductionResult::AlreadyDiagnosed;
5301 }
5302
5303 DeducedType = getDecltypeForExpr(E: Init);
5304 assert(!DeducedType.isNull());
5305 } else {
5306 LocalInstantiationScope InstScope(*this);
5307
5308 // Build template<class TemplParam> void Func(FuncParam);
5309 SourceLocation Loc = Init->getExprLoc();
5310 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
5311 C: Context, DC: nullptr, KeyLoc: SourceLocation(), NameLoc: Loc, D: Info.getDeducedDepth(), P: 0,
5312 Id: nullptr, Typename: false, ParameterPack: false, HasTypeConstraint: false);
5313 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
5314 NamedDecl *TemplParamPtr = TemplParam;
5315 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
5316 Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
5317
5318 if (InitList) {
5319 // Notionally, we substitute std::initializer_list<T> for 'auto' and
5320 // deduce against that. Such deduction only succeeds if removing
5321 // cv-qualifiers and references results in std::initializer_list<T>.
5322 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
5323 return TemplateDeductionResult::Invalid;
5324
5325 SourceRange DeducedFromInitRange;
5326 for (Expr *Init : InitList->inits()) {
5327 // Resolving a core issue: a braced-init-list containing any designators
5328 // is a non-deduced context.
5329 if (isa<DesignatedInitExpr>(Val: Init))
5330 return TemplateDeductionResult::Invalid;
5331 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
5332 S&: *this, TemplateParams: TemplateParamsSt.get(), FirstInnerIndex: 0, ParamType: TemplArg, ArgType: Init->getType(),
5333 ArgClassification: Init->Classify(Ctx&: getASTContext()), Arg: Init, Info, Deduced,
5334 OriginalCallArgs,
5335 /*Decomposed=*/DecomposedParam: true,
5336 /*ArgIdx=*/0, /*TDF=*/0);
5337 TDK != TemplateDeductionResult::Success) {
5338 if (TDK == TemplateDeductionResult::Inconsistent) {
5339 Diag(Loc: Info.getLocation(), DiagID: diag::err_auto_inconsistent_deduction)
5340 << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
5341 << Init->getSourceRange();
5342 return TemplateDeductionResult::AlreadyDiagnosed;
5343 }
5344 return TDK;
5345 }
5346
5347 if (DeducedFromInitRange.isInvalid() &&
5348 Deduced[0].getKind() != TemplateArgument::Null)
5349 DeducedFromInitRange = Init->getSourceRange();
5350 }
5351 } else {
5352 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
5353 Diag(Loc, DiagID: diag::err_auto_bitfield);
5354 return TemplateDeductionResult::AlreadyDiagnosed;
5355 }
5356 QualType FuncParam =
5357 SubstituteDeducedTypeTransform(*this, TemplArg).Apply(TL: Type);
5358 assert(!FuncParam.isNull() &&
5359 "substituting template parameter for 'auto' failed");
5360 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
5361 S&: *this, TemplateParams: TemplateParamsSt.get(), FirstInnerIndex: 0, ParamType: FuncParam, ArgType: Init->getType(),
5362 ArgClassification: Init->Classify(Ctx&: getASTContext()), Arg: Init, Info, Deduced,
5363 OriginalCallArgs,
5364 /*Decomposed=*/DecomposedParam: false, /*ArgIdx=*/0, /*TDF=*/0, FailedTSC);
5365 TDK != TemplateDeductionResult::Success)
5366 return TDK;
5367 }
5368
5369 // Could be null if somehow 'auto' appears in a non-deduced context.
5370 if (Deduced[0].getKind() != TemplateArgument::Type)
5371 return TemplateDeductionResult::Incomplete;
5372 DeducedType = Deduced[0].getAsType();
5373
5374 if (InitList) {
5375 DeducedType = BuildStdInitializerList(Element: DeducedType, Loc);
5376 if (DeducedType.isNull())
5377 return TemplateDeductionResult::AlreadyDiagnosed;
5378 }
5379 }
5380
5381 if (!Result.isNull()) {
5382 if (!Context.hasSameType(T1: DeducedType, T2: Result)) {
5383 Info.FirstArg = Result;
5384 Info.SecondArg = DeducedType;
5385 return TemplateDeductionResult::Inconsistent;
5386 }
5387 DeducedType = Context.getCommonSugaredType(X: Result, Y: DeducedType);
5388 }
5389
5390 if (AT->isConstrained() && !IgnoreConstraints &&
5391 CheckDeducedPlaceholderConstraints(
5392 S&: *this, Type: *AT, TypeLoc: Type.getContainedAutoTypeLoc(), Deduced: DeducedType))
5393 return TemplateDeductionResult::AlreadyDiagnosed;
5394
5395 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(TL: Type);
5396 if (Result.isNull())
5397 return TemplateDeductionResult::AlreadyDiagnosed;
5398
5399 // Check that the deduced argument type is compatible with the original
5400 // argument type per C++ [temp.deduct.call]p4.
5401 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
5402 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
5403 assert((bool)InitList == OriginalArg.DecomposedParam &&
5404 "decomposed non-init-list in auto deduction?");
5405 if (auto TDK =
5406 CheckOriginalCallArgDeduction(S&: *this, Info, OriginalArg, DeducedA);
5407 TDK != TemplateDeductionResult::Success) {
5408 Result = QualType();
5409 return TDK;
5410 }
5411 }
5412
5413 return TemplateDeductionResult::Success;
5414}
5415
5416QualType Sema::SubstAutoType(QualType TypeWithAuto,
5417 QualType TypeToReplaceAuto) {
5418 assert(TypeToReplaceAuto != Context.DependentTy);
5419 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5420 .TransformType(T: TypeWithAuto);
5421}
5422
5423TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
5424 QualType TypeToReplaceAuto) {
5425 assert(TypeToReplaceAuto != Context.DependentTy);
5426 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5427 .TransformType(TSI: TypeWithAuto);
5428}
5429
5430QualType Sema::SubstAutoTypeDependent(QualType TypeWithAuto) {
5431 return SubstituteDeducedTypeTransform(
5432 *this,
5433 DependentAuto{/*IsPack=*/isa<PackExpansionType>(Val: TypeWithAuto)})
5434 .TransformType(T: TypeWithAuto);
5435}
5436
5437TypeSourceInfo *
5438Sema::SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto) {
5439 return SubstituteDeducedTypeTransform(
5440 *this, DependentAuto{/*IsPack=*/isa<PackExpansionType>(
5441 Val: TypeWithAuto->getType())})
5442 .TransformType(TSI: TypeWithAuto);
5443}
5444
5445QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
5446 QualType TypeToReplaceAuto) {
5447 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5448 /*UseTypeSugar*/ false)
5449 .TransformType(T: TypeWithAuto);
5450}
5451
5452TypeSourceInfo *Sema::ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
5453 QualType TypeToReplaceAuto) {
5454 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5455 /*UseTypeSugar*/ false)
5456 .TransformType(TSI: TypeWithAuto);
5457}
5458
5459void Sema::DiagnoseAutoDeductionFailure(const VarDecl *VDecl,
5460 const Expr *Init) {
5461 if (isa<InitListExpr>(Val: Init))
5462 Diag(Loc: VDecl->getLocation(),
5463 DiagID: VDecl->isInitCapture()
5464 ? diag::err_init_capture_deduction_failure_from_init_list
5465 : diag::err_auto_var_deduction_failure_from_init_list)
5466 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
5467 else
5468 Diag(Loc: VDecl->getLocation(),
5469 DiagID: VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
5470 : diag::err_auto_var_deduction_failure)
5471 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5472 << Init->getSourceRange();
5473}
5474
5475bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
5476 bool Diagnose) {
5477 assert(FD->getReturnType()->isUndeducedType());
5478
5479 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
5480 // within the return type from the call operator's type.
5481 if (isLambdaConversionOperator(D: FD)) {
5482 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(Val: FD)->getParent();
5483 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5484
5485 // For a generic lambda, instantiate the call operator if needed.
5486 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5487 CallOp = InstantiateFunctionDeclaration(
5488 FTD: CallOp->getDescribedFunctionTemplate(), Args, Loc);
5489 if (!CallOp || CallOp->isInvalidDecl())
5490 return true;
5491
5492 // We might need to deduce the return type by instantiating the definition
5493 // of the operator() function.
5494 if (CallOp->getReturnType()->isUndeducedType()) {
5495 runWithSufficientStackSpace(Loc, Fn: [&] {
5496 InstantiateFunctionDefinition(PointOfInstantiation: Loc, Function: CallOp);
5497 });
5498 }
5499 }
5500
5501 if (CallOp->isInvalidDecl())
5502 return true;
5503 assert(!CallOp->getReturnType()->isUndeducedType() &&
5504 "failed to deduce lambda return type");
5505
5506 // Build the new return type from scratch.
5507 CallingConv RetTyCC = FD->getReturnType()
5508 ->getPointeeType()
5509 ->castAs<FunctionType>()
5510 ->getCallConv();
5511 QualType RetType = getLambdaConversionFunctionResultType(
5512 CallOpType: CallOp->getType()->castAs<FunctionProtoType>(), CC: RetTyCC);
5513 if (FD->getReturnType()->getAs<PointerType>())
5514 RetType = Context.getPointerType(T: RetType);
5515 else {
5516 assert(FD->getReturnType()->getAs<BlockPointerType>());
5517 RetType = Context.getBlockPointerType(T: RetType);
5518 }
5519 Context.adjustDeducedFunctionResultType(FD, ResultType: RetType);
5520 return false;
5521 }
5522
5523 if (FD->getTemplateInstantiationPattern()) {
5524 runWithSufficientStackSpace(Loc, Fn: [&] {
5525 InstantiateFunctionDefinition(PointOfInstantiation: Loc, Function: FD);
5526 });
5527 }
5528
5529 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
5530 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
5531 Diag(Loc, DiagID: diag::err_auto_fn_used_before_defined) << FD;
5532 Diag(Loc: FD->getLocation(), DiagID: diag::note_callee_decl) << FD;
5533 }
5534
5535 return StillUndeduced;
5536}
5537
5538bool Sema::CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD,
5539 SourceLocation Loc) {
5540 assert(FD->isImmediateEscalating());
5541
5542 if (isLambdaConversionOperator(D: FD)) {
5543 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(Val: FD)->getParent();
5544 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5545
5546 // For a generic lambda, instantiate the call operator if needed.
5547 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5548 CallOp = InstantiateFunctionDeclaration(
5549 FTD: CallOp->getDescribedFunctionTemplate(), Args, Loc);
5550 if (!CallOp || CallOp->isInvalidDecl())
5551 return true;
5552 runWithSufficientStackSpace(
5553 Loc, Fn: [&] { InstantiateFunctionDefinition(PointOfInstantiation: Loc, Function: CallOp); });
5554 }
5555 return CallOp->isInvalidDecl();
5556 }
5557
5558 if (FD->getTemplateInstantiationPattern()) {
5559 runWithSufficientStackSpace(
5560 Loc, Fn: [&] { InstantiateFunctionDefinition(PointOfInstantiation: Loc, Function: FD); });
5561 }
5562 return false;
5563}
5564
5565static QualType GetImplicitObjectParameterType(ASTContext &Context,
5566 const CXXMethodDecl *Method,
5567 QualType RawType,
5568 bool IsOtherRvr) {
5569 // C++20 [temp.func.order]p3.1, p3.2:
5570 // - The type X(M) is "rvalue reference to cv A" if the optional
5571 // ref-qualifier of M is && or if M has no ref-qualifier and the
5572 // positionally-corresponding parameter of the other transformed template
5573 // has rvalue reference type; if this determination depends recursively
5574 // upon whether X(M) is an rvalue reference type, it is not considered to
5575 // have rvalue reference type.
5576 //
5577 // - Otherwise, X(M) is "lvalue reference to cv A".
5578 assert(Method && !Method->isExplicitObjectMemberFunction() &&
5579 "expected a member function with no explicit object parameter");
5580
5581 RawType = Context.getQualifiedType(T: RawType, Qs: Method->getMethodQualifiers());
5582 if (Method->getRefQualifier() == RQ_RValue ||
5583 (IsOtherRvr && Method->getRefQualifier() == RQ_None))
5584 return Context.getRValueReferenceType(T: RawType);
5585 return Context.getLValueReferenceType(T: RawType);
5586}
5587
5588static TemplateDeductionResult CheckDeductionConsistency(
5589 Sema &S, FunctionTemplateDecl *FTD, UnsignedOrNone ArgIdx, QualType P,
5590 QualType A, ArrayRef<TemplateArgument> DeducedArgs, bool CheckConsistency) {
5591 MultiLevelTemplateArgumentList MLTAL(FTD, DeducedArgs,
5592 /*Final=*/true);
5593 Sema::ArgPackSubstIndexRAII PackIndex(
5594 S,
5595 ArgIdx ? ::getPackIndexForParam(S, FunctionTemplate: FTD, Args: MLTAL, ParamIdx: *ArgIdx) : std::nullopt);
5596 bool IsIncompleteSubstitution = false;
5597 // FIXME: A substitution can be incomplete on a non-structural part of the
5598 // type. Use the canonical type for now, until the TemplateInstantiator can
5599 // deal with that.
5600
5601 // Workaround: Implicit deduction guides use InjectedClassNameTypes, whereas
5602 // the explicit guides don't. The substitution doesn't transform these types,
5603 // so let it transform their specializations instead.
5604 bool IsDeductionGuide = isa<CXXDeductionGuideDecl>(Val: FTD->getTemplatedDecl());
5605 if (IsDeductionGuide) {
5606 if (auto *Injected = P->getAsCanonical<InjectedClassNameType>())
5607 P = Injected->getDecl()->getCanonicalTemplateSpecializationType(
5608 Ctx: S.Context);
5609 }
5610 QualType InstP = S.SubstType(T: P.getCanonicalType(), TemplateArgs: MLTAL, Loc: FTD->getLocation(),
5611 Entity: FTD->getDeclName(), IsIncompleteSubstitution: &IsIncompleteSubstitution);
5612 if (InstP.isNull() && !IsIncompleteSubstitution)
5613 return TemplateDeductionResult::SubstitutionFailure;
5614 if (!CheckConsistency)
5615 return TemplateDeductionResult::Success;
5616 if (IsIncompleteSubstitution)
5617 return TemplateDeductionResult::Incomplete;
5618
5619 // [temp.deduct.call]/4 - Check we produced a consistent deduction.
5620 // This handles just the cases that can appear when partial ordering.
5621 if (auto *PA = dyn_cast<PackExpansionType>(Val&: A);
5622 PA && !isa<PackExpansionType>(Val: InstP))
5623 A = PA->getPattern();
5624 auto T1 = S.Context.getUnqualifiedArrayType(T: InstP.getNonReferenceType());
5625 auto T2 = S.Context.getUnqualifiedArrayType(T: A.getNonReferenceType());
5626 if (IsDeductionGuide) {
5627 if (auto *Injected = T1->getAsCanonical<InjectedClassNameType>())
5628 T1 = Injected->getDecl()->getCanonicalTemplateSpecializationType(
5629 Ctx: S.Context);
5630 if (auto *Injected = T2->getAsCanonical<InjectedClassNameType>())
5631 T2 = Injected->getDecl()->getCanonicalTemplateSpecializationType(
5632 Ctx: S.Context);
5633 }
5634 if (!S.Context.hasSameType(T1, T2))
5635 return TemplateDeductionResult::NonDeducedMismatch;
5636 return TemplateDeductionResult::Success;
5637}
5638
5639template <class T>
5640static TemplateDeductionResult FinishTemplateArgumentDeduction(
5641 Sema &S, FunctionTemplateDecl *FTD,
5642 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5643 TemplateDeductionInfo &Info, T &&CheckDeductionConsistency) {
5644 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(D: FTD));
5645
5646 // C++26 [temp.deduct.type]p2:
5647 // [...] or if any template argument remains neither deduced nor
5648 // explicitly specified, template argument deduction fails.
5649 bool IsIncomplete = false;
5650 Sema::CheckTemplateArgumentInfo CTAI(/*PartialOrdering=*/true);
5651 if (auto Result = ConvertDeducedTemplateArguments(
5652 S, Template: FTD, TemplateParams: FTD->getTemplateParameters(), /*IsDeduced=*/true, Deduced,
5653 Info, CTAI,
5654 /*CurrentInstantiationScope=*/nullptr,
5655 /*NumAlreadyConverted=*/0, IsIncomplete: &IsIncomplete);
5656 Result != TemplateDeductionResult::Success)
5657 return Result;
5658
5659 // Form the template argument list from the deduced template arguments.
5660 TemplateArgumentList *SugaredDeducedArgumentList =
5661 TemplateArgumentList::CreateCopy(Context&: S.Context, Args: CTAI.SugaredConverted);
5662 TemplateArgumentList *CanonicalDeducedArgumentList =
5663 TemplateArgumentList::CreateCopy(Context&: S.Context, Args: CTAI.CanonicalConverted);
5664
5665 Info.reset(NewDeducedSugared: SugaredDeducedArgumentList, NewDeducedCanonical: CanonicalDeducedArgumentList);
5666
5667 // Substitute the deduced template arguments into the argument
5668 // and verify that the instantiated argument is both valid
5669 // and equivalent to the parameter.
5670 LocalInstantiationScope InstScope(S);
5671 return CheckDeductionConsistency(S, FTD, CTAI.SugaredConverted);
5672}
5673
5674/// Determine whether the function template \p FT1 is at least as
5675/// specialized as \p FT2.
5676static bool isAtLeastAsSpecializedAs(
5677 Sema &S, SourceLocation Loc, FunctionTemplateDecl *FT1,
5678 FunctionTemplateDecl *FT2, TemplatePartialOrderingContext TPOC,
5679 ArrayRef<QualType> Args1, ArrayRef<QualType> Args2, bool Args1Offset) {
5680 FunctionDecl *FD1 = FT1->getTemplatedDecl();
5681 FunctionDecl *FD2 = FT2->getTemplatedDecl();
5682 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
5683 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
5684 assert(Proto1 && Proto2 && "Function templates must have prototypes");
5685
5686 // C++26 [temp.deduct.partial]p3:
5687 // The types used to determine the ordering depend on the context in which
5688 // the partial ordering is done:
5689 // - In the context of a function call, the types used are those function
5690 // parameter types for which the function call has arguments.
5691 // - In the context of a call to a conversion operator, the return types
5692 // of the conversion function templates are used.
5693 // - In other contexts (14.6.6.2) the function template's function type
5694 // is used.
5695
5696 if (TPOC == TPOC_Other) {
5697 // We wouldn't be partial ordering these candidates if these didn't match.
5698 assert(Proto1->getMethodQuals() == Proto2->getMethodQuals() &&
5699 Proto1->getRefQualifier() == Proto2->getRefQualifier() &&
5700 Proto1->isVariadic() == Proto2->isVariadic() &&
5701 "shouldn't partial order functions with different qualifiers in a "
5702 "context where the function type is used");
5703
5704 assert(Args1.empty() && Args2.empty() &&
5705 "Only call context should have arguments");
5706 Args1 = Proto1->getParamTypes();
5707 Args2 = Proto2->getParamTypes();
5708 }
5709
5710 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
5711 SmallVector<DeducedTemplateArgument, 4> Deduced(TemplateParams->size());
5712 TemplateDeductionInfo Info(Loc);
5713
5714 bool HasDeducedAnyParamFromReturnType = false;
5715 if (TPOC != TPOC_Call) {
5716 if (DeduceTemplateArgumentsByTypeMatch(
5717 S, TemplateParams, P: Proto2->getReturnType(), A: Proto1->getReturnType(),
5718 Info, Deduced, TDF: TDF_None, POK: PartialOrderingKind::Call,
5719 /*DeducedFromArrayBound=*/false,
5720 HasDeducedAnyParam: &HasDeducedAnyParamFromReturnType) !=
5721 TemplateDeductionResult::Success)
5722 return false;
5723 }
5724
5725 llvm::SmallBitVector HasDeducedParam;
5726 if (TPOC != TPOC_Conversion) {
5727 HasDeducedParam.resize(N: Args2.size());
5728 if (DeduceTemplateArguments(S, TemplateParams, Params: Args2, Args: Args1, Info, Deduced,
5729 TDF: TDF_None, POK: PartialOrderingKind::Call,
5730 /*HasDeducedAnyParam=*/nullptr,
5731 HasDeducedParam: &HasDeducedParam) !=
5732 TemplateDeductionResult::Success)
5733 return false;
5734 }
5735
5736 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
5737 EnterExpressionEvaluationContext Unevaluated(
5738 S, Sema::ExpressionEvaluationContext::Unevaluated);
5739 Sema::SFINAETrap Trap(S, Info);
5740 Sema::InstantiatingTemplate Inst(
5741 S, Info.getLocation(), FT2, DeducedArgs,
5742 Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
5743 if (Inst.isInvalid())
5744 return false;
5745
5746 bool AtLeastAsSpecialized;
5747 S.runWithSufficientStackSpace(Loc: Info.getLocation(), Fn: [&] {
5748 AtLeastAsSpecialized =
5749 ::FinishTemplateArgumentDeduction(
5750 S, FTD: FT2, Deduced, Info,
5751 CheckDeductionConsistency: [&](Sema &S, FunctionTemplateDecl *FTD,
5752 ArrayRef<TemplateArgument> DeducedArgs) {
5753 // As a provisional fix for a core issue that does not
5754 // exist yet, which may be related to CWG2160, only check the
5755 // consistency of parameters and return types which participated
5756 // in deduction. We will still try to substitute them though.
5757 if (TPOC != TPOC_Call) {
5758 if (auto TDR = ::CheckDeductionConsistency(
5759 S, FTD, /*ArgIdx=*/std::nullopt,
5760 P: Proto2->getReturnType(), A: Proto1->getReturnType(),
5761 DeducedArgs,
5762 /*CheckConsistency=*/HasDeducedAnyParamFromReturnType);
5763 TDR != TemplateDeductionResult::Success)
5764 return TDR;
5765 }
5766
5767 if (TPOC == TPOC_Conversion)
5768 return TemplateDeductionResult::Success;
5769
5770 return ::DeduceForEachType(
5771 S, TemplateParams, Params: Args2, Args: Args1, Info, Deduced,
5772 POK: PartialOrderingKind::Call, /*FinishingDeduction=*/true,
5773 DeductFunc: [&](Sema &S, TemplateParameterList *, int ParamIdx,
5774 UnsignedOrNone ArgIdx, QualType P, QualType A,
5775 TemplateDeductionInfo &Info,
5776 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5777 PartialOrderingKind) {
5778 if (ArgIdx && *ArgIdx >= static_cast<unsigned>(Args1Offset))
5779 ArgIdx = *ArgIdx - Args1Offset;
5780 else
5781 ArgIdx = std::nullopt;
5782 return ::CheckDeductionConsistency(
5783 S, FTD, ArgIdx, P, A, DeducedArgs,
5784 /*CheckConsistency=*/HasDeducedParam[ParamIdx]);
5785 });
5786 }) == TemplateDeductionResult::Success;
5787 });
5788 if (!AtLeastAsSpecialized || Trap.hasErrorOccurred())
5789 return false;
5790
5791 // C++0x [temp.deduct.partial]p11:
5792 // In most cases, all template parameters must have values in order for
5793 // deduction to succeed, but for partial ordering purposes a template
5794 // parameter may remain without a value provided it is not used in the
5795 // types being used for partial ordering. [ Note: a template parameter used
5796 // in a non-deduced context is considered used. -end note]
5797 unsigned ArgIdx = 0, NumArgs = Deduced.size();
5798 for (; ArgIdx != NumArgs; ++ArgIdx)
5799 if (Deduced[ArgIdx].isNull())
5800 break;
5801
5802 if (ArgIdx == NumArgs) {
5803 // All template arguments were deduced. FT1 is at least as specialized
5804 // as FT2.
5805 return true;
5806 }
5807
5808 // Figure out which template parameters were used.
5809 llvm::SmallBitVector UsedParameters(TemplateParams->size());
5810 switch (TPOC) {
5811 case TPOC_Call:
5812 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
5813 ::MarkUsedTemplateParameters(Ctx&: S.Context, T: Args2[I], /*OnlyDeduced=*/false,
5814 Level: TemplateParams->getDepth(), Deduced&: UsedParameters);
5815 break;
5816
5817 case TPOC_Conversion:
5818 ::MarkUsedTemplateParameters(Ctx&: S.Context, T: Proto2->getReturnType(),
5819 /*OnlyDeduced=*/false,
5820 Level: TemplateParams->getDepth(), Deduced&: UsedParameters);
5821 break;
5822
5823 case TPOC_Other:
5824 // We do not deduce template arguments from the exception specification
5825 // when determining the primary template of a function template
5826 // specialization or when taking the address of a function template.
5827 // Therefore, we do not mark template parameters in the exception
5828 // specification as used during partial ordering to prevent the following
5829 // from being ambiguous:
5830 //
5831 // template<typename T, typename U>
5832 // void f(U) noexcept(noexcept(T())); // #1
5833 //
5834 // template<typename T>
5835 // void f(T*) noexcept; // #2
5836 //
5837 // template<>
5838 // void f<int>(int*) noexcept; // explicit specialization of #2
5839 //
5840 // Although there is no corresponding wording in the standard, this seems
5841 // to be the intended behavior given the definition of
5842 // 'deduction substitution loci' in [temp.deduct].
5843 ::MarkUsedTemplateParameters(
5844 Ctx&: S.Context,
5845 T: S.Context.getFunctionTypeWithExceptionSpec(Orig: FD2->getType(), ESI: EST_None),
5846 /*OnlyDeduced=*/false, Level: TemplateParams->getDepth(), Deduced&: UsedParameters);
5847 break;
5848 }
5849
5850 for (; ArgIdx != NumArgs; ++ArgIdx)
5851 // If this argument had no value deduced but was used in one of the types
5852 // used for partial ordering, then deduction fails.
5853 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
5854 return false;
5855
5856 return true;
5857}
5858
5859enum class MoreSpecializedTrailingPackTieBreakerResult { Equal, Less, More };
5860
5861// This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
5862// there is no wording or even resolution for this issue.
5863static MoreSpecializedTrailingPackTieBreakerResult
5864getMoreSpecializedTrailingPackTieBreaker(
5865 const TemplateSpecializationType *TST1,
5866 const TemplateSpecializationType *TST2) {
5867 ArrayRef<TemplateArgument> As1 = TST1->template_arguments(),
5868 As2 = TST2->template_arguments();
5869 const TemplateArgument &TA1 = As1.back(), &TA2 = As2.back();
5870 bool IsPack = TA1.getKind() == TemplateArgument::Pack;
5871 assert(IsPack == (TA2.getKind() == TemplateArgument::Pack));
5872 if (!IsPack)
5873 return MoreSpecializedTrailingPackTieBreakerResult::Equal;
5874 assert(As1.size() == As2.size());
5875
5876 unsigned PackSize1 = TA1.pack_size(), PackSize2 = TA2.pack_size();
5877 bool IsPackExpansion1 =
5878 PackSize1 && TA1.pack_elements().back().isPackExpansion();
5879 bool IsPackExpansion2 =
5880 PackSize2 && TA2.pack_elements().back().isPackExpansion();
5881 if (PackSize1 == PackSize2 && IsPackExpansion1 == IsPackExpansion2)
5882 return MoreSpecializedTrailingPackTieBreakerResult::Equal;
5883 if (PackSize1 > PackSize2 && IsPackExpansion1)
5884 return MoreSpecializedTrailingPackTieBreakerResult::More;
5885 if (PackSize1 < PackSize2 && IsPackExpansion2)
5886 return MoreSpecializedTrailingPackTieBreakerResult::Less;
5887 return MoreSpecializedTrailingPackTieBreakerResult::Equal;
5888}
5889
5890FunctionTemplateDecl *Sema::getMoreSpecializedTemplate(
5891 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
5892 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
5893 QualType RawObj1Ty, QualType RawObj2Ty, bool Reversed,
5894 bool PartialOverloading) {
5895 SmallVector<QualType> Args1;
5896 SmallVector<QualType> Args2;
5897 const FunctionDecl *FD1 = FT1->getTemplatedDecl();
5898 const FunctionDecl *FD2 = FT2->getTemplatedDecl();
5899 bool ShouldConvert1 = false;
5900 bool ShouldConvert2 = false;
5901 bool Args1Offset = false;
5902 bool Args2Offset = false;
5903 QualType Obj1Ty;
5904 QualType Obj2Ty;
5905 if (TPOC == TPOC_Call) {
5906 const FunctionProtoType *Proto1 =
5907 FD1->getType()->castAs<FunctionProtoType>();
5908 const FunctionProtoType *Proto2 =
5909 FD2->getType()->castAs<FunctionProtoType>();
5910
5911 // - In the context of a function call, the function parameter types are
5912 // used.
5913 const CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(Val: FD1);
5914 const CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(Val: FD2);
5915 // C++20 [temp.func.order]p3
5916 // [...] Each function template M that is a member function is
5917 // considered to have a new first parameter of type
5918 // X(M), described below, inserted in its function parameter list.
5919 //
5920 // Note that we interpret "that is a member function" as
5921 // "that is a member function with no expicit object argument".
5922 // Otherwise the ordering rules for methods with expicit objet arguments
5923 // against anything else make no sense.
5924
5925 bool NonStaticMethod1 = Method1 && !Method1->isStatic(),
5926 NonStaticMethod2 = Method2 && !Method2->isStatic();
5927
5928 auto Params1Begin = Proto1->param_type_begin(),
5929 Params2Begin = Proto2->param_type_begin();
5930
5931 size_t NumComparedArguments = NumCallArguments1;
5932
5933 if (auto OO = FD1->getOverloadedOperator();
5934 (NonStaticMethod1 && NonStaticMethod2) ||
5935 (OO != OO_None && OO != OO_Call && OO != OO_Subscript)) {
5936 ShouldConvert1 =
5937 NonStaticMethod1 && !Method1->hasCXXExplicitFunctionObjectParameter();
5938 ShouldConvert2 =
5939 NonStaticMethod2 && !Method2->hasCXXExplicitFunctionObjectParameter();
5940 NumComparedArguments += 1;
5941
5942 if (ShouldConvert1) {
5943 bool IsRValRef2 =
5944 ShouldConvert2
5945 ? Method2->getRefQualifier() == RQ_RValue
5946 : Proto2->param_type_begin()[0]->isRValueReferenceType();
5947 // Compare 'this' from Method1 against first parameter from Method2.
5948 Obj1Ty = GetImplicitObjectParameterType(Context&: this->Context, Method: Method1,
5949 RawType: RawObj1Ty, IsOtherRvr: IsRValRef2);
5950 Args1.push_back(Elt: Obj1Ty);
5951 Args1Offset = true;
5952 }
5953 if (ShouldConvert2) {
5954 bool IsRValRef1 =
5955 ShouldConvert1
5956 ? Method1->getRefQualifier() == RQ_RValue
5957 : Proto1->param_type_begin()[0]->isRValueReferenceType();
5958 // Compare 'this' from Method2 against first parameter from Method1.
5959 Obj2Ty = GetImplicitObjectParameterType(Context&: this->Context, Method: Method2,
5960 RawType: RawObj2Ty, IsOtherRvr: IsRValRef1);
5961 Args2.push_back(Elt: Obj2Ty);
5962 Args2Offset = true;
5963 }
5964 } else {
5965 if (NonStaticMethod1 && Method1->hasCXXExplicitFunctionObjectParameter())
5966 Params1Begin += 1;
5967 if (NonStaticMethod2 && Method2->hasCXXExplicitFunctionObjectParameter())
5968 Params2Begin += 1;
5969 }
5970 Args1.insert(I: Args1.end(), From: Params1Begin, To: Proto1->param_type_end());
5971 Args2.insert(I: Args2.end(), From: Params2Begin, To: Proto2->param_type_end());
5972
5973 // C++ [temp.func.order]p5:
5974 // The presence of unused ellipsis and default arguments has no effect on
5975 // the partial ordering of function templates.
5976 Args1.resize(N: std::min(a: Args1.size(), b: NumComparedArguments));
5977 Args2.resize(N: std::min(a: Args2.size(), b: NumComparedArguments));
5978
5979 if (Reversed)
5980 std::reverse(first: Args2.begin(), last: Args2.end());
5981 } else {
5982 assert(!Reversed && "Only call context could have reversed arguments");
5983 }
5984 bool Better1 = isAtLeastAsSpecializedAs(S&: *this, Loc, FT1, FT2, TPOC, Args1,
5985 Args2, Args1Offset: Args2Offset);
5986 bool Better2 = isAtLeastAsSpecializedAs(S&: *this, Loc, FT1: FT2, FT2: FT1, TPOC, Args1: Args2,
5987 Args2: Args1, Args1Offset);
5988 // C++ [temp.deduct.partial]p10:
5989 // F is more specialized than G if F is at least as specialized as G and G
5990 // is not at least as specialized as F.
5991 if (Better1 != Better2) // We have a clear winner
5992 return Better1 ? FT1 : FT2;
5993
5994 if (!Better1 && !Better2) // Neither is better than the other
5995 return nullptr;
5996
5997 // C++ [temp.deduct.partial]p11:
5998 // ... and if G has a trailing function parameter pack for which F does not
5999 // have a corresponding parameter, and if F does not have a trailing
6000 // function parameter pack, then F is more specialized than G.
6001
6002 SmallVector<QualType> Param1;
6003 Param1.reserve(N: FD1->param_size() + ShouldConvert1);
6004 if (ShouldConvert1)
6005 Param1.push_back(Elt: Obj1Ty);
6006 for (const auto &P : FD1->parameters())
6007 Param1.push_back(Elt: P->getType());
6008
6009 SmallVector<QualType> Param2;
6010 Param2.reserve(N: FD2->param_size() + ShouldConvert2);
6011 if (ShouldConvert2)
6012 Param2.push_back(Elt: Obj2Ty);
6013 for (const auto &P : FD2->parameters())
6014 Param2.push_back(Elt: P->getType());
6015
6016 unsigned NumParams1 = Param1.size();
6017 unsigned NumParams2 = Param2.size();
6018
6019 bool Variadic1 =
6020 FD1->param_size() && FD1->parameters().back()->isParameterPack();
6021 bool Variadic2 =
6022 FD2->param_size() && FD2->parameters().back()->isParameterPack();
6023 if (Variadic1 != Variadic2) {
6024 if (Variadic1 && NumParams1 > NumParams2)
6025 return FT2;
6026 if (Variadic2 && NumParams2 > NumParams1)
6027 return FT1;
6028 }
6029
6030 // Skip this tie breaker if we are performing overload resolution with partial
6031 // arguments, as this breaks some assumptions about how closely related the
6032 // candidates are.
6033 for (int i = 0, e = std::min(a: NumParams1, b: NumParams2);
6034 !PartialOverloading && i < e; ++i) {
6035 QualType T1 = Param1[i].getCanonicalType();
6036 QualType T2 = Param2[i].getCanonicalType();
6037 auto *TST1 = dyn_cast<TemplateSpecializationType>(Val&: T1);
6038 auto *TST2 = dyn_cast<TemplateSpecializationType>(Val&: T2);
6039 if (!TST1 || !TST2)
6040 continue;
6041 switch (getMoreSpecializedTrailingPackTieBreaker(TST1, TST2)) {
6042 case MoreSpecializedTrailingPackTieBreakerResult::Less:
6043 return FT1;
6044 case MoreSpecializedTrailingPackTieBreakerResult::More:
6045 return FT2;
6046 case MoreSpecializedTrailingPackTieBreakerResult::Equal:
6047 continue;
6048 }
6049 llvm_unreachable(
6050 "unknown MoreSpecializedTrailingPackTieBreakerResult value");
6051 }
6052
6053 if (!Context.getLangOpts().CPlusPlus20)
6054 return nullptr;
6055
6056 // Match GCC on not implementing [temp.func.order]p6.2.1.
6057
6058 // C++20 [temp.func.order]p6:
6059 // If deduction against the other template succeeds for both transformed
6060 // templates, constraints can be considered as follows:
6061
6062 // C++20 [temp.func.order]p6.1:
6063 // If their template-parameter-lists (possibly including template-parameters
6064 // invented for an abbreviated function template ([dcl.fct])) or function
6065 // parameter lists differ in length, neither template is more specialized
6066 // than the other.
6067 TemplateParameterList *TPL1 = FT1->getTemplateParameters();
6068 TemplateParameterList *TPL2 = FT2->getTemplateParameters();
6069 if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
6070 return nullptr;
6071
6072 // C++20 [temp.func.order]p6.2.2:
6073 // Otherwise, if the corresponding template-parameters of the
6074 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6075 // function parameters that positionally correspond between the two
6076 // templates are not of the same type, neither template is more specialized
6077 // than the other.
6078 if (!TemplateParameterListsAreEqual(New: TPL1, Old: TPL2, Complain: false,
6079 Kind: Sema::TPL_TemplateParamsEquivalent))
6080 return nullptr;
6081
6082 // [dcl.fct]p5:
6083 // Any top-level cv-qualifiers modifying a parameter type are deleted when
6084 // forming the function type.
6085 for (unsigned i = 0; i < NumParams1; ++i)
6086 if (!Context.hasSameUnqualifiedType(T1: Param1[i], T2: Param2[i]))
6087 return nullptr;
6088
6089 // C++20 [temp.func.order]p6.3:
6090 // Otherwise, if the context in which the partial ordering is done is
6091 // that of a call to a conversion function and the return types of the
6092 // templates are not the same, then neither template is more specialized
6093 // than the other.
6094 if (TPOC == TPOC_Conversion &&
6095 !Context.hasSameType(T1: FD1->getReturnType(), T2: FD2->getReturnType()))
6096 return nullptr;
6097
6098 llvm::SmallVector<AssociatedConstraint, 3> AC1, AC2;
6099 FT1->getAssociatedConstraints(AC&: AC1);
6100 FT2->getAssociatedConstraints(AC&: AC2);
6101 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6102 if (IsAtLeastAsConstrained(D1: FT1, AC1, D2: FT2, AC2, Result&: AtLeastAsConstrained1))
6103 return nullptr;
6104 if (IsAtLeastAsConstrained(D1: FT2, AC1: AC2, D2: FT1, AC2: AC1, Result&: AtLeastAsConstrained2))
6105 return nullptr;
6106 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6107 return nullptr;
6108 return AtLeastAsConstrained1 ? FT1 : FT2;
6109}
6110
6111UnresolvedSetIterator Sema::getMostSpecialized(
6112 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
6113 TemplateSpecCandidateSet &FailedCandidates,
6114 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
6115 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
6116 bool Complain, QualType TargetType) {
6117 if (SpecBegin == SpecEnd) {
6118 if (Complain) {
6119 Diag(Loc, PD: NoneDiag);
6120 FailedCandidates.NoteCandidates(S&: *this, Loc);
6121 }
6122 return SpecEnd;
6123 }
6124
6125 if (SpecBegin + 1 == SpecEnd)
6126 return SpecBegin;
6127
6128 // Find the function template that is better than all of the templates it
6129 // has been compared to.
6130 UnresolvedSetIterator Best = SpecBegin;
6131 FunctionTemplateDecl *BestTemplate
6132 = cast<FunctionDecl>(Val: *Best)->getPrimaryTemplate();
6133 assert(BestTemplate && "Not a function template specialization?");
6134 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
6135 FunctionTemplateDecl *Challenger
6136 = cast<FunctionDecl>(Val: *I)->getPrimaryTemplate();
6137 assert(Challenger && "Not a function template specialization?");
6138 if (declaresSameEntity(D1: getMoreSpecializedTemplate(FT1: BestTemplate, FT2: Challenger,
6139 Loc, TPOC: TPOC_Other, NumCallArguments1: 0),
6140 D2: Challenger)) {
6141 Best = I;
6142 BestTemplate = Challenger;
6143 }
6144 }
6145
6146 // Make sure that the "best" function template is more specialized than all
6147 // of the others.
6148 bool Ambiguous = false;
6149 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6150 FunctionTemplateDecl *Challenger
6151 = cast<FunctionDecl>(Val: *I)->getPrimaryTemplate();
6152 if (I != Best &&
6153 !declaresSameEntity(D1: getMoreSpecializedTemplate(FT1: BestTemplate, FT2: Challenger,
6154 Loc, TPOC: TPOC_Other, NumCallArguments1: 0),
6155 D2: BestTemplate)) {
6156 Ambiguous = true;
6157 break;
6158 }
6159 }
6160
6161 if (!Ambiguous) {
6162 // We found an answer. Return it.
6163 return Best;
6164 }
6165
6166 // Diagnose the ambiguity.
6167 if (Complain) {
6168 Diag(Loc, PD: AmbigDiag);
6169
6170 // FIXME: Can we order the candidates in some sane way?
6171 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6172 PartialDiagnostic PD = CandidateDiag;
6173 const auto *FD = cast<FunctionDecl>(Val: *I);
6174 PD << FD << getTemplateArgumentBindingsText(
6175 Params: FD->getPrimaryTemplate()->getTemplateParameters(),
6176 Args: *FD->getTemplateSpecializationArgs());
6177 if (!TargetType.isNull())
6178 HandleFunctionTypeMismatch(PDiag&: PD, FromType: FD->getType(), ToType: TargetType);
6179 Diag(Loc: (*I)->getLocation(), PD);
6180 }
6181 }
6182
6183 return SpecEnd;
6184}
6185
6186FunctionDecl *Sema::getMoreConstrainedFunction(FunctionDecl *FD1,
6187 FunctionDecl *FD2) {
6188 assert(!FD1->getDescribedTemplate() && !FD2->getDescribedTemplate() &&
6189 "not for function templates");
6190 assert(!FD1->isFunctionTemplateSpecialization() ||
6191 (isa<CXXConversionDecl, CXXConstructorDecl>(FD1)));
6192 assert(!FD2->isFunctionTemplateSpecialization() ||
6193 (isa<CXXConversionDecl, CXXConstructorDecl>(FD2)));
6194
6195 FunctionDecl *F1 = FD1;
6196 if (FunctionDecl *P = FD1->getTemplateInstantiationPattern(ForDefinition: false))
6197 F1 = P;
6198
6199 FunctionDecl *F2 = FD2;
6200 if (FunctionDecl *P = FD2->getTemplateInstantiationPattern(ForDefinition: false))
6201 F2 = P;
6202
6203 llvm::SmallVector<AssociatedConstraint, 1> AC1, AC2;
6204 F1->getAssociatedConstraints(ACs&: AC1);
6205 F2->getAssociatedConstraints(ACs&: AC2);
6206 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6207 if (IsAtLeastAsConstrained(D1: F1, AC1, D2: F2, AC2, Result&: AtLeastAsConstrained1))
6208 return nullptr;
6209 if (IsAtLeastAsConstrained(D1: F2, AC1: AC2, D2: F1, AC2: AC1, Result&: AtLeastAsConstrained2))
6210 return nullptr;
6211 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6212 return nullptr;
6213 return AtLeastAsConstrained1 ? FD1 : FD2;
6214}
6215
6216/// Determine whether one template specialization, P1, is at least as
6217/// specialized than another, P2.
6218///
6219/// \tparam TemplateLikeDecl The kind of P2, which must be a
6220/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
6221/// \param T1 The injected-class-name of P1 (faked for a variable template).
6222/// \param T2 The injected-class-name of P2 (faked for a variable template).
6223/// \param Template The primary template of P2, in case it is a partial
6224/// specialization, the same as P2 otherwise.
6225template <typename TemplateLikeDecl>
6226static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
6227 TemplateLikeDecl *P2,
6228 TemplateDecl *Template,
6229 TemplateDeductionInfo &Info) {
6230 // C++ [temp.class.order]p1:
6231 // For two class template partial specializations, the first is at least as
6232 // specialized as the second if, given the following rewrite to two
6233 // function templates, the first function template is at least as
6234 // specialized as the second according to the ordering rules for function
6235 // templates (14.6.6.2):
6236 // - the first function template has the same template parameters as the
6237 // first partial specialization and has a single function parameter
6238 // whose type is a class template specialization with the template
6239 // arguments of the first partial specialization, and
6240 // - the second function template has the same template parameters as the
6241 // second partial specialization and has a single function parameter
6242 // whose type is a class template specialization with the template
6243 // arguments of the second partial specialization.
6244 //
6245 // Rather than synthesize function templates, we merely perform the
6246 // equivalent partial ordering by performing deduction directly on
6247 // the template arguments of the class template partial
6248 // specializations. This computation is slightly simpler than the
6249 // general problem of function template partial ordering, because
6250 // class template partial specializations are more constrained. We
6251 // know that every template parameter is deducible from the class
6252 // template partial specialization's template arguments, for
6253 // example.
6254 SmallVector<DeducedTemplateArgument, 4> Deduced;
6255
6256 // Determine whether P1 is at least as specialized as P2.
6257 Deduced.resize(P2->getTemplateParameters()->size());
6258 if (DeduceTemplateArgumentsByTypeMatch(
6259 S, P2->getTemplateParameters(), T2, T1, Info, Deduced, TDF_None,
6260 PartialOrderingKind::Call, /*DeducedFromArrayBound=*/false,
6261 /*HasDeducedAnyParam=*/nullptr) != TemplateDeductionResult::Success)
6262 return false;
6263
6264 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
6265 EnterExpressionEvaluationContext Unevaluated(
6266 S, Sema::ExpressionEvaluationContext::Unevaluated);
6267 Sema::SFINAETrap Trap(S, Info);
6268 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs);
6269 if (Inst.isInvalid())
6270 return false;
6271
6272 ArrayRef<TemplateArgument>
6273 Ps = cast<TemplateSpecializationType>(Val&: T2)->template_arguments(),
6274 As = cast<TemplateSpecializationType>(Val&: T1)->template_arguments();
6275
6276 TemplateDeductionResult Result;
6277 S.runWithSufficientStackSpace(Loc: Info.getLocation(), Fn: [&] {
6278 Result = ::FinishTemplateArgumentDeduction(
6279 S, P2, P2->getTemplateParameters(), Template,
6280 /*IsPartialOrdering=*/true, Ps, As, Deduced, Info,
6281 /*CopyDeducedArgs=*/false);
6282 });
6283 return Result == TemplateDeductionResult::Success && !Trap.hasErrorOccurred();
6284}
6285
6286namespace {
6287// A dummy class to return nullptr instead of P2 when performing "more
6288// specialized than primary" check.
6289struct GetP2 {
6290 template <typename T1, typename T2,
6291 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6292 T2 *operator()(T1 *, T2 *P2) {
6293 return P2;
6294 }
6295 template <typename T1, typename T2,
6296 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6297 T1 *operator()(T1 *, T2 *) {
6298 return nullptr;
6299 }
6300};
6301
6302// The assumption is that two template argument lists have the same size.
6303struct TemplateArgumentListAreEqual {
6304 ASTContext &Ctx;
6305 TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
6306
6307 template <typename T1, typename T2,
6308 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6309 bool operator()(T1 *PS1, T2 *PS2) {
6310 ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
6311 Args2 = PS2->getTemplateArgs().asArray();
6312
6313 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6314 // We use profile, instead of structural comparison of the arguments,
6315 // because canonicalization can't do the right thing for dependent
6316 // expressions.
6317 llvm::FoldingSetNodeID IDA, IDB;
6318 Args1[I].Profile(ID&: IDA, Context: Ctx);
6319 Args2[I].Profile(ID&: IDB, Context: Ctx);
6320 if (IDA != IDB)
6321 return false;
6322 }
6323 return true;
6324 }
6325
6326 template <typename T1, typename T2,
6327 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6328 bool operator()(T1 *Spec, T2 *Primary) {
6329 ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
6330 Args2 = Primary->getInjectedTemplateArgs(Ctx);
6331
6332 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6333 // We use profile, instead of structural comparison of the arguments,
6334 // because canonicalization can't do the right thing for dependent
6335 // expressions.
6336 llvm::FoldingSetNodeID IDA, IDB;
6337 Args1[I].Profile(ID&: IDA, Context: Ctx);
6338 // Unlike the specialization arguments, the injected arguments are not
6339 // always canonical.
6340 Ctx.getCanonicalTemplateArgument(Arg: Args2[I]).Profile(ID&: IDB, Context: Ctx);
6341 if (IDA != IDB)
6342 return false;
6343 }
6344 return true;
6345 }
6346};
6347} // namespace
6348
6349/// Returns the more specialized template specialization between T1/P1 and
6350/// T2/P2.
6351/// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
6352/// specialization and T2/P2 is the primary template.
6353/// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
6354///
6355/// \param T1 the type of the first template partial specialization
6356///
6357/// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
6358/// template partial specialization; otherwise, the type of the
6359/// primary template.
6360///
6361/// \param P1 the first template partial specialization
6362///
6363/// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
6364/// partial specialization; otherwise, the primary template.
6365///
6366/// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
6367/// more specialized, returns nullptr if P1 is not more specialized.
6368/// - otherwise, returns the more specialized template partial
6369/// specialization. If neither partial specialization is more
6370/// specialized, returns NULL.
6371template <typename TemplateLikeDecl, typename PrimaryDel>
6372static TemplateLikeDecl *
6373getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
6374 PrimaryDel *P2, TemplateDeductionInfo &Info) {
6375 constexpr bool IsMoreSpecialThanPrimaryCheck =
6376 !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
6377
6378 TemplateDecl *P2T;
6379 if constexpr (IsMoreSpecialThanPrimaryCheck)
6380 P2T = P2;
6381 else
6382 P2T = P2->getSpecializedTemplate();
6383
6384 bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, P2T, Info);
6385 if (IsMoreSpecialThanPrimaryCheck && !Better1)
6386 return nullptr;
6387
6388 bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1,
6389 P1->getSpecializedTemplate(), Info);
6390 if (IsMoreSpecialThanPrimaryCheck && !Better2)
6391 return P1;
6392
6393 // C++ [temp.deduct.partial]p10:
6394 // F is more specialized than G if F is at least as specialized as G and G
6395 // is not at least as specialized as F.
6396 if (Better1 != Better2) // We have a clear winner
6397 return Better1 ? P1 : GetP2()(P1, P2);
6398
6399 if (!Better1 && !Better2)
6400 return nullptr;
6401
6402 switch (getMoreSpecializedTrailingPackTieBreaker(
6403 TST1: cast<TemplateSpecializationType>(Val&: T1),
6404 TST2: cast<TemplateSpecializationType>(Val&: T2))) {
6405 case MoreSpecializedTrailingPackTieBreakerResult::Less:
6406 return P1;
6407 case MoreSpecializedTrailingPackTieBreakerResult::More:
6408 return GetP2()(P1, P2);
6409 case MoreSpecializedTrailingPackTieBreakerResult::Equal:
6410 break;
6411 }
6412
6413 if (!S.Context.getLangOpts().CPlusPlus20)
6414 return nullptr;
6415
6416 // Match GCC on not implementing [temp.func.order]p6.2.1.
6417
6418 // C++20 [temp.func.order]p6:
6419 // If deduction against the other template succeeds for both transformed
6420 // templates, constraints can be considered as follows:
6421
6422 TemplateParameterList *TPL1 = P1->getTemplateParameters();
6423 TemplateParameterList *TPL2 = P2->getTemplateParameters();
6424 if (TPL1->size() != TPL2->size())
6425 return nullptr;
6426
6427 // C++20 [temp.func.order]p6.2.2:
6428 // Otherwise, if the corresponding template-parameters of the
6429 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6430 // function parameters that positionally correspond between the two
6431 // templates are not of the same type, neither template is more specialized
6432 // than the other.
6433 if (!S.TemplateParameterListsAreEqual(New: TPL1, Old: TPL2, Complain: false,
6434 Kind: Sema::TPL_TemplateParamsEquivalent))
6435 return nullptr;
6436
6437 if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
6438 return nullptr;
6439
6440 llvm::SmallVector<AssociatedConstraint, 3> AC1, AC2;
6441 P1->getAssociatedConstraints(AC1);
6442 P2->getAssociatedConstraints(AC2);
6443 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6444 if (S.IsAtLeastAsConstrained(D1: P1, AC1, D2: P2, AC2, Result&: AtLeastAsConstrained1) ||
6445 (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
6446 return nullptr;
6447 if (S.IsAtLeastAsConstrained(D1: P2, AC1: AC2, D2: P1, AC2: AC1, Result&: AtLeastAsConstrained2))
6448 return nullptr;
6449 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6450 return nullptr;
6451 return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
6452}
6453
6454ClassTemplatePartialSpecializationDecl *
6455Sema::getMoreSpecializedPartialSpecialization(
6456 ClassTemplatePartialSpecializationDecl *PS1,
6457 ClassTemplatePartialSpecializationDecl *PS2,
6458 SourceLocation Loc) {
6459 QualType PT1 = PS1->getCanonicalInjectedSpecializationType(Ctx: Context);
6460 QualType PT2 = PS2->getCanonicalInjectedSpecializationType(Ctx: Context);
6461
6462 TemplateDeductionInfo Info(Loc);
6463 return getMoreSpecialized(S&: *this, T1: PT1, T2: PT2, P1: PS1, P2: PS2, Info);
6464}
6465
6466bool Sema::isMoreSpecializedThanPrimary(
6467 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
6468 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
6469 QualType PrimaryT = Primary->getCanonicalInjectedSpecializationType(Ctx: Context);
6470 QualType PartialT = Spec->getCanonicalInjectedSpecializationType(Ctx: Context);
6471
6472 ClassTemplatePartialSpecializationDecl *MaybeSpec =
6473 getMoreSpecialized(S&: *this, T1: PartialT, T2: PrimaryT, P1: Spec, P2: Primary, Info);
6474 if (MaybeSpec)
6475 Info.clearSFINAEDiagnostic();
6476 return MaybeSpec;
6477}
6478
6479VarTemplatePartialSpecializationDecl *
6480Sema::getMoreSpecializedPartialSpecialization(
6481 VarTemplatePartialSpecializationDecl *PS1,
6482 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
6483 // Pretend the variable template specializations are class template
6484 // specializations and form a fake injected class name type for comparison.
6485 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
6486 "the partial specializations being compared should specialize"
6487 " the same template.");
6488 TemplateName Name(PS1->getSpecializedTemplate()->getCanonicalDecl());
6489 QualType PT1 = Context.getCanonicalTemplateSpecializationType(
6490 Keyword: ElaboratedTypeKeyword::None, T: Name, CanonicalArgs: PS1->getTemplateArgs().asArray());
6491 QualType PT2 = Context.getCanonicalTemplateSpecializationType(
6492 Keyword: ElaboratedTypeKeyword::None, T: Name, CanonicalArgs: PS2->getTemplateArgs().asArray());
6493
6494 TemplateDeductionInfo Info(Loc);
6495 return getMoreSpecialized(S&: *this, T1: PT1, T2: PT2, P1: PS1, P2: PS2, Info);
6496}
6497
6498bool Sema::isMoreSpecializedThanPrimary(
6499 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
6500 VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
6501 TemplateName Name(Primary->getCanonicalDecl());
6502
6503 SmallVector<TemplateArgument, 8> PrimaryCanonArgs(
6504 Primary->getInjectedTemplateArgs(Context));
6505 Context.canonicalizeTemplateArguments(Args: PrimaryCanonArgs);
6506
6507 QualType PrimaryT = Context.getCanonicalTemplateSpecializationType(
6508 Keyword: ElaboratedTypeKeyword::None, T: Name, CanonicalArgs: PrimaryCanonArgs);
6509 QualType PartialT = Context.getCanonicalTemplateSpecializationType(
6510 Keyword: ElaboratedTypeKeyword::None, T: Name, CanonicalArgs: Spec->getTemplateArgs().asArray());
6511
6512 VarTemplatePartialSpecializationDecl *MaybeSpec =
6513 getMoreSpecialized(S&: *this, T1: PartialT, T2: PrimaryT, P1: Spec, P2: Primary, Info);
6514 if (MaybeSpec)
6515 Info.clearSFINAEDiagnostic();
6516 return MaybeSpec;
6517}
6518
6519bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
6520 TemplateParameterList *P, TemplateDecl *PArg, TemplateDecl *AArg,
6521 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
6522 bool PartialOrdering, bool *StrictPackMatch) {
6523 // C++1z [temp.arg.template]p4: (DR 150)
6524 // A template template-parameter P is at least as specialized as a
6525 // template template-argument A if, given the following rewrite to two
6526 // function templates...
6527
6528 // Rather than synthesize function templates, we merely perform the
6529 // equivalent partial ordering by performing deduction directly on
6530 // the template parameter lists of the template template parameters.
6531 //
6532 TemplateParameterList *A = AArg->getTemplateParameters();
6533
6534 Sema::InstantiatingTemplate Inst(
6535 *this, ArgLoc, Sema::InstantiatingTemplate::PartialOrderingTTP(), PArg,
6536 SourceRange(P->getTemplateLoc(), P->getRAngleLoc()));
6537 if (Inst.isInvalid())
6538 return false;
6539
6540 LocalInstantiationScope Scope(*this);
6541
6542 // Given an invented class template X with the template parameter list of
6543 // A (including default arguments):
6544 // - Each function template has a single function parameter whose type is
6545 // a specialization of X with template arguments corresponding to the
6546 // template parameters from the respective function template
6547 SmallVector<TemplateArgument, 8> AArgs(A->getInjectedTemplateArgs(Context));
6548
6549 // Check P's arguments against A's parameter list. This will fill in default
6550 // template arguments as needed. AArgs are already correct by construction.
6551 // We can't just use CheckTemplateIdType because that will expand alias
6552 // templates.
6553 SmallVector<TemplateArgument, 4> PArgs(P->getInjectedTemplateArgs(Context));
6554 {
6555 TemplateArgumentListInfo PArgList(P->getLAngleLoc(),
6556 P->getRAngleLoc());
6557 for (unsigned I = 0, N = P->size(); I != N; ++I) {
6558 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
6559 // expansions, to form an "as written" argument list.
6560 TemplateArgument Arg = PArgs[I];
6561 if (Arg.getKind() == TemplateArgument::Pack) {
6562 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
6563 Arg = *Arg.pack_begin();
6564 }
6565 PArgList.addArgument(Loc: getTrivialTemplateArgumentLoc(
6566 Arg, NTTPType: QualType(), Loc: P->getParam(Idx: I)->getLocation()));
6567 }
6568 PArgs.clear();
6569
6570 // C++1z [temp.arg.template]p3:
6571 // If the rewrite produces an invalid type, then P is not at least as
6572 // specialized as A.
6573 CheckTemplateArgumentInfo CTAI(
6574 /*PartialOrdering=*/false, /*MatchingTTP=*/true);
6575 CTAI.SugaredConverted = std::move(PArgs);
6576 if (CheckTemplateArgumentList(Template: AArg, TemplateLoc: ArgLoc, TemplateArgs&: PArgList, DefaultArgs,
6577 /*PartialTemplateArgs=*/false, CTAI,
6578 /*UpdateArgsWithConversions=*/true,
6579 /*ConstraintsNotSatisfied=*/nullptr))
6580 return false;
6581 PArgs = std::move(CTAI.SugaredConverted);
6582 if (StrictPackMatch)
6583 *StrictPackMatch |= CTAI.StrictPackMatch;
6584 }
6585
6586 // Determine whether P1 is at least as specialized as P2.
6587 TemplateDeductionInfo Info(ArgLoc, A->getDepth());
6588 SmallVector<DeducedTemplateArgument, 4> Deduced;
6589 Deduced.resize(N: A->size());
6590
6591 // ... the function template corresponding to P is at least as specialized
6592 // as the function template corresponding to A according to the partial
6593 // ordering rules for function templates.
6594
6595 // Provisional resolution for CWG2398: Regarding temp.arg.template]p4, when
6596 // applying the partial ordering rules for function templates on
6597 // the rewritten template template parameters:
6598 // - In a deduced context, the matching of packs versus fixed-size needs to
6599 // be inverted between Ps and As. On non-deduced context, matching needs to
6600 // happen both ways, according to [temp.arg.template]p3, but this is
6601 // currently implemented as a special case elsewhere.
6602 switch (::DeduceTemplateArguments(
6603 S&: *this, TemplateParams: A, Ps: AArgs, As: PArgs, Info, Deduced,
6604 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/true,
6605 PackFold: PartialOrdering ? PackFold::ArgumentToParameter : PackFold::Both,
6606 /*HasDeducedAnyParam=*/nullptr)) {
6607 case clang::TemplateDeductionResult::Success:
6608 if (StrictPackMatch && Info.hasStrictPackMatch())
6609 *StrictPackMatch = true;
6610 break;
6611
6612 case TemplateDeductionResult::MiscellaneousDeductionFailure:
6613 Diag(Loc: AArg->getLocation(), DiagID: diag::err_template_param_list_different_arity)
6614 << (A->size() > P->size()) << /*isTemplateTemplateParameter=*/true
6615 << SourceRange(A->getTemplateLoc(), P->getRAngleLoc());
6616 return false;
6617 case TemplateDeductionResult::NonDeducedMismatch:
6618 Diag(Loc: AArg->getLocation(), DiagID: diag::err_non_deduced_mismatch)
6619 << Info.FirstArg << Info.SecondArg;
6620 return false;
6621 case TemplateDeductionResult::Inconsistent:
6622 Diag(Loc: getAsNamedDecl(P: Info.Param)->getLocation(),
6623 DiagID: diag::err_inconsistent_deduction)
6624 << Info.FirstArg << Info.SecondArg;
6625 return false;
6626 case TemplateDeductionResult::AlreadyDiagnosed:
6627 return false;
6628
6629 // None of these should happen for a plain deduction.
6630 case TemplateDeductionResult::Invalid:
6631 case TemplateDeductionResult::InstantiationDepth:
6632 case TemplateDeductionResult::Incomplete:
6633 case TemplateDeductionResult::IncompletePack:
6634 case TemplateDeductionResult::Underqualified:
6635 case TemplateDeductionResult::SubstitutionFailure:
6636 case TemplateDeductionResult::DeducedMismatch:
6637 case TemplateDeductionResult::DeducedMismatchNested:
6638 case TemplateDeductionResult::TooManyArguments:
6639 case TemplateDeductionResult::TooFewArguments:
6640 case TemplateDeductionResult::InvalidExplicitArguments:
6641 case TemplateDeductionResult::NonDependentConversionFailure:
6642 case TemplateDeductionResult::ConstraintsNotSatisfied:
6643 case TemplateDeductionResult::CUDATargetMismatch:
6644 llvm_unreachable("Unexpected Result");
6645 }
6646
6647 TemplateDeductionResult TDK;
6648 runWithSufficientStackSpace(Loc: Info.getLocation(), Fn: [&] {
6649 TDK = ::FinishTemplateArgumentDeduction(
6650 S&: *this, Entity: AArg, EntityTPL: AArg->getTemplateParameters(), Template: AArg, PartialOrdering,
6651 Ps: AArgs, As: PArgs, Deduced, Info, /*CopyDeducedArgs=*/false);
6652 });
6653 switch (TDK) {
6654 case TemplateDeductionResult::Success:
6655 return true;
6656
6657 // It doesn't seem possible to get a non-deduced mismatch when partial
6658 // ordering TTPs, except with an invalid template parameter list which has
6659 // a parameter after a pack.
6660 case TemplateDeductionResult::NonDeducedMismatch:
6661 assert(PArg->isInvalidDecl() && "Unexpected NonDeducedMismatch");
6662 return false;
6663
6664 // Substitution failures should have already been diagnosed.
6665 case TemplateDeductionResult::AlreadyDiagnosed:
6666 case TemplateDeductionResult::SubstitutionFailure:
6667 case TemplateDeductionResult::InstantiationDepth:
6668 return false;
6669
6670 // None of these should happen when just converting deduced arguments.
6671 case TemplateDeductionResult::Invalid:
6672 case TemplateDeductionResult::Incomplete:
6673 case TemplateDeductionResult::IncompletePack:
6674 case TemplateDeductionResult::Inconsistent:
6675 case TemplateDeductionResult::Underqualified:
6676 case TemplateDeductionResult::DeducedMismatch:
6677 case TemplateDeductionResult::DeducedMismatchNested:
6678 case TemplateDeductionResult::TooManyArguments:
6679 case TemplateDeductionResult::TooFewArguments:
6680 case TemplateDeductionResult::InvalidExplicitArguments:
6681 case TemplateDeductionResult::NonDependentConversionFailure:
6682 case TemplateDeductionResult::ConstraintsNotSatisfied:
6683 case TemplateDeductionResult::MiscellaneousDeductionFailure:
6684 case TemplateDeductionResult::CUDATargetMismatch:
6685 llvm_unreachable("Unexpected Result");
6686 }
6687 llvm_unreachable("Unexpected TDK");
6688}
6689
6690namespace {
6691struct MarkUsedTemplateParameterVisitor : DynamicRecursiveASTVisitor {
6692 llvm::SmallBitVector &Used;
6693 unsigned Depth;
6694 bool VisitDeclRefTypes = true;
6695
6696 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used, unsigned Depth,
6697 bool VisitDeclRefTypes = true)
6698 : Used(Used), Depth(Depth), VisitDeclRefTypes(VisitDeclRefTypes) {}
6699
6700 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
6701 if (T->getDepth() == Depth)
6702 Used[T->getIndex()] = true;
6703 return true;
6704 }
6705
6706 bool TraverseTemplateName(TemplateName Template) override {
6707 if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
6708 Val: Template.getAsTemplateDecl()))
6709 if (TTP->getDepth() == Depth)
6710 Used[TTP->getIndex()] = true;
6711 DynamicRecursiveASTVisitor::TraverseTemplateName(Template);
6712 return true;
6713 }
6714
6715 bool VisitDeclRefExpr(DeclRefExpr *E) override {
6716 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: E->getDecl()))
6717 if (NTTP->getDepth() == Depth)
6718 Used[NTTP->getIndex()] = true;
6719 if (VisitDeclRefTypes)
6720 DynamicRecursiveASTVisitor::TraverseType(T: E->getType());
6721 return true;
6722 }
6723
6724 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
6725 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
6726 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
6727 if (TTP->getDepth() == Depth)
6728 Used[TTP->getIndex()] = true;
6729 }
6730 for (auto &TLoc : ULE->template_arguments())
6731 DynamicRecursiveASTVisitor::TraverseTemplateArgumentLoc(ArgLoc: TLoc);
6732 }
6733 return true;
6734 }
6735
6736 bool TraverseSizeOfPackExpr(SizeOfPackExpr *SOPE) override {
6737 return TraverseDecl(D: SOPE->getPack());
6738 }
6739};
6740}
6741
6742/// Mark the template parameters that are used by the given
6743/// expression.
6744static void
6745MarkUsedTemplateParameters(ASTContext &Ctx,
6746 const Expr *E,
6747 bool OnlyDeduced,
6748 unsigned Depth,
6749 llvm::SmallBitVector &Used) {
6750 if (!OnlyDeduced) {
6751 MarkUsedTemplateParameterVisitor(Used, Depth)
6752 .TraverseStmt(S: const_cast<Expr *>(E));
6753 return;
6754 }
6755
6756 // We can deduce from a pack expansion.
6757 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Val: E))
6758 E = Expansion->getPattern();
6759
6760 E = unwrapExpressionForDeduction(E);
6761 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E);
6762 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
6763 if (const auto *TTP = ULE->getTemplateTemplateDecl())
6764 Used[TTP->getIndex()] = true;
6765 for (auto &TLoc : ULE->template_arguments())
6766 MarkUsedTemplateParameters(Ctx, TemplateArg: TLoc.getArgument(), OnlyDeduced, Depth,
6767 Used);
6768 return;
6769 }
6770
6771 const NonTypeOrVarTemplateParmDecl NTTP =
6772 getDeducedNTTParameterFromExpr(E, Depth);
6773 if (!NTTP)
6774 return;
6775 if (NTTP.getDepth() == Depth)
6776 Used[NTTP.getIndex()] = true;
6777
6778 // In C++17 mode, additional arguments may be deduced from the type of a
6779 // non-type argument.
6780 if (Ctx.getLangOpts().CPlusPlus17)
6781 MarkUsedTemplateParameters(Ctx, T: NTTP.getType(), OnlyDeduced, Level: Depth, Deduced&: Used);
6782}
6783
6784/// Mark the template parameters that are used by the given
6785/// nested name specifier.
6786static void MarkUsedTemplateParameters(ASTContext &Ctx, NestedNameSpecifier NNS,
6787 bool OnlyDeduced, unsigned Depth,
6788 llvm::SmallBitVector &Used) {
6789 if (NNS.getKind() != NestedNameSpecifier::Kind::Type)
6790 return;
6791 MarkUsedTemplateParameters(Ctx, T: QualType(NNS.getAsType(), 0), OnlyDeduced,
6792 Level: Depth, Deduced&: Used);
6793}
6794
6795/// Mark the template parameters that are used by the given
6796/// template name.
6797static void
6798MarkUsedTemplateParameters(ASTContext &Ctx,
6799 TemplateName Name,
6800 bool OnlyDeduced,
6801 unsigned Depth,
6802 llvm::SmallBitVector &Used) {
6803 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
6804 if (TemplateTemplateParmDecl *TTP
6805 = dyn_cast<TemplateTemplateParmDecl>(Val: Template)) {
6806 if (TTP->getDepth() == Depth)
6807 Used[TTP->getIndex()] = true;
6808 }
6809 return;
6810 }
6811
6812 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
6813 MarkUsedTemplateParameters(Ctx, NNS: QTN->getQualifier(), OnlyDeduced,
6814 Depth, Used);
6815 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
6816 MarkUsedTemplateParameters(Ctx, NNS: DTN->getQualifier(), OnlyDeduced,
6817 Depth, Used);
6818}
6819
6820/// Mark the template parameters that are used by the given
6821/// type.
6822static void
6823MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
6824 bool OnlyDeduced,
6825 unsigned Depth,
6826 llvm::SmallBitVector &Used) {
6827 if (T.isNull())
6828 return;
6829
6830 // Non-dependent types have nothing deducible
6831 if (!T->isDependentType())
6832 return;
6833
6834 T = Ctx.getCanonicalType(T);
6835 switch (T->getTypeClass()) {
6836 case Type::Pointer:
6837 MarkUsedTemplateParameters(Ctx,
6838 T: cast<PointerType>(Val&: T)->getPointeeType(),
6839 OnlyDeduced,
6840 Depth,
6841 Used);
6842 break;
6843
6844 case Type::BlockPointer:
6845 MarkUsedTemplateParameters(Ctx,
6846 T: cast<BlockPointerType>(Val&: T)->getPointeeType(),
6847 OnlyDeduced,
6848 Depth,
6849 Used);
6850 break;
6851
6852 case Type::LValueReference:
6853 case Type::RValueReference:
6854 MarkUsedTemplateParameters(Ctx,
6855 T: cast<ReferenceType>(Val&: T)->getPointeeType(),
6856 OnlyDeduced,
6857 Depth,
6858 Used);
6859 break;
6860
6861 case Type::MemberPointer: {
6862 const MemberPointerType *MemPtr = cast<MemberPointerType>(Val: T.getTypePtr());
6863 MarkUsedTemplateParameters(Ctx, T: MemPtr->getPointeeType(), OnlyDeduced,
6864 Depth, Used);
6865 MarkUsedTemplateParameters(Ctx,
6866 T: QualType(MemPtr->getQualifier().getAsType(), 0),
6867 OnlyDeduced, Depth, Used);
6868 break;
6869 }
6870
6871 case Type::DependentSizedArray:
6872 MarkUsedTemplateParameters(Ctx,
6873 E: cast<DependentSizedArrayType>(Val&: T)->getSizeExpr(),
6874 OnlyDeduced, Depth, Used);
6875 // Fall through to check the element type
6876 [[fallthrough]];
6877
6878 case Type::ConstantArray:
6879 case Type::IncompleteArray:
6880 case Type::ArrayParameter:
6881 MarkUsedTemplateParameters(Ctx,
6882 T: cast<ArrayType>(Val&: T)->getElementType(),
6883 OnlyDeduced, Depth, Used);
6884 break;
6885 case Type::Vector:
6886 case Type::ExtVector:
6887 MarkUsedTemplateParameters(Ctx,
6888 T: cast<VectorType>(Val&: T)->getElementType(),
6889 OnlyDeduced, Depth, Used);
6890 break;
6891
6892 case Type::DependentVector: {
6893 const auto *VecType = cast<DependentVectorType>(Val&: T);
6894 MarkUsedTemplateParameters(Ctx, T: VecType->getElementType(), OnlyDeduced,
6895 Depth, Used);
6896 MarkUsedTemplateParameters(Ctx, E: VecType->getSizeExpr(), OnlyDeduced, Depth,
6897 Used);
6898 break;
6899 }
6900 case Type::DependentSizedExtVector: {
6901 const DependentSizedExtVectorType *VecType
6902 = cast<DependentSizedExtVectorType>(Val&: T);
6903 MarkUsedTemplateParameters(Ctx, T: VecType->getElementType(), OnlyDeduced,
6904 Depth, Used);
6905 MarkUsedTemplateParameters(Ctx, E: VecType->getSizeExpr(), OnlyDeduced,
6906 Depth, Used);
6907 break;
6908 }
6909
6910 case Type::DependentAddressSpace: {
6911 const DependentAddressSpaceType *DependentASType =
6912 cast<DependentAddressSpaceType>(Val&: T);
6913 MarkUsedTemplateParameters(Ctx, T: DependentASType->getPointeeType(),
6914 OnlyDeduced, Depth, Used);
6915 MarkUsedTemplateParameters(Ctx,
6916 E: DependentASType->getAddrSpaceExpr(),
6917 OnlyDeduced, Depth, Used);
6918 break;
6919 }
6920
6921 case Type::ConstantMatrix: {
6922 const ConstantMatrixType *MatType = cast<ConstantMatrixType>(Val&: T);
6923 MarkUsedTemplateParameters(Ctx, T: MatType->getElementType(), OnlyDeduced,
6924 Depth, Used);
6925 break;
6926 }
6927
6928 case Type::DependentSizedMatrix: {
6929 const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(Val&: T);
6930 MarkUsedTemplateParameters(Ctx, T: MatType->getElementType(), OnlyDeduced,
6931 Depth, Used);
6932 MarkUsedTemplateParameters(Ctx, E: MatType->getRowExpr(), OnlyDeduced, Depth,
6933 Used);
6934 MarkUsedTemplateParameters(Ctx, E: MatType->getColumnExpr(), OnlyDeduced,
6935 Depth, Used);
6936 break;
6937 }
6938
6939 case Type::FunctionProto: {
6940 const FunctionProtoType *Proto = cast<FunctionProtoType>(Val&: T);
6941 MarkUsedTemplateParameters(Ctx, T: Proto->getReturnType(), OnlyDeduced, Depth,
6942 Used);
6943 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
6944 // C++17 [temp.deduct.type]p5:
6945 // The non-deduced contexts are: [...]
6946 // -- A function parameter pack that does not occur at the end of the
6947 // parameter-declaration-list.
6948 if (!OnlyDeduced || I + 1 == N ||
6949 !Proto->getParamType(i: I)->getAs<PackExpansionType>()) {
6950 MarkUsedTemplateParameters(Ctx, T: Proto->getParamType(i: I), OnlyDeduced,
6951 Depth, Used);
6952 } else {
6953 // FIXME: C++17 [temp.deduct.call]p1:
6954 // When a function parameter pack appears in a non-deduced context,
6955 // the type of that pack is never deduced.
6956 //
6957 // We should also track a set of "never deduced" parameters, and
6958 // subtract that from the list of deduced parameters after marking.
6959 }
6960 }
6961 if (auto *E = Proto->getNoexceptExpr())
6962 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
6963 break;
6964 }
6965
6966 case Type::TemplateTypeParm: {
6967 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(Val&: T);
6968 if (TTP->getDepth() == Depth)
6969 Used[TTP->getIndex()] = true;
6970 break;
6971 }
6972
6973 case Type::SubstTemplateTypeParmPack: {
6974 const SubstTemplateTypeParmPackType *Subst
6975 = cast<SubstTemplateTypeParmPackType>(Val&: T);
6976 if (Subst->getReplacedParameter()->getDepth() == Depth)
6977 Used[Subst->getIndex()] = true;
6978 MarkUsedTemplateParameters(Ctx, TemplateArg: Subst->getArgumentPack(), OnlyDeduced,
6979 Depth, Used);
6980 break;
6981 }
6982 case Type::SubstBuiltinTemplatePack: {
6983 MarkUsedTemplateParameters(Ctx, TemplateArg: cast<SubstPackType>(Val&: T)->getArgumentPack(),
6984 OnlyDeduced, Depth, Used);
6985 break;
6986 }
6987
6988 case Type::InjectedClassName:
6989 T = cast<InjectedClassNameType>(Val&: T)
6990 ->getDecl()
6991 ->getCanonicalTemplateSpecializationType(Ctx);
6992 [[fallthrough]];
6993
6994 case Type::TemplateSpecialization: {
6995 const TemplateSpecializationType *Spec
6996 = cast<TemplateSpecializationType>(Val&: T);
6997
6998 TemplateName Name = Spec->getTemplateName();
6999 if (OnlyDeduced && Name.getAsDependentTemplateName())
7000 break;
7001
7002 MarkUsedTemplateParameters(Ctx, Name, OnlyDeduced, Depth, Used);
7003
7004 // C++0x [temp.deduct.type]p9:
7005 // If the template argument list of P contains a pack expansion that is
7006 // not the last template argument, the entire template argument list is a
7007 // non-deduced context.
7008 if (OnlyDeduced &&
7009 hasPackExpansionBeforeEnd(Args: Spec->template_arguments()))
7010 break;
7011
7012 for (const auto &Arg : Spec->template_arguments())
7013 MarkUsedTemplateParameters(Ctx, TemplateArg: Arg, OnlyDeduced, Depth, Used);
7014 break;
7015 }
7016
7017 case Type::Complex:
7018 if (!OnlyDeduced)
7019 MarkUsedTemplateParameters(Ctx,
7020 T: cast<ComplexType>(Val&: T)->getElementType(),
7021 OnlyDeduced, Depth, Used);
7022 break;
7023
7024 case Type::Atomic:
7025 if (!OnlyDeduced)
7026 MarkUsedTemplateParameters(Ctx,
7027 T: cast<AtomicType>(Val&: T)->getValueType(),
7028 OnlyDeduced, Depth, Used);
7029 break;
7030
7031 case Type::DependentName:
7032 if (!OnlyDeduced)
7033 MarkUsedTemplateParameters(Ctx,
7034 NNS: cast<DependentNameType>(Val&: T)->getQualifier(),
7035 OnlyDeduced, Depth, Used);
7036 break;
7037
7038 case Type::TypeOf:
7039 if (!OnlyDeduced)
7040 MarkUsedTemplateParameters(Ctx, T: cast<TypeOfType>(Val&: T)->getUnmodifiedType(),
7041 OnlyDeduced, Depth, Used);
7042 break;
7043
7044 case Type::TypeOfExpr:
7045 if (!OnlyDeduced)
7046 MarkUsedTemplateParameters(Ctx,
7047 E: cast<TypeOfExprType>(Val&: T)->getUnderlyingExpr(),
7048 OnlyDeduced, Depth, Used);
7049 break;
7050
7051 case Type::Decltype:
7052 if (!OnlyDeduced)
7053 MarkUsedTemplateParameters(Ctx,
7054 E: cast<DecltypeType>(Val&: T)->getUnderlyingExpr(),
7055 OnlyDeduced, Depth, Used);
7056 break;
7057
7058 case Type::PackIndexing:
7059 if (!OnlyDeduced) {
7060 MarkUsedTemplateParameters(Ctx, T: cast<PackIndexingType>(Val&: T)->getPattern(),
7061 OnlyDeduced, Depth, Used);
7062 MarkUsedTemplateParameters(Ctx, E: cast<PackIndexingType>(Val&: T)->getIndexExpr(),
7063 OnlyDeduced, Depth, Used);
7064 }
7065 break;
7066
7067 case Type::UnaryTransform:
7068 if (!OnlyDeduced) {
7069 auto *UTT = cast<UnaryTransformType>(Val&: T);
7070 auto Next = UTT->getUnderlyingType();
7071 if (Next.isNull())
7072 Next = UTT->getBaseType();
7073 MarkUsedTemplateParameters(Ctx, T: Next, OnlyDeduced, Depth, Used);
7074 }
7075 break;
7076
7077 case Type::PackExpansion:
7078 MarkUsedTemplateParameters(Ctx,
7079 T: cast<PackExpansionType>(Val&: T)->getPattern(),
7080 OnlyDeduced, Depth, Used);
7081 break;
7082
7083 case Type::Auto:
7084 case Type::DeducedTemplateSpecialization:
7085 MarkUsedTemplateParameters(Ctx,
7086 T: cast<DeducedType>(Val&: T)->getDeducedType(),
7087 OnlyDeduced, Depth, Used);
7088 break;
7089 case Type::DependentBitInt:
7090 MarkUsedTemplateParameters(Ctx,
7091 E: cast<DependentBitIntType>(Val&: T)->getNumBitsExpr(),
7092 OnlyDeduced, Depth, Used);
7093 break;
7094
7095 case Type::HLSLAttributedResource:
7096 MarkUsedTemplateParameters(
7097 Ctx, T: cast<HLSLAttributedResourceType>(Val&: T)->getWrappedType(), OnlyDeduced,
7098 Depth, Used);
7099 if (cast<HLSLAttributedResourceType>(Val&: T)->hasContainedType())
7100 MarkUsedTemplateParameters(
7101 Ctx, T: cast<HLSLAttributedResourceType>(Val&: T)->getContainedType(),
7102 OnlyDeduced, Depth, Used);
7103 break;
7104
7105 // None of these types have any template parameters in them.
7106 case Type::Builtin:
7107 case Type::VariableArray:
7108 case Type::FunctionNoProto:
7109 case Type::Record:
7110 case Type::Enum:
7111 case Type::ObjCInterface:
7112 case Type::ObjCObject:
7113 case Type::ObjCObjectPointer:
7114 case Type::UnresolvedUsing:
7115 case Type::Pipe:
7116 case Type::BitInt:
7117 case Type::HLSLInlineSpirv:
7118 case Type::OverflowBehavior:
7119#define TYPE(Class, Base)
7120#define ABSTRACT_TYPE(Class, Base)
7121#define DEPENDENT_TYPE(Class, Base)
7122#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7123#include "clang/AST/TypeNodes.inc"
7124 break;
7125 }
7126}
7127
7128/// Mark the template parameters that are used by this
7129/// template argument.
7130static void
7131MarkUsedTemplateParameters(ASTContext &Ctx,
7132 const TemplateArgument &TemplateArg,
7133 bool OnlyDeduced,
7134 unsigned Depth,
7135 llvm::SmallBitVector &Used) {
7136 switch (TemplateArg.getKind()) {
7137 case TemplateArgument::Null:
7138 case TemplateArgument::Integral:
7139 case TemplateArgument::Declaration:
7140 case TemplateArgument::NullPtr:
7141 case TemplateArgument::StructuralValue:
7142 break;
7143
7144 case TemplateArgument::Type:
7145 MarkUsedTemplateParameters(Ctx, T: TemplateArg.getAsType(), OnlyDeduced,
7146 Depth, Used);
7147 break;
7148
7149 case TemplateArgument::Template:
7150 case TemplateArgument::TemplateExpansion:
7151 MarkUsedTemplateParameters(Ctx,
7152 Name: TemplateArg.getAsTemplateOrTemplatePattern(),
7153 OnlyDeduced, Depth, Used);
7154 break;
7155
7156 case TemplateArgument::Expression:
7157 MarkUsedTemplateParameters(Ctx, E: TemplateArg.getAsExpr(), OnlyDeduced,
7158 Depth, Used);
7159 break;
7160
7161 case TemplateArgument::Pack:
7162 for (const auto &P : TemplateArg.pack_elements())
7163 MarkUsedTemplateParameters(Ctx, TemplateArg: P, OnlyDeduced, Depth, Used);
7164 break;
7165 }
7166}
7167
7168void
7169Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
7170 unsigned Depth,
7171 llvm::SmallBitVector &Used) {
7172 ::MarkUsedTemplateParameters(Ctx&: Context, E, OnlyDeduced, Depth, Used);
7173}
7174
7175void Sema::MarkUsedTemplateParametersForSubsumptionParameterMapping(
7176 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used) {
7177 MarkUsedTemplateParameterVisitor(Used, Depth, /*VisitDeclRefTypes=*/false)
7178 .TraverseStmt(S: const_cast<Expr *>(E));
7179}
7180
7181void
7182Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
7183 bool OnlyDeduced, unsigned Depth,
7184 llvm::SmallBitVector &Used) {
7185 // C++0x [temp.deduct.type]p9:
7186 // If the template argument list of P contains a pack expansion that is not
7187 // the last template argument, the entire template argument list is a
7188 // non-deduced context.
7189 if (OnlyDeduced &&
7190 hasPackExpansionBeforeEnd(Args: TemplateArgs.asArray()))
7191 return;
7192
7193 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7194 ::MarkUsedTemplateParameters(Ctx&: Context, TemplateArg: TemplateArgs[I], OnlyDeduced,
7195 Depth, Used);
7196}
7197
7198void Sema::MarkUsedTemplateParameters(ArrayRef<TemplateArgument> TemplateArgs,
7199 unsigned Depth,
7200 llvm::SmallBitVector &Used) {
7201 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7202 ::MarkUsedTemplateParameters(Ctx&: Context, TemplateArg: TemplateArgs[I],
7203 /*OnlyDeduced=*/false, Depth, Used);
7204}
7205
7206void Sema::MarkUsedTemplateParameters(
7207 ArrayRef<TemplateArgumentLoc> TemplateArgs, unsigned Depth,
7208 llvm::SmallBitVector &Used) {
7209 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7210 ::MarkUsedTemplateParameters(Ctx&: Context, TemplateArg: TemplateArgs[I].getArgument(),
7211 /*OnlyDeduced=*/false, Depth, Used);
7212}
7213
7214void Sema::MarkDeducedTemplateParameters(
7215 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
7216 llvm::SmallBitVector &Deduced) {
7217 TemplateParameterList *TemplateParams
7218 = FunctionTemplate->getTemplateParameters();
7219 Deduced.clear();
7220 Deduced.resize(N: TemplateParams->size());
7221
7222 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
7223 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
7224 ::MarkUsedTemplateParameters(Ctx, T: Function->getParamDecl(i: I)->getType(),
7225 OnlyDeduced: true, Depth: TemplateParams->getDepth(), Used&: Deduced);
7226}
7227
7228bool hasDeducibleTemplateParameters(Sema &S,
7229 FunctionTemplateDecl *FunctionTemplate,
7230 QualType T) {
7231 if (!T->isDependentType())
7232 return false;
7233
7234 TemplateParameterList *TemplateParams
7235 = FunctionTemplate->getTemplateParameters();
7236 llvm::SmallBitVector Deduced(TemplateParams->size());
7237 ::MarkUsedTemplateParameters(Ctx&: S.Context, T, OnlyDeduced: true, Depth: TemplateParams->getDepth(),
7238 Used&: Deduced);
7239
7240 return Deduced.any();
7241}
7242