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