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

source code of clang/lib/Sema/SemaTemplateDeduction.cpp