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 "clang/Sema/TemplateDeduction.h"
14 #include "TreeTransform.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclAccessPair.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NestedNameSpecifier.h"
27 #include "clang/AST/TemplateBase.h"
28 #include "clang/AST/TemplateName.h"
29 #include "clang/AST/Type.h"
30 #include "clang/AST/TypeLoc.h"
31 #include "clang/AST/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/Ownership.h"
40 #include "clang/Sema/Sema.h"
41 #include "clang/Sema/Template.h"
42 #include "llvm/ADT/APInt.h"
43 #include "llvm/ADT/APSInt.h"
44 #include "llvm/ADT/ArrayRef.h"
45 #include "llvm/ADT/DenseMap.h"
46 #include "llvm/ADT/FoldingSet.h"
47 #include "llvm/ADT/Optional.h"
48 #include "llvm/ADT/SmallBitVector.h"
49 #include "llvm/ADT/SmallPtrSet.h"
50 #include "llvm/ADT/SmallVector.h"
51 #include "llvm/Support/Casting.h"
52 #include "llvm/Support/Compiler.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include <algorithm>
55 #include <cassert>
56 #include <tuple>
57 #include <utility>
58 
59 namespace clang {
60 
61   /// Various flags that control template argument deduction.
62   ///
63   /// These flags can be bitwise-OR'd together.
64   enum TemplateDeductionFlags {
65     /// No template argument deduction flags, which indicates the
66     /// strictest results for template argument deduction (as used for, e.g.,
67     /// matching class template partial specializations).
68     TDF_None = 0,
69 
70     /// Within template argument deduction from a function call, we are
71     /// matching with a parameter type for which the original parameter was
72     /// a reference.
73     TDF_ParamWithReferenceType = 0x1,
74 
75     /// Within template argument deduction from a function call, we
76     /// are matching in a case where we ignore cv-qualifiers.
77     TDF_IgnoreQualifiers = 0x02,
78 
79     /// Within template argument deduction from a function call,
80     /// we are matching in a case where we can perform template argument
81     /// deduction from a template-id of a derived class of the argument type.
82     TDF_DerivedClass = 0x04,
83 
84     /// Allow non-dependent types to differ, e.g., when performing
85     /// template argument deduction from a function call where conversions
86     /// may apply.
87     TDF_SkipNonDependent = 0x08,
88 
89     /// Whether we are performing template argument deduction for
90     /// parameters and arguments in a top-level template argument
91     TDF_TopLevelParameterTypeList = 0x10,
92 
93     /// Within template argument deduction from overload resolution per
94     /// C++ [over.over] allow matching function types that are compatible in
95     /// terms of noreturn and default calling convention adjustments, or
96     /// similarly matching a declared template specialization against a
97     /// possible template, per C++ [temp.deduct.decl]. In either case, permit
98     /// deduction where the parameter is a function type that can be converted
99     /// to the argument type.
100     TDF_AllowCompatibleFunctionType = 0x20,
101 
102     /// Within template argument deduction for a conversion function, we are
103     /// matching with an argument type for which the original argument was
104     /// a reference.
105     TDF_ArgWithReferenceType = 0x40,
106   };
107 }
108 
109 using namespace clang;
110 using namespace sema;
111 
112 /// Compare two APSInts, extending and switching the sign as
113 /// necessary to compare their values regardless of underlying type.
114 static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
115   if (Y.getBitWidth() > X.getBitWidth())
116     X = X.extend(Y.getBitWidth());
117   else if (Y.getBitWidth() < X.getBitWidth())
118     Y = Y.extend(X.getBitWidth());
119 
120   // If there is a signedness mismatch, correct it.
121   if (X.isSigned() != Y.isSigned()) {
122     // If the signed value is negative, then the values cannot be the same.
123     if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
124       return false;
125 
126     Y.setIsSigned(true);
127     X.setIsSigned(true);
128   }
129 
130   return X == Y;
131 }
132 
133 static Sema::TemplateDeductionResult
134 DeduceTemplateArguments(Sema &S,
135                         TemplateParameterList *TemplateParams,
136                         const TemplateArgument &Param,
137                         TemplateArgument Arg,
138                         TemplateDeductionInfo &Info,
139                         SmallVectorImpl<DeducedTemplateArgument> &Deduced);
140 
141 static Sema::TemplateDeductionResult
142 DeduceTemplateArgumentsByTypeMatch(Sema &S,
143                                    TemplateParameterList *TemplateParams,
144                                    QualType Param,
145                                    QualType Arg,
146                                    TemplateDeductionInfo &Info,
147                                    SmallVectorImpl<DeducedTemplateArgument> &
148                                                       Deduced,
149                                    unsigned TDF,
150                                    bool PartialOrdering = false,
151                                    bool DeducedFromArrayBound = false);
152 
153 static Sema::TemplateDeductionResult
154 DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
155                         ArrayRef<TemplateArgument> Params,
156                         ArrayRef<TemplateArgument> Args,
157                         TemplateDeductionInfo &Info,
158                         SmallVectorImpl<DeducedTemplateArgument> &Deduced,
159                         bool NumberOfArgumentsMustMatch);
160 
161 static void MarkUsedTemplateParameters(ASTContext &Ctx,
162                                        const TemplateArgument &TemplateArg,
163                                        bool OnlyDeduced, unsigned Depth,
164                                        llvm::SmallBitVector &Used);
165 
166 static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
167                                        bool OnlyDeduced, unsigned Level,
168                                        llvm::SmallBitVector &Deduced);
169 
170 /// If the given expression is of a form that permits the deduction
171 /// of a non-type template parameter, return the declaration of that
172 /// non-type template parameter.
173 static NonTypeTemplateParmDecl *
174 getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
175   // If we are within an alias template, the expression may have undergone
176   // any number of parameter substitutions already.
177   while (true) {
178     if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
179       E = IC->getSubExpr();
180     else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(E))
181       E = CE->getSubExpr();
182     else if (SubstNonTypeTemplateParmExpr *Subst =
183                dyn_cast<SubstNonTypeTemplateParmExpr>(E))
184       E = Subst->getReplacement();
185     else
186       break;
187   }
188 
189   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
190     if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
191       if (NTTP->getDepth() == Info.getDeducedDepth())
192         return NTTP;
193 
194   return nullptr;
195 }
196 
197 /// Determine whether two declaration pointers refer to the same
198 /// declaration.
199 static bool isSameDeclaration(Decl *X, Decl *Y) {
200   if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
201     X = NX->getUnderlyingDecl();
202   if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
203     Y = NY->getUnderlyingDecl();
204 
205   return X->getCanonicalDecl() == Y->getCanonicalDecl();
206 }
207 
208 /// Verify that the given, deduced template arguments are compatible.
209 ///
210 /// \returns The deduced template argument, or a NULL template argument if
211 /// the deduced template arguments were incompatible.
212 static DeducedTemplateArgument
213 checkDeducedTemplateArguments(ASTContext &Context,
214                               const DeducedTemplateArgument &X,
215                               const DeducedTemplateArgument &Y) {
216   // We have no deduction for one or both of the arguments; they're compatible.
217   if (X.isNull())
218     return Y;
219   if (Y.isNull())
220     return X;
221 
222   // If we have two non-type template argument values deduced for the same
223   // parameter, they must both match the type of the parameter, and thus must
224   // match each other's type. As we're only keeping one of them, we must check
225   // for that now. The exception is that if either was deduced from an array
226   // bound, the type is permitted to differ.
227   if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
228     QualType XType = X.getNonTypeTemplateArgumentType();
229     if (!XType.isNull()) {
230       QualType YType = Y.getNonTypeTemplateArgumentType();
231       if (YType.isNull() || !Context.hasSameType(XType, YType))
232         return DeducedTemplateArgument();
233     }
234   }
235 
236   switch (X.getKind()) {
237   case TemplateArgument::Null:
238     llvm_unreachable("Non-deduced template arguments handled above");
239 
240   case TemplateArgument::Type:
241     // If two template type arguments have the same type, they're compatible.
242     if (Y.getKind() == TemplateArgument::Type &&
243         Context.hasSameType(X.getAsType(), Y.getAsType()))
244       return X;
245 
246     // If one of the two arguments was deduced from an array bound, the other
247     // supersedes it.
248     if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
249       return X.wasDeducedFromArrayBound() ? Y : X;
250 
251     // The arguments are not compatible.
252     return DeducedTemplateArgument();
253 
254   case TemplateArgument::Integral:
255     // If we deduced a constant in one case and either a dependent expression or
256     // declaration in another case, keep the integral constant.
257     // If both are integral constants with the same value, keep that value.
258     if (Y.getKind() == TemplateArgument::Expression ||
259         Y.getKind() == TemplateArgument::Declaration ||
260         (Y.getKind() == TemplateArgument::Integral &&
261          hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
262       return X.wasDeducedFromArrayBound() ? Y : X;
263 
264     // All other combinations are incompatible.
265     return DeducedTemplateArgument();
266 
267   case TemplateArgument::Template:
268     if (Y.getKind() == TemplateArgument::Template &&
269         Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
270       return X;
271 
272     // All other combinations are incompatible.
273     return DeducedTemplateArgument();
274 
275   case TemplateArgument::TemplateExpansion:
276     if (Y.getKind() == TemplateArgument::TemplateExpansion &&
277         Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
278                                     Y.getAsTemplateOrTemplatePattern()))
279       return X;
280 
281     // All other combinations are incompatible.
282     return DeducedTemplateArgument();
283 
284   case TemplateArgument::Expression: {
285     if (Y.getKind() != TemplateArgument::Expression)
286       return checkDeducedTemplateArguments(Context, Y, X);
287 
288     // Compare the expressions for equality
289     llvm::FoldingSetNodeID ID1, ID2;
290     X.getAsExpr()->Profile(ID1, Context, true);
291     Y.getAsExpr()->Profile(ID2, Context, true);
292     if (ID1 == ID2)
293       return X.wasDeducedFromArrayBound() ? Y : X;
294 
295     // Differing dependent expressions are incompatible.
296     return DeducedTemplateArgument();
297   }
298 
299   case TemplateArgument::Declaration:
300     assert(!X.wasDeducedFromArrayBound());
301 
302     // If we deduced a declaration and a dependent expression, keep the
303     // declaration.
304     if (Y.getKind() == TemplateArgument::Expression)
305       return X;
306 
307     // If we deduced a declaration and an integral constant, keep the
308     // integral constant and whichever type did not come from an array
309     // bound.
310     if (Y.getKind() == TemplateArgument::Integral) {
311       if (Y.wasDeducedFromArrayBound())
312         return TemplateArgument(Context, Y.getAsIntegral(),
313                                 X.getParamTypeForDecl());
314       return Y;
315     }
316 
317     // If we deduced two declarations, make sure that they refer to the
318     // same declaration.
319     if (Y.getKind() == TemplateArgument::Declaration &&
320         isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
321       return X;
322 
323     // All other combinations are incompatible.
324     return DeducedTemplateArgument();
325 
326   case TemplateArgument::NullPtr:
327     // If we deduced a null pointer and a dependent expression, keep the
328     // null pointer.
329     if (Y.getKind() == TemplateArgument::Expression)
330       return X;
331 
332     // If we deduced a null pointer and an integral constant, keep the
333     // integral constant.
334     if (Y.getKind() == TemplateArgument::Integral)
335       return Y;
336 
337     // If we deduced two null pointers, they are the same.
338     if (Y.getKind() == TemplateArgument::NullPtr)
339       return X;
340 
341     // All other combinations are incompatible.
342     return DeducedTemplateArgument();
343 
344   case TemplateArgument::Pack: {
345     if (Y.getKind() != TemplateArgument::Pack ||
346         X.pack_size() != Y.pack_size())
347       return DeducedTemplateArgument();
348 
349     llvm::SmallVector<TemplateArgument, 8> NewPack;
350     for (TemplateArgument::pack_iterator XA = X.pack_begin(),
351                                       XAEnd = X.pack_end(),
352                                          YA = Y.pack_begin();
353          XA != XAEnd; ++XA, ++YA) {
354       TemplateArgument Merged = checkDeducedTemplateArguments(
355           Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
356           DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
357       if (Merged.isNull())
358         return DeducedTemplateArgument();
359       NewPack.push_back(Merged);
360     }
361 
362     return DeducedTemplateArgument(
363         TemplateArgument::CreatePackCopy(Context, NewPack),
364         X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
365   }
366   }
367 
368   llvm_unreachable("Invalid TemplateArgument Kind!");
369 }
370 
371 /// Deduce the value of the given non-type template parameter
372 /// as the given deduced template argument. All non-type template parameter
373 /// deduction is funneled through here.
374 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
375     Sema &S, TemplateParameterList *TemplateParams,
376     NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
377     QualType ValueType, TemplateDeductionInfo &Info,
378     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
379   assert(NTTP->getDepth() == Info.getDeducedDepth() &&
380          "deducing non-type template argument with wrong depth");
381 
382   DeducedTemplateArgument Result = checkDeducedTemplateArguments(
383       S.Context, Deduced[NTTP->getIndex()], NewDeduced);
384   if (Result.isNull()) {
385     Info.Param = NTTP;
386     Info.FirstArg = Deduced[NTTP->getIndex()];
387     Info.SecondArg = NewDeduced;
388     return Sema::TDK_Inconsistent;
389   }
390 
391   Deduced[NTTP->getIndex()] = Result;
392   if (!S.getLangOpts().CPlusPlus17)
393     return Sema::TDK_Success;
394 
395   if (NTTP->isExpandedParameterPack())
396     // FIXME: We may still need to deduce parts of the type here! But we
397     // don't have any way to find which slice of the type to use, and the
398     // type stored on the NTTP itself is nonsense. Perhaps the type of an
399     // expanded NTTP should be a pack expansion type?
400     return Sema::TDK_Success;
401 
402   // Get the type of the parameter for deduction. If it's a (dependent) array
403   // or function type, we will not have decayed it yet, so do that now.
404   QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
405   if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
406     ParamType = Expansion->getPattern();
407 
408   // FIXME: It's not clear how deduction of a parameter of reference
409   // type from an argument (of non-reference type) should be performed.
410   // For now, we just remove reference types from both sides and let
411   // the final check for matching types sort out the mess.
412   return DeduceTemplateArgumentsByTypeMatch(
413       S, TemplateParams, ParamType.getNonReferenceType(),
414       ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
415       /*PartialOrdering=*/false,
416       /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
417 }
418 
419 /// Deduce the value of the given non-type template parameter
420 /// from the given integral constant.
421 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
422     Sema &S, TemplateParameterList *TemplateParams,
423     NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
424     QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
425     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
426   return DeduceNonTypeTemplateArgument(
427       S, TemplateParams, NTTP,
428       DeducedTemplateArgument(S.Context, Value, ValueType,
429                               DeducedFromArrayBound),
430       ValueType, Info, Deduced);
431 }
432 
433 /// Deduce the value of the given non-type template parameter
434 /// from the given null pointer template argument type.
435 static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
436     Sema &S, TemplateParameterList *TemplateParams,
437     NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
438     TemplateDeductionInfo &Info,
439     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
440   Expr *Value =
441       S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
442                               S.Context.NullPtrTy, NTTP->getLocation()),
443                           NullPtrType, CK_NullToPointer)
444           .get();
445   return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
446                                        DeducedTemplateArgument(Value),
447                                        Value->getType(), Info, Deduced);
448 }
449 
450 /// Deduce the value of the given non-type template parameter
451 /// from the given type- or value-dependent expression.
452 ///
453 /// \returns true if deduction succeeded, false otherwise.
454 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
455     Sema &S, TemplateParameterList *TemplateParams,
456     NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
457     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
458   return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
459                                        DeducedTemplateArgument(Value),
460                                        Value->getType(), Info, Deduced);
461 }
462 
463 /// Deduce the value of the given non-type template parameter
464 /// from the given declaration.
465 ///
466 /// \returns true if deduction succeeded, false otherwise.
467 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
468     Sema &S, TemplateParameterList *TemplateParams,
469     NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
470     TemplateDeductionInfo &Info,
471     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
472   D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
473   TemplateArgument New(D, T);
474   return DeduceNonTypeTemplateArgument(
475       S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
476 }
477 
478 static Sema::TemplateDeductionResult
479 DeduceTemplateArguments(Sema &S,
480                         TemplateParameterList *TemplateParams,
481                         TemplateName Param,
482                         TemplateName Arg,
483                         TemplateDeductionInfo &Info,
484                         SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
485   TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
486   if (!ParamDecl) {
487     // The parameter type is dependent and is not a template template parameter,
488     // so there is nothing that we can deduce.
489     return Sema::TDK_Success;
490   }
491 
492   if (TemplateTemplateParmDecl *TempParam
493         = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
494     // If we're not deducing at this depth, there's nothing to deduce.
495     if (TempParam->getDepth() != Info.getDeducedDepth())
496       return Sema::TDK_Success;
497 
498     DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
499     DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
500                                                  Deduced[TempParam->getIndex()],
501                                                                    NewDeduced);
502     if (Result.isNull()) {
503       Info.Param = TempParam;
504       Info.FirstArg = Deduced[TempParam->getIndex()];
505       Info.SecondArg = NewDeduced;
506       return Sema::TDK_Inconsistent;
507     }
508 
509     Deduced[TempParam->getIndex()] = Result;
510     return Sema::TDK_Success;
511   }
512 
513   // Verify that the two template names are equivalent.
514   if (S.Context.hasSameTemplateName(Param, Arg))
515     return Sema::TDK_Success;
516 
517   // Mismatch of non-dependent template parameter to argument.
518   Info.FirstArg = TemplateArgument(Param);
519   Info.SecondArg = TemplateArgument(Arg);
520   return Sema::TDK_NonDeducedMismatch;
521 }
522 
523 /// Deduce the template arguments by comparing the template parameter
524 /// type (which is a template-id) with the template argument type.
525 ///
526 /// \param S the Sema
527 ///
528 /// \param TemplateParams the template parameters that we are deducing
529 ///
530 /// \param Param the parameter type
531 ///
532 /// \param Arg the argument type
533 ///
534 /// \param Info information about the template argument deduction itself
535 ///
536 /// \param Deduced the deduced template arguments
537 ///
538 /// \returns the result of template argument deduction so far. Note that a
539 /// "success" result means that template argument deduction has not yet failed,
540 /// but it may still fail, later, for other reasons.
541 static Sema::TemplateDeductionResult
542 DeduceTemplateArguments(Sema &S,
543                         TemplateParameterList *TemplateParams,
544                         const TemplateSpecializationType *Param,
545                         QualType Arg,
546                         TemplateDeductionInfo &Info,
547                         SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
548   assert(Arg.isCanonical() && "Argument type must be canonical");
549 
550   // Treat an injected-class-name as its underlying template-id.
551   if (auto *Injected = dyn_cast<InjectedClassNameType>(Arg))
552     Arg = Injected->getInjectedSpecializationType();
553 
554   // Check whether the template argument is a dependent template-id.
555   if (const TemplateSpecializationType *SpecArg
556         = dyn_cast<TemplateSpecializationType>(Arg)) {
557     // Perform template argument deduction for the template name.
558     if (Sema::TemplateDeductionResult Result
559           = DeduceTemplateArguments(S, TemplateParams,
560                                     Param->getTemplateName(),
561                                     SpecArg->getTemplateName(),
562                                     Info, Deduced))
563       return Result;
564 
565 
566     // Perform template argument deduction on each template
567     // argument. Ignore any missing/extra arguments, since they could be
568     // filled in by default arguments.
569     return DeduceTemplateArguments(S, TemplateParams,
570                                    Param->template_arguments(),
571                                    SpecArg->template_arguments(), Info, Deduced,
572                                    /*NumberOfArgumentsMustMatch=*/false);
573   }
574 
575   // If the argument type is a class template specialization, we
576   // perform template argument deduction using its template
577   // arguments.
578   const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
579   if (!RecordArg) {
580     Info.FirstArg = TemplateArgument(QualType(Param, 0));
581     Info.SecondArg = TemplateArgument(Arg);
582     return Sema::TDK_NonDeducedMismatch;
583   }
584 
585   ClassTemplateSpecializationDecl *SpecArg
586     = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
587   if (!SpecArg) {
588     Info.FirstArg = TemplateArgument(QualType(Param, 0));
589     Info.SecondArg = TemplateArgument(Arg);
590     return Sema::TDK_NonDeducedMismatch;
591   }
592 
593   // Perform template argument deduction for the template name.
594   if (Sema::TemplateDeductionResult Result
595         = DeduceTemplateArguments(S,
596                                   TemplateParams,
597                                   Param->getTemplateName(),
598                                TemplateName(SpecArg->getSpecializedTemplate()),
599                                   Info, Deduced))
600     return Result;
601 
602   // Perform template argument deduction for the template arguments.
603   return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
604                                  SpecArg->getTemplateArgs().asArray(), Info,
605                                  Deduced, /*NumberOfArgumentsMustMatch=*/true);
606 }
607 
608 /// Determines whether the given type is an opaque type that
609 /// might be more qualified when instantiated.
610 static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
611   switch (T->getTypeClass()) {
612   case Type::TypeOfExpr:
613   case Type::TypeOf:
614   case Type::DependentName:
615   case Type::Decltype:
616   case Type::UnresolvedUsing:
617   case Type::TemplateTypeParm:
618     return true;
619 
620   case Type::ConstantArray:
621   case Type::IncompleteArray:
622   case Type::VariableArray:
623   case Type::DependentSizedArray:
624     return IsPossiblyOpaquelyQualifiedType(
625                                       cast<ArrayType>(T)->getElementType());
626 
627   default:
628     return false;
629   }
630 }
631 
632 /// Helper function to build a TemplateParameter when we don't
633 /// know its type statically.
634 static TemplateParameter makeTemplateParameter(Decl *D) {
635   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
636     return TemplateParameter(TTP);
637   if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
638     return TemplateParameter(NTTP);
639 
640   return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
641 }
642 
643 /// If \p Param is an expanded parameter pack, get the number of expansions.
644 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
645   if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
646     if (NTTP->isExpandedParameterPack())
647       return NTTP->getNumExpansionTypes();
648 
649   if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param))
650     if (TTP->isExpandedParameterPack())
651       return TTP->getNumExpansionTemplateParameters();
652 
653   return None;
654 }
655 
656 /// A pack that we're currently deducing.
657 struct clang::DeducedPack {
658   // The index of the pack.
659   unsigned Index;
660 
661   // The old value of the pack before we started deducing it.
662   DeducedTemplateArgument Saved;
663 
664   // A deferred value of this pack from an inner deduction, that couldn't be
665   // deduced because this deduction hadn't happened yet.
666   DeducedTemplateArgument DeferredDeduction;
667 
668   // The new value of the pack.
669   SmallVector<DeducedTemplateArgument, 4> New;
670 
671   // The outer deduction for this pack, if any.
672   DeducedPack *Outer = nullptr;
673 
674   DeducedPack(unsigned Index) : Index(Index) {}
675 };
676 
677 namespace {
678 
679 /// A scope in which we're performing pack deduction.
680 class PackDeductionScope {
681 public:
682   /// Prepare to deduce the packs named within Pattern.
683   PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
684                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
685                      TemplateDeductionInfo &Info, TemplateArgument Pattern)
686       : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
687     unsigned NumNamedPacks = addPacks(Pattern);
688     finishConstruction(NumNamedPacks);
689   }
690 
691   /// Prepare to directly deduce arguments of the parameter with index \p Index.
692   PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
693                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
694                      TemplateDeductionInfo &Info, unsigned Index)
695       : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
696     addPack(Index);
697     finishConstruction(1);
698   }
699 
700 private:
701   void addPack(unsigned Index) {
702     // Save the deduced template argument for the parameter pack expanded
703     // by this pack expansion, then clear out the deduction.
704     DeducedPack Pack(Index);
705     Pack.Saved = Deduced[Index];
706     Deduced[Index] = TemplateArgument();
707 
708     // FIXME: What if we encounter multiple packs with different numbers of
709     // pre-expanded expansions? (This should already have been diagnosed
710     // during substitution.)
711     if (Optional<unsigned> ExpandedPackExpansions =
712             getExpandedPackSize(TemplateParams->getParam(Index)))
713       FixedNumExpansions = ExpandedPackExpansions;
714 
715     Packs.push_back(Pack);
716   }
717 
718   unsigned addPacks(TemplateArgument Pattern) {
719     // Compute the set of template parameter indices that correspond to
720     // parameter packs expanded by the pack expansion.
721     llvm::SmallBitVector SawIndices(TemplateParams->size());
722 
723     auto AddPack = [&](unsigned Index) {
724       if (SawIndices[Index])
725         return;
726       SawIndices[Index] = true;
727       addPack(Index);
728     };
729 
730     // First look for unexpanded packs in the pattern.
731     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
732     S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
733     for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
734       unsigned Depth, Index;
735       std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
736       if (Depth == Info.getDeducedDepth())
737         AddPack(Index);
738     }
739     assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
740 
741     unsigned NumNamedPacks = Packs.size();
742 
743     // We can also have deduced template parameters that do not actually
744     // appear in the pattern, but can be deduced by it (the type of a non-type
745     // template parameter pack, in particular). These won't have prevented us
746     // from partially expanding the pack.
747     llvm::SmallBitVector Used(TemplateParams->size());
748     MarkUsedTemplateParameters(S.Context, Pattern, /*OnlyDeduced*/true,
749                                Info.getDeducedDepth(), Used);
750     for (int Index = Used.find_first(); Index != -1;
751          Index = Used.find_next(Index))
752       if (TemplateParams->getParam(Index)->isParameterPack())
753         AddPack(Index);
754 
755     return NumNamedPacks;
756   }
757 
758   void finishConstruction(unsigned NumNamedPacks) {
759     // Dig out the partially-substituted pack, if there is one.
760     const TemplateArgument *PartialPackArgs = nullptr;
761     unsigned NumPartialPackArgs = 0;
762     std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
763     if (auto *Scope = S.CurrentInstantiationScope)
764       if (auto *Partial = Scope->getPartiallySubstitutedPack(
765               &PartialPackArgs, &NumPartialPackArgs))
766         PartialPackDepthIndex = getDepthAndIndex(Partial);
767 
768     // This pack expansion will have been partially or fully expanded if
769     // it only names explicitly-specified parameter packs (including the
770     // partially-substituted one, if any).
771     bool IsExpanded = true;
772     for (unsigned I = 0; I != NumNamedPacks; ++I) {
773       if (Packs[I].Index >= Info.getNumExplicitArgs()) {
774         IsExpanded = false;
775         IsPartiallyExpanded = false;
776         break;
777       }
778       if (PartialPackDepthIndex ==
779             std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
780         IsPartiallyExpanded = true;
781       }
782     }
783 
784     // Skip over the pack elements that were expanded into separate arguments.
785     // If we partially expanded, this is the number of partial arguments.
786     if (IsPartiallyExpanded)
787       PackElements += NumPartialPackArgs;
788     else if (IsExpanded)
789       PackElements += *FixedNumExpansions;
790 
791     for (auto &Pack : Packs) {
792       if (Info.PendingDeducedPacks.size() > Pack.Index)
793         Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
794       else
795         Info.PendingDeducedPacks.resize(Pack.Index + 1);
796       Info.PendingDeducedPacks[Pack.Index] = &Pack;
797 
798       if (PartialPackDepthIndex ==
799             std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
800         Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
801         // We pre-populate the deduced value of the partially-substituted
802         // pack with the specified value. This is not entirely correct: the
803         // value is supposed to have been substituted, not deduced, but the
804         // cases where this is observable require an exact type match anyway.
805         //
806         // FIXME: If we could represent a "depth i, index j, pack elem k"
807         // parameter, we could substitute the partially-substituted pack
808         // everywhere and avoid this.
809         if (!IsPartiallyExpanded)
810           Deduced[Pack.Index] = Pack.New[PackElements];
811       }
812     }
813   }
814 
815 public:
816   ~PackDeductionScope() {
817     for (auto &Pack : Packs)
818       Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
819   }
820 
821   /// Determine whether this pack has already been partially expanded into a
822   /// sequence of (prior) function parameters / template arguments.
823   bool isPartiallyExpanded() { return IsPartiallyExpanded; }
824 
825   /// Determine whether this pack expansion scope has a known, fixed arity.
826   /// This happens if it involves a pack from an outer template that has
827   /// (notionally) already been expanded.
828   bool hasFixedArity() { return FixedNumExpansions.hasValue(); }
829 
830   /// Determine whether the next element of the argument is still part of this
831   /// pack. This is the case unless the pack is already expanded to a fixed
832   /// length.
833   bool hasNextElement() {
834     return !FixedNumExpansions || *FixedNumExpansions > PackElements;
835   }
836 
837   /// Move to deducing the next element in each pack that is being deduced.
838   void nextPackElement() {
839     // Capture the deduced template arguments for each parameter pack expanded
840     // by this pack expansion, add them to the list of arguments we've deduced
841     // for that pack, then clear out the deduced argument.
842     for (auto &Pack : Packs) {
843       DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
844       if (!Pack.New.empty() || !DeducedArg.isNull()) {
845         while (Pack.New.size() < PackElements)
846           Pack.New.push_back(DeducedTemplateArgument());
847         if (Pack.New.size() == PackElements)
848           Pack.New.push_back(DeducedArg);
849         else
850           Pack.New[PackElements] = DeducedArg;
851         DeducedArg = Pack.New.size() > PackElements + 1
852                          ? Pack.New[PackElements + 1]
853                          : DeducedTemplateArgument();
854       }
855     }
856     ++PackElements;
857   }
858 
859   /// Finish template argument deduction for a set of argument packs,
860   /// producing the argument packs and checking for consistency with prior
861   /// deductions.
862   Sema::TemplateDeductionResult
863   finish(bool TreatNoDeductionsAsNonDeduced = true) {
864     // Build argument packs for each of the parameter packs expanded by this
865     // pack expansion.
866     for (auto &Pack : Packs) {
867       // Put back the old value for this pack.
868       Deduced[Pack.Index] = Pack.Saved;
869 
870       // If we are deducing the size of this pack even if we didn't deduce any
871       // values for it, then make sure we build a pack of the right size.
872       // FIXME: Should we always deduce the size, even if the pack appears in
873       // a non-deduced context?
874       if (!TreatNoDeductionsAsNonDeduced)
875         Pack.New.resize(PackElements);
876 
877       // Build or find a new value for this pack.
878       DeducedTemplateArgument NewPack;
879       if (PackElements && Pack.New.empty()) {
880         if (Pack.DeferredDeduction.isNull()) {
881           // We were not able to deduce anything for this parameter pack
882           // (because it only appeared in non-deduced contexts), so just
883           // restore the saved argument pack.
884           continue;
885         }
886 
887         NewPack = Pack.DeferredDeduction;
888         Pack.DeferredDeduction = TemplateArgument();
889       } else if (Pack.New.empty()) {
890         // If we deduced an empty argument pack, create it now.
891         NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
892       } else {
893         TemplateArgument *ArgumentPack =
894             new (S.Context) TemplateArgument[Pack.New.size()];
895         std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
896         NewPack = DeducedTemplateArgument(
897             TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
898             // FIXME: This is wrong, it's possible that some pack elements are
899             // deduced from an array bound and others are not:
900             //   template<typename ...T, T ...V> void g(const T (&...p)[V]);
901             //   g({1, 2, 3}, {{}, {}});
902             // ... should deduce T = {int, size_t (from array bound)}.
903             Pack.New[0].wasDeducedFromArrayBound());
904       }
905 
906       // Pick where we're going to put the merged pack.
907       DeducedTemplateArgument *Loc;
908       if (Pack.Outer) {
909         if (Pack.Outer->DeferredDeduction.isNull()) {
910           // Defer checking this pack until we have a complete pack to compare
911           // it against.
912           Pack.Outer->DeferredDeduction = NewPack;
913           continue;
914         }
915         Loc = &Pack.Outer->DeferredDeduction;
916       } else {
917         Loc = &Deduced[Pack.Index];
918       }
919 
920       // Check the new pack matches any previous value.
921       DeducedTemplateArgument OldPack = *Loc;
922       DeducedTemplateArgument Result =
923           checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
924 
925       // If we deferred a deduction of this pack, check that one now too.
926       if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
927         OldPack = Result;
928         NewPack = Pack.DeferredDeduction;
929         Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
930       }
931 
932       NamedDecl *Param = TemplateParams->getParam(Pack.Index);
933       if (Result.isNull()) {
934         Info.Param = makeTemplateParameter(Param);
935         Info.FirstArg = OldPack;
936         Info.SecondArg = NewPack;
937         return Sema::TDK_Inconsistent;
938       }
939 
940       // If we have a pre-expanded pack and we didn't deduce enough elements
941       // for it, fail deduction.
942       if (Optional<unsigned> Expansions = getExpandedPackSize(Param)) {
943         if (*Expansions != PackElements) {
944           Info.Param = makeTemplateParameter(Param);
945           Info.FirstArg = Result;
946           return Sema::TDK_IncompletePack;
947         }
948       }
949 
950       *Loc = Result;
951     }
952 
953     return Sema::TDK_Success;
954   }
955 
956 private:
957   Sema &S;
958   TemplateParameterList *TemplateParams;
959   SmallVectorImpl<DeducedTemplateArgument> &Deduced;
960   TemplateDeductionInfo &Info;
961   unsigned PackElements = 0;
962   bool IsPartiallyExpanded = false;
963   /// The number of expansions, if we have a fully-expanded pack in this scope.
964   Optional<unsigned> FixedNumExpansions;
965 
966   SmallVector<DeducedPack, 2> Packs;
967 };
968 
969 } // namespace
970 
971 /// Deduce the template arguments by comparing the list of parameter
972 /// types to the list of argument types, as in the parameter-type-lists of
973 /// function types (C++ [temp.deduct.type]p10).
974 ///
975 /// \param S The semantic analysis object within which we are deducing
976 ///
977 /// \param TemplateParams The template parameters that we are deducing
978 ///
979 /// \param Params The list of parameter types
980 ///
981 /// \param NumParams The number of types in \c Params
982 ///
983 /// \param Args The list of argument types
984 ///
985 /// \param NumArgs The number of types in \c Args
986 ///
987 /// \param Info information about the template argument deduction itself
988 ///
989 /// \param Deduced the deduced template arguments
990 ///
991 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
992 /// how template argument deduction is performed.
993 ///
994 /// \param PartialOrdering If true, we are performing template argument
995 /// deduction for during partial ordering for a call
996 /// (C++0x [temp.deduct.partial]).
997 ///
998 /// \returns the result of template argument deduction so far. Note that a
999 /// "success" result means that template argument deduction has not yet failed,
1000 /// but it may still fail, later, for other reasons.
1001 static Sema::TemplateDeductionResult
1002 DeduceTemplateArguments(Sema &S,
1003                         TemplateParameterList *TemplateParams,
1004                         const QualType *Params, unsigned NumParams,
1005                         const QualType *Args, unsigned NumArgs,
1006                         TemplateDeductionInfo &Info,
1007                         SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1008                         unsigned TDF,
1009                         bool PartialOrdering = false) {
1010   // C++0x [temp.deduct.type]p10:
1011   //   Similarly, if P has a form that contains (T), then each parameter type
1012   //   Pi of the respective parameter-type- list of P is compared with the
1013   //   corresponding parameter type Ai of the corresponding parameter-type-list
1014   //   of A. [...]
1015   unsigned ArgIdx = 0, ParamIdx = 0;
1016   for (; ParamIdx != NumParams; ++ParamIdx) {
1017     // Check argument types.
1018     const PackExpansionType *Expansion
1019                                 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1020     if (!Expansion) {
1021       // Simple case: compare the parameter and argument types at this point.
1022 
1023       // Make sure we have an argument.
1024       if (ArgIdx >= NumArgs)
1025         return Sema::TDK_MiscellaneousDeductionFailure;
1026 
1027       if (isa<PackExpansionType>(Args[ArgIdx])) {
1028         // C++0x [temp.deduct.type]p22:
1029         //   If the original function parameter associated with A is a function
1030         //   parameter pack and the function parameter associated with P is not
1031         //   a function parameter pack, then template argument deduction fails.
1032         return Sema::TDK_MiscellaneousDeductionFailure;
1033       }
1034 
1035       if (Sema::TemplateDeductionResult Result
1036             = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1037                                                  Params[ParamIdx], Args[ArgIdx],
1038                                                  Info, Deduced, TDF,
1039                                                  PartialOrdering))
1040         return Result;
1041 
1042       ++ArgIdx;
1043       continue;
1044     }
1045 
1046     // C++0x [temp.deduct.type]p10:
1047     //   If the parameter-declaration corresponding to Pi is a function
1048     //   parameter pack, then the type of its declarator- id is compared with
1049     //   each remaining parameter type in the parameter-type-list of A. Each
1050     //   comparison deduces template arguments for subsequent positions in the
1051     //   template parameter packs expanded by the function parameter pack.
1052 
1053     QualType Pattern = Expansion->getPattern();
1054     PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
1055 
1056     // A pack scope with fixed arity is not really a pack any more, so is not
1057     // a non-deduced context.
1058     if (ParamIdx + 1 == NumParams || PackScope.hasFixedArity()) {
1059       for (; ArgIdx < NumArgs && PackScope.hasNextElement(); ++ArgIdx) {
1060         // Deduce template arguments from the pattern.
1061         if (Sema::TemplateDeductionResult Result
1062               = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
1063                                                    Args[ArgIdx], Info, Deduced,
1064                                                    TDF, PartialOrdering))
1065           return Result;
1066 
1067         PackScope.nextPackElement();
1068       }
1069     } else {
1070       // C++0x [temp.deduct.type]p5:
1071       //   The non-deduced contexts are:
1072       //     - A function parameter pack that does not occur at the end of the
1073       //       parameter-declaration-clause.
1074       //
1075       // FIXME: There is no wording to say what we should do in this case. We
1076       // choose to resolve this by applying the same rule that is applied for a
1077       // function call: that is, deduce all contained packs to their
1078       // explicitly-specified values (or to <> if there is no such value).
1079       //
1080       // This is seemingly-arbitrarily different from the case of a template-id
1081       // with a non-trailing pack-expansion in its arguments, which renders the
1082       // entire template-argument-list a non-deduced context.
1083 
1084       // If the parameter type contains an explicitly-specified pack that we
1085       // could not expand, skip the number of parameters notionally created
1086       // by the expansion.
1087       Optional<unsigned> NumExpansions = Expansion->getNumExpansions();
1088       if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1089         for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs;
1090              ++I, ++ArgIdx)
1091           PackScope.nextPackElement();
1092       }
1093     }
1094 
1095     // Build argument packs for each of the parameter packs expanded by this
1096     // pack expansion.
1097     if (auto Result = PackScope.finish())
1098       return Result;
1099   }
1100 
1101   // Make sure we don't have any extra arguments.
1102   if (ArgIdx < NumArgs)
1103     return Sema::TDK_MiscellaneousDeductionFailure;
1104 
1105   return Sema::TDK_Success;
1106 }
1107 
1108 /// Determine whether the parameter has qualifiers that the argument
1109 /// lacks. Put another way, determine whether there is no way to add
1110 /// a deduced set of qualifiers to the ParamType that would result in
1111 /// its qualifiers matching those of the ArgType.
1112 static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
1113                                                   QualType ArgType) {
1114   Qualifiers ParamQs = ParamType.getQualifiers();
1115   Qualifiers ArgQs = ArgType.getQualifiers();
1116 
1117   if (ParamQs == ArgQs)
1118     return false;
1119 
1120   // Mismatched (but not missing) Objective-C GC attributes.
1121   if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1122       ParamQs.hasObjCGCAttr())
1123     return true;
1124 
1125   // Mismatched (but not missing) address spaces.
1126   if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1127       ParamQs.hasAddressSpace())
1128     return true;
1129 
1130   // Mismatched (but not missing) Objective-C lifetime qualifiers.
1131   if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1132       ParamQs.hasObjCLifetime())
1133     return true;
1134 
1135   // CVR qualifiers inconsistent or a superset.
1136   return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1137 }
1138 
1139 /// Compare types for equality with respect to possibly compatible
1140 /// function types (noreturn adjustment, implicit calling conventions). If any
1141 /// of parameter and argument is not a function, just perform type comparison.
1142 ///
1143 /// \param Param the template parameter type.
1144 ///
1145 /// \param Arg the argument type.
1146 bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
1147                                           CanQualType Arg) {
1148   const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
1149                      *ArgFunction   = Arg->getAs<FunctionType>();
1150 
1151   // Just compare if not functions.
1152   if (!ParamFunction || !ArgFunction)
1153     return Param == Arg;
1154 
1155   // Noreturn and noexcept adjustment.
1156   QualType AdjustedParam;
1157   if (IsFunctionConversion(Param, Arg, AdjustedParam))
1158     return Arg == Context.getCanonicalType(AdjustedParam);
1159 
1160   // FIXME: Compatible calling conventions.
1161 
1162   return Param == Arg;
1163 }
1164 
1165 /// Get the index of the first template parameter that was originally from the
1166 /// innermost template-parameter-list. This is 0 except when we concatenate
1167 /// the template parameter lists of a class template and a constructor template
1168 /// when forming an implicit deduction guide.
1169 static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
1170   auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1171   if (!Guide || !Guide->isImplicit())
1172     return 0;
1173   return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1174 }
1175 
1176 /// Determine whether a type denotes a forwarding reference.
1177 static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1178   // C++1z [temp.deduct.call]p3:
1179   //   A forwarding reference is an rvalue reference to a cv-unqualified
1180   //   template parameter that does not represent a template parameter of a
1181   //   class template.
1182   if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1183     if (ParamRef->getPointeeType().getQualifiers())
1184       return false;
1185     auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1186     return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1187   }
1188   return false;
1189 }
1190 
1191 /// Deduce the template arguments by comparing the parameter type and
1192 /// the argument type (C++ [temp.deduct.type]).
1193 ///
1194 /// \param S the semantic analysis object within which we are deducing
1195 ///
1196 /// \param TemplateParams the template parameters that we are deducing
1197 ///
1198 /// \param ParamIn the parameter type
1199 ///
1200 /// \param ArgIn the argument type
1201 ///
1202 /// \param Info information about the template argument deduction itself
1203 ///
1204 /// \param Deduced the deduced template arguments
1205 ///
1206 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1207 /// how template argument deduction is performed.
1208 ///
1209 /// \param PartialOrdering Whether we're performing template argument deduction
1210 /// in the context of partial ordering (C++0x [temp.deduct.partial]).
1211 ///
1212 /// \returns the result of template argument deduction so far. Note that a
1213 /// "success" result means that template argument deduction has not yet failed,
1214 /// but it may still fail, later, for other reasons.
1215 static Sema::TemplateDeductionResult
1216 DeduceTemplateArgumentsByTypeMatch(Sema &S,
1217                                    TemplateParameterList *TemplateParams,
1218                                    QualType ParamIn, QualType ArgIn,
1219                                    TemplateDeductionInfo &Info,
1220                             SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1221                                    unsigned TDF,
1222                                    bool PartialOrdering,
1223                                    bool DeducedFromArrayBound) {
1224   // We only want to look at the canonical types, since typedefs and
1225   // sugar are not part of template argument deduction.
1226   QualType Param = S.Context.getCanonicalType(ParamIn);
1227   QualType Arg = S.Context.getCanonicalType(ArgIn);
1228 
1229   // If the argument type is a pack expansion, look at its pattern.
1230   // This isn't explicitly called out
1231   if (const PackExpansionType *ArgExpansion
1232                                             = dyn_cast<PackExpansionType>(Arg))
1233     Arg = ArgExpansion->getPattern();
1234 
1235   if (PartialOrdering) {
1236     // C++11 [temp.deduct.partial]p5:
1237     //   Before the partial ordering is done, certain transformations are
1238     //   performed on the types used for partial ordering:
1239     //     - If P is a reference type, P is replaced by the type referred to.
1240     const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1241     if (ParamRef)
1242       Param = ParamRef->getPointeeType();
1243 
1244     //     - If A is a reference type, A is replaced by the type referred to.
1245     const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1246     if (ArgRef)
1247       Arg = ArgRef->getPointeeType();
1248 
1249     if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1250       // C++11 [temp.deduct.partial]p9:
1251       //   If, for a given type, deduction succeeds in both directions (i.e.,
1252       //   the types are identical after the transformations above) and both
1253       //   P and A were reference types [...]:
1254       //     - if [one type] was an lvalue reference and [the other type] was
1255       //       not, [the other type] is not considered to be at least as
1256       //       specialized as [the first type]
1257       //     - if [one type] is more cv-qualified than [the other type],
1258       //       [the other type] is not considered to be at least as specialized
1259       //       as [the first type]
1260       // Objective-C ARC adds:
1261       //     - [one type] has non-trivial lifetime, [the other type] has
1262       //       __unsafe_unretained lifetime, and the types are otherwise
1263       //       identical
1264       //
1265       // A is "considered to be at least as specialized" as P iff deduction
1266       // succeeds, so we model this as a deduction failure. Note that
1267       // [the first type] is P and [the other type] is A here; the standard
1268       // gets this backwards.
1269       Qualifiers ParamQuals = Param.getQualifiers();
1270       Qualifiers ArgQuals = Arg.getQualifiers();
1271       if ((ParamRef->isLValueReferenceType() &&
1272            !ArgRef->isLValueReferenceType()) ||
1273           ParamQuals.isStrictSupersetOf(ArgQuals) ||
1274           (ParamQuals.hasNonTrivialObjCLifetime() &&
1275            ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1276            ParamQuals.withoutObjCLifetime() ==
1277                ArgQuals.withoutObjCLifetime())) {
1278         Info.FirstArg = TemplateArgument(ParamIn);
1279         Info.SecondArg = TemplateArgument(ArgIn);
1280         return Sema::TDK_NonDeducedMismatch;
1281       }
1282     }
1283 
1284     // C++11 [temp.deduct.partial]p7:
1285     //   Remove any top-level cv-qualifiers:
1286     //     - If P is a cv-qualified type, P is replaced by the cv-unqualified
1287     //       version of P.
1288     Param = Param.getUnqualifiedType();
1289     //     - If A is a cv-qualified type, A is replaced by the cv-unqualified
1290     //       version of A.
1291     Arg = Arg.getUnqualifiedType();
1292   } else {
1293     // C++0x [temp.deduct.call]p4 bullet 1:
1294     //   - If the original P is a reference type, the deduced A (i.e., the type
1295     //     referred to by the reference) can be more cv-qualified than the
1296     //     transformed A.
1297     if (TDF & TDF_ParamWithReferenceType) {
1298       Qualifiers Quals;
1299       QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1300       Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
1301                              Arg.getCVRQualifiers());
1302       Param = S.Context.getQualifiedType(UnqualParam, Quals);
1303     }
1304 
1305     if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1306       // C++0x [temp.deduct.type]p10:
1307       //   If P and A are function types that originated from deduction when
1308       //   taking the address of a function template (14.8.2.2) or when deducing
1309       //   template arguments from a function declaration (14.8.2.6) and Pi and
1310       //   Ai are parameters of the top-level parameter-type-list of P and A,
1311       //   respectively, Pi is adjusted if it is a forwarding reference and Ai
1312       //   is an lvalue reference, in
1313       //   which case the type of Pi is changed to be the template parameter
1314       //   type (i.e., T&& is changed to simply T). [ Note: As a result, when
1315       //   Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1316       //   deduced as X&. - end note ]
1317       TDF &= ~TDF_TopLevelParameterTypeList;
1318       if (isForwardingReference(Param, 0) && Arg->isLValueReferenceType())
1319         Param = Param->getPointeeType();
1320     }
1321   }
1322 
1323   // C++ [temp.deduct.type]p9:
1324   //   A template type argument T, a template template argument TT or a
1325   //   template non-type argument i can be deduced if P and A have one of
1326   //   the following forms:
1327   //
1328   //     T
1329   //     cv-list T
1330   if (const TemplateTypeParmType *TemplateTypeParm
1331         = Param->getAs<TemplateTypeParmType>()) {
1332     // Just skip any attempts to deduce from a placeholder type or a parameter
1333     // at a different depth.
1334     if (Arg->isPlaceholderType() ||
1335         Info.getDeducedDepth() != TemplateTypeParm->getDepth())
1336       return Sema::TDK_Success;
1337 
1338     unsigned Index = TemplateTypeParm->getIndex();
1339     bool RecanonicalizeArg = false;
1340 
1341     // If the argument type is an array type, move the qualifiers up to the
1342     // top level, so they can be matched with the qualifiers on the parameter.
1343     if (isa<ArrayType>(Arg)) {
1344       Qualifiers Quals;
1345       Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
1346       if (Quals) {
1347         Arg = S.Context.getQualifiedType(Arg, Quals);
1348         RecanonicalizeArg = true;
1349       }
1350     }
1351 
1352     // The argument type can not be less qualified than the parameter
1353     // type.
1354     if (!(TDF & TDF_IgnoreQualifiers) &&
1355         hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
1356       Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1357       Info.FirstArg = TemplateArgument(Param);
1358       Info.SecondArg = TemplateArgument(Arg);
1359       return Sema::TDK_Underqualified;
1360     }
1361 
1362     // Do not match a function type with a cv-qualified type.
1363     // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1364     if (Arg->isFunctionType() && Param.hasQualifiers()) {
1365       return Sema::TDK_NonDeducedMismatch;
1366     }
1367 
1368     assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1369            "saw template type parameter with wrong depth");
1370     assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
1371     QualType DeducedType = Arg;
1372 
1373     // Remove any qualifiers on the parameter from the deduced type.
1374     // We checked the qualifiers for consistency above.
1375     Qualifiers DeducedQs = DeducedType.getQualifiers();
1376     Qualifiers ParamQs = Param.getQualifiers();
1377     DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1378     if (ParamQs.hasObjCGCAttr())
1379       DeducedQs.removeObjCGCAttr();
1380     if (ParamQs.hasAddressSpace())
1381       DeducedQs.removeAddressSpace();
1382     if (ParamQs.hasObjCLifetime())
1383       DeducedQs.removeObjCLifetime();
1384 
1385     // Objective-C ARC:
1386     //   If template deduction would produce a lifetime qualifier on a type
1387     //   that is not a lifetime type, template argument deduction fails.
1388     if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1389         !DeducedType->isDependentType()) {
1390       Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1391       Info.FirstArg = TemplateArgument(Param);
1392       Info.SecondArg = TemplateArgument(Arg);
1393       return Sema::TDK_Underqualified;
1394     }
1395 
1396     // Objective-C ARC:
1397     //   If template deduction would produce an argument type with lifetime type
1398     //   but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1399     if (S.getLangOpts().ObjCAutoRefCount &&
1400         DeducedType->isObjCLifetimeType() &&
1401         !DeducedQs.hasObjCLifetime())
1402       DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1403 
1404     DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1405                                              DeducedQs);
1406 
1407     if (RecanonicalizeArg)
1408       DeducedType = S.Context.getCanonicalType(DeducedType);
1409 
1410     DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1411     DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
1412                                                                  Deduced[Index],
1413                                                                    NewDeduced);
1414     if (Result.isNull()) {
1415       Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1416       Info.FirstArg = Deduced[Index];
1417       Info.SecondArg = NewDeduced;
1418       return Sema::TDK_Inconsistent;
1419     }
1420 
1421     Deduced[Index] = Result;
1422     return Sema::TDK_Success;
1423   }
1424 
1425   // Set up the template argument deduction information for a failure.
1426   Info.FirstArg = TemplateArgument(ParamIn);
1427   Info.SecondArg = TemplateArgument(ArgIn);
1428 
1429   // If the parameter is an already-substituted template parameter
1430   // pack, do nothing: we don't know which of its arguments to look
1431   // at, so we have to wait until all of the parameter packs in this
1432   // expansion have arguments.
1433   if (isa<SubstTemplateTypeParmPackType>(Param))
1434     return Sema::TDK_Success;
1435 
1436   // Check the cv-qualifiers on the parameter and argument types.
1437   CanQualType CanParam = S.Context.getCanonicalType(Param);
1438   CanQualType CanArg = S.Context.getCanonicalType(Arg);
1439   if (!(TDF & TDF_IgnoreQualifiers)) {
1440     if (TDF & TDF_ParamWithReferenceType) {
1441       if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
1442         return Sema::TDK_NonDeducedMismatch;
1443     } else if (TDF & TDF_ArgWithReferenceType) {
1444       // C++ [temp.deduct.conv]p4:
1445       //   If the original A is a reference type, A can be more cv-qualified
1446       //   than the deduced A
1447       if (!Arg.getQualifiers().compatiblyIncludes(Param.getQualifiers()))
1448         return Sema::TDK_NonDeducedMismatch;
1449 
1450       // Strip out all extra qualifiers from the argument to figure out the
1451       // type we're converting to, prior to the qualification conversion.
1452       Qualifiers Quals;
1453       Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
1454       Arg = S.Context.getQualifiedType(Arg, Param.getQualifiers());
1455     } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
1456       if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
1457         return Sema::TDK_NonDeducedMismatch;
1458     }
1459 
1460     // If the parameter type is not dependent, there is nothing to deduce.
1461     if (!Param->isDependentType()) {
1462       if (!(TDF & TDF_SkipNonDependent)) {
1463         bool NonDeduced =
1464             (TDF & TDF_AllowCompatibleFunctionType)
1465                 ? !S.isSameOrCompatibleFunctionType(CanParam, CanArg)
1466                 : Param != Arg;
1467         if (NonDeduced) {
1468           return Sema::TDK_NonDeducedMismatch;
1469         }
1470       }
1471       return Sema::TDK_Success;
1472     }
1473   } else if (!Param->isDependentType()) {
1474     CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1475                 ArgUnqualType = CanArg.getUnqualifiedType();
1476     bool Success =
1477         (TDF & TDF_AllowCompatibleFunctionType)
1478             ? S.isSameOrCompatibleFunctionType(ParamUnqualType, ArgUnqualType)
1479             : ParamUnqualType == ArgUnqualType;
1480     if (Success)
1481       return Sema::TDK_Success;
1482   }
1483 
1484   switch (Param->getTypeClass()) {
1485     // Non-canonical types cannot appear here.
1486 #define NON_CANONICAL_TYPE(Class, Base) \
1487   case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1488 #define TYPE(Class, Base)
1489 #include "clang/AST/TypeNodes.inc"
1490 
1491     case Type::TemplateTypeParm:
1492     case Type::SubstTemplateTypeParmPack:
1493       llvm_unreachable("Type nodes handled above");
1494 
1495     // These types cannot be dependent, so simply check whether the types are
1496     // the same.
1497     case Type::Builtin:
1498     case Type::VariableArray:
1499     case Type::Vector:
1500     case Type::FunctionNoProto:
1501     case Type::Record:
1502     case Type::Enum:
1503     case Type::ObjCObject:
1504     case Type::ObjCInterface:
1505     case Type::ObjCObjectPointer:
1506       if (TDF & TDF_SkipNonDependent)
1507         return Sema::TDK_Success;
1508 
1509       if (TDF & TDF_IgnoreQualifiers) {
1510         Param = Param.getUnqualifiedType();
1511         Arg = Arg.getUnqualifiedType();
1512       }
1513 
1514       return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1515 
1516     //     _Complex T   [placeholder extension]
1517     case Type::Complex:
1518       if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
1519         return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1520                                     cast<ComplexType>(Param)->getElementType(),
1521                                     ComplexArg->getElementType(),
1522                                     Info, Deduced, TDF);
1523 
1524       return Sema::TDK_NonDeducedMismatch;
1525 
1526     //     _Atomic T   [extension]
1527     case Type::Atomic:
1528       if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
1529         return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1530                                        cast<AtomicType>(Param)->getValueType(),
1531                                        AtomicArg->getValueType(),
1532                                        Info, Deduced, TDF);
1533 
1534       return Sema::TDK_NonDeducedMismatch;
1535 
1536     //     T *
1537     case Type::Pointer: {
1538       QualType PointeeType;
1539       if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1540         PointeeType = PointerArg->getPointeeType();
1541       } else if (const ObjCObjectPointerType *PointerArg
1542                    = Arg->getAs<ObjCObjectPointerType>()) {
1543         PointeeType = PointerArg->getPointeeType();
1544       } else {
1545         return Sema::TDK_NonDeducedMismatch;
1546       }
1547 
1548       unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
1549       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1550                                      cast<PointerType>(Param)->getPointeeType(),
1551                                      PointeeType,
1552                                      Info, Deduced, SubTDF);
1553     }
1554 
1555     //     T &
1556     case Type::LValueReference: {
1557       const LValueReferenceType *ReferenceArg =
1558           Arg->getAs<LValueReferenceType>();
1559       if (!ReferenceArg)
1560         return Sema::TDK_NonDeducedMismatch;
1561 
1562       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1563                            cast<LValueReferenceType>(Param)->getPointeeType(),
1564                            ReferenceArg->getPointeeType(), Info, Deduced, 0);
1565     }
1566 
1567     //     T && [C++0x]
1568     case Type::RValueReference: {
1569       const RValueReferenceType *ReferenceArg =
1570           Arg->getAs<RValueReferenceType>();
1571       if (!ReferenceArg)
1572         return Sema::TDK_NonDeducedMismatch;
1573 
1574       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1575                              cast<RValueReferenceType>(Param)->getPointeeType(),
1576                              ReferenceArg->getPointeeType(),
1577                              Info, Deduced, 0);
1578     }
1579 
1580     //     T [] (implied, but not stated explicitly)
1581     case Type::IncompleteArray: {
1582       const IncompleteArrayType *IncompleteArrayArg =
1583         S.Context.getAsIncompleteArrayType(Arg);
1584       if (!IncompleteArrayArg)
1585         return Sema::TDK_NonDeducedMismatch;
1586 
1587       unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1588       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1589                     S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1590                     IncompleteArrayArg->getElementType(),
1591                     Info, Deduced, SubTDF);
1592     }
1593 
1594     //     T [integer-constant]
1595     case Type::ConstantArray: {
1596       const ConstantArrayType *ConstantArrayArg =
1597         S.Context.getAsConstantArrayType(Arg);
1598       if (!ConstantArrayArg)
1599         return Sema::TDK_NonDeducedMismatch;
1600 
1601       const ConstantArrayType *ConstantArrayParm =
1602         S.Context.getAsConstantArrayType(Param);
1603       if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
1604         return Sema::TDK_NonDeducedMismatch;
1605 
1606       unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1607       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1608                                            ConstantArrayParm->getElementType(),
1609                                            ConstantArrayArg->getElementType(),
1610                                            Info, Deduced, SubTDF);
1611     }
1612 
1613     //     type [i]
1614     case Type::DependentSizedArray: {
1615       const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
1616       if (!ArrayArg)
1617         return Sema::TDK_NonDeducedMismatch;
1618 
1619       unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1620 
1621       // Check the element type of the arrays
1622       const DependentSizedArrayType *DependentArrayParm
1623         = S.Context.getAsDependentSizedArrayType(Param);
1624       if (Sema::TemplateDeductionResult Result
1625             = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1626                                           DependentArrayParm->getElementType(),
1627                                           ArrayArg->getElementType(),
1628                                           Info, Deduced, SubTDF))
1629         return Result;
1630 
1631       // Determine the array bound is something we can deduce.
1632       NonTypeTemplateParmDecl *NTTP
1633         = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
1634       if (!NTTP)
1635         return Sema::TDK_Success;
1636 
1637       // We can perform template argument deduction for the given non-type
1638       // template parameter.
1639       assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1640              "saw non-type template parameter with wrong depth");
1641       if (const ConstantArrayType *ConstantArrayArg
1642             = dyn_cast<ConstantArrayType>(ArrayArg)) {
1643         llvm::APSInt Size(ConstantArrayArg->getSize());
1644         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
1645                                              S.Context.getSizeType(),
1646                                              /*ArrayBound=*/true,
1647                                              Info, Deduced);
1648       }
1649       if (const DependentSizedArrayType *DependentArrayArg
1650             = dyn_cast<DependentSizedArrayType>(ArrayArg))
1651         if (DependentArrayArg->getSizeExpr())
1652           return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1653                                                DependentArrayArg->getSizeExpr(),
1654                                                Info, Deduced);
1655 
1656       // Incomplete type does not match a dependently-sized array type
1657       return Sema::TDK_NonDeducedMismatch;
1658     }
1659 
1660     //     type(*)(T)
1661     //     T(*)()
1662     //     T(*)(T)
1663     case Type::FunctionProto: {
1664       unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
1665       const FunctionProtoType *FunctionProtoArg =
1666         dyn_cast<FunctionProtoType>(Arg);
1667       if (!FunctionProtoArg)
1668         return Sema::TDK_NonDeducedMismatch;
1669 
1670       const FunctionProtoType *FunctionProtoParam =
1671         cast<FunctionProtoType>(Param);
1672 
1673       if (FunctionProtoParam->getMethodQuals()
1674             != FunctionProtoArg->getMethodQuals() ||
1675           FunctionProtoParam->getRefQualifier()
1676             != FunctionProtoArg->getRefQualifier() ||
1677           FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
1678         return Sema::TDK_NonDeducedMismatch;
1679 
1680       // Check return types.
1681       if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1682               S, TemplateParams, FunctionProtoParam->getReturnType(),
1683               FunctionProtoArg->getReturnType(), Info, Deduced, 0))
1684         return Result;
1685 
1686       // Check parameter types.
1687       if (auto Result = DeduceTemplateArguments(
1688               S, TemplateParams, FunctionProtoParam->param_type_begin(),
1689               FunctionProtoParam->getNumParams(),
1690               FunctionProtoArg->param_type_begin(),
1691               FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF))
1692         return Result;
1693 
1694       if (TDF & TDF_AllowCompatibleFunctionType)
1695         return Sema::TDK_Success;
1696 
1697       // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1698       // deducing through the noexcept-specifier if it's part of the canonical
1699       // type. libstdc++ relies on this.
1700       Expr *NoexceptExpr = FunctionProtoParam->getNoexceptExpr();
1701       if (NonTypeTemplateParmDecl *NTTP =
1702           NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
1703                        : nullptr) {
1704         assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1705                "saw non-type template parameter with wrong depth");
1706 
1707         llvm::APSInt Noexcept(1);
1708         switch (FunctionProtoArg->canThrow()) {
1709         case CT_Cannot:
1710           Noexcept = 1;
1711           LLVM_FALLTHROUGH;
1712 
1713         case CT_Can:
1714           // We give E in noexcept(E) the "deduced from array bound" treatment.
1715           // FIXME: Should we?
1716           return DeduceNonTypeTemplateArgument(
1717               S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
1718               /*ArrayBound*/true, Info, Deduced);
1719 
1720         case CT_Dependent:
1721           if (Expr *ArgNoexceptExpr = FunctionProtoArg->getNoexceptExpr())
1722             return DeduceNonTypeTemplateArgument(
1723                 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
1724           // Can't deduce anything from throw(T...).
1725           break;
1726         }
1727       }
1728       // FIXME: Detect non-deduced exception specification mismatches?
1729       //
1730       // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
1731       // top-level differences in noexcept-specifications.
1732 
1733       return Sema::TDK_Success;
1734     }
1735 
1736     case Type::InjectedClassName:
1737       // Treat a template's injected-class-name as if the template
1738       // specialization type had been used.
1739       Param = cast<InjectedClassNameType>(Param)
1740         ->getInjectedSpecializationType();
1741       assert(isa<TemplateSpecializationType>(Param) &&
1742              "injected class name is not a template specialization type");
1743       LLVM_FALLTHROUGH;
1744 
1745     //     template-name<T> (where template-name refers to a class template)
1746     //     template-name<i>
1747     //     TT<T>
1748     //     TT<i>
1749     //     TT<>
1750     case Type::TemplateSpecialization: {
1751       const TemplateSpecializationType *SpecParam =
1752           cast<TemplateSpecializationType>(Param);
1753 
1754       // When Arg cannot be a derived class, we can just try to deduce template
1755       // arguments from the template-id.
1756       const RecordType *RecordT = Arg->getAs<RecordType>();
1757       if (!(TDF & TDF_DerivedClass) || !RecordT)
1758         return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1759                                        Deduced);
1760 
1761       SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1762                                                           Deduced.end());
1763 
1764       Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1765           S, TemplateParams, SpecParam, Arg, Info, Deduced);
1766 
1767       if (Result == Sema::TDK_Success)
1768         return Result;
1769 
1770       // We cannot inspect base classes as part of deduction when the type
1771       // is incomplete, so either instantiate any templates necessary to
1772       // complete the type, or skip over it if it cannot be completed.
1773       if (!S.isCompleteType(Info.getLocation(), Arg))
1774         return Result;
1775 
1776       // C++14 [temp.deduct.call] p4b3:
1777       //   If P is a class and P has the form simple-template-id, then the
1778       //   transformed A can be a derived class of the deduced A. Likewise if
1779       //   P is a pointer to a class of the form simple-template-id, the
1780       //   transformed A can be a pointer to a derived class pointed to by the
1781       //   deduced A.
1782       //
1783       //   These alternatives are considered only if type deduction would
1784       //   otherwise fail. If they yield more than one possible deduced A, the
1785       //   type deduction fails.
1786 
1787       // Reset the incorrectly deduced argument from above.
1788       Deduced = DeducedOrig;
1789 
1790       // Use data recursion to crawl through the list of base classes.
1791       // Visited contains the set of nodes we have already visited, while
1792       // ToVisit is our stack of records that we still need to visit.
1793       llvm::SmallPtrSet<const RecordType *, 8> Visited;
1794       SmallVector<const RecordType *, 8> ToVisit;
1795       ToVisit.push_back(RecordT);
1796       bool Successful = false;
1797       SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
1798       while (!ToVisit.empty()) {
1799         // Retrieve the next class in the inheritance hierarchy.
1800         const RecordType *NextT = ToVisit.pop_back_val();
1801 
1802         // If we have already seen this type, skip it.
1803         if (!Visited.insert(NextT).second)
1804           continue;
1805 
1806         // If this is a base class, try to perform template argument
1807         // deduction from it.
1808         if (NextT != RecordT) {
1809           TemplateDeductionInfo BaseInfo(Info.getLocation());
1810           Sema::TemplateDeductionResult BaseResult =
1811               DeduceTemplateArguments(S, TemplateParams, SpecParam,
1812                                       QualType(NextT, 0), BaseInfo, Deduced);
1813 
1814           // If template argument deduction for this base was successful,
1815           // note that we had some success. Otherwise, ignore any deductions
1816           // from this base class.
1817           if (BaseResult == Sema::TDK_Success) {
1818             // If we've already seen some success, then deduction fails due to
1819             // an ambiguity (temp.deduct.call p5).
1820             if (Successful)
1821               return Sema::TDK_MiscellaneousDeductionFailure;
1822 
1823             Successful = true;
1824             std::swap(SuccessfulDeduced, Deduced);
1825 
1826             Info.Param = BaseInfo.Param;
1827             Info.FirstArg = BaseInfo.FirstArg;
1828             Info.SecondArg = BaseInfo.SecondArg;
1829           }
1830 
1831           Deduced = DeducedOrig;
1832         }
1833 
1834         // Visit base classes
1835         CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1836         for (const auto &Base : Next->bases()) {
1837           assert(Base.getType()->isRecordType() &&
1838                  "Base class that isn't a record?");
1839           ToVisit.push_back(Base.getType()->getAs<RecordType>());
1840         }
1841       }
1842 
1843       if (Successful) {
1844         std::swap(SuccessfulDeduced, Deduced);
1845         return Sema::TDK_Success;
1846       }
1847 
1848       return Result;
1849     }
1850 
1851     //     T type::*
1852     //     T T::*
1853     //     T (type::*)()
1854     //     type (T::*)()
1855     //     type (type::*)(T)
1856     //     type (T::*)(T)
1857     //     T (type::*)(T)
1858     //     T (T::*)()
1859     //     T (T::*)(T)
1860     case Type::MemberPointer: {
1861       const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1862       const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1863       if (!MemPtrArg)
1864         return Sema::TDK_NonDeducedMismatch;
1865 
1866       QualType ParamPointeeType = MemPtrParam->getPointeeType();
1867       if (ParamPointeeType->isFunctionType())
1868         S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1869                                  /*IsCtorOrDtor=*/false, Info.getLocation());
1870       QualType ArgPointeeType = MemPtrArg->getPointeeType();
1871       if (ArgPointeeType->isFunctionType())
1872         S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1873                                  /*IsCtorOrDtor=*/false, Info.getLocation());
1874 
1875       if (Sema::TemplateDeductionResult Result
1876             = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1877                                                  ParamPointeeType,
1878                                                  ArgPointeeType,
1879                                                  Info, Deduced,
1880                                                  TDF & TDF_IgnoreQualifiers))
1881         return Result;
1882 
1883       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1884                                            QualType(MemPtrParam->getClass(), 0),
1885                                            QualType(MemPtrArg->getClass(), 0),
1886                                            Info, Deduced,
1887                                            TDF & TDF_IgnoreQualifiers);
1888     }
1889 
1890     //     (clang extension)
1891     //
1892     //     type(^)(T)
1893     //     T(^)()
1894     //     T(^)(T)
1895     case Type::BlockPointer: {
1896       const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1897       const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
1898 
1899       if (!BlockPtrArg)
1900         return Sema::TDK_NonDeducedMismatch;
1901 
1902       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1903                                                 BlockPtrParam->getPointeeType(),
1904                                                 BlockPtrArg->getPointeeType(),
1905                                                 Info, Deduced, 0);
1906     }
1907 
1908     //     (clang extension)
1909     //
1910     //     T __attribute__(((ext_vector_type(<integral constant>))))
1911     case Type::ExtVector: {
1912       const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1913       if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1914         // Make sure that the vectors have the same number of elements.
1915         if (VectorParam->getNumElements() != VectorArg->getNumElements())
1916           return Sema::TDK_NonDeducedMismatch;
1917 
1918         // Perform deduction on the element types.
1919         return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1920                                                   VectorParam->getElementType(),
1921                                                   VectorArg->getElementType(),
1922                                                   Info, Deduced, TDF);
1923       }
1924 
1925       if (const DependentSizedExtVectorType *VectorArg
1926                                 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1927         // We can't check the number of elements, since the argument has a
1928         // dependent number of elements. This can only occur during partial
1929         // ordering.
1930 
1931         // Perform deduction on the element types.
1932         return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1933                                                   VectorParam->getElementType(),
1934                                                   VectorArg->getElementType(),
1935                                                   Info, Deduced, TDF);
1936       }
1937 
1938       return Sema::TDK_NonDeducedMismatch;
1939     }
1940 
1941     case Type::DependentVector: {
1942       const auto *VectorParam = cast<DependentVectorType>(Param);
1943 
1944       if (const auto *VectorArg = dyn_cast<VectorType>(Arg)) {
1945         // Perform deduction on the element types.
1946         if (Sema::TemplateDeductionResult Result =
1947                 DeduceTemplateArgumentsByTypeMatch(
1948                     S, TemplateParams, VectorParam->getElementType(),
1949                     VectorArg->getElementType(), Info, Deduced, TDF))
1950           return Result;
1951 
1952         // Perform deduction on the vector size, if we can.
1953         NonTypeTemplateParmDecl *NTTP =
1954             getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
1955         if (!NTTP)
1956           return Sema::TDK_Success;
1957 
1958         llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1959         ArgSize = VectorArg->getNumElements();
1960         // Note that we use the "array bound" rules here; just like in that
1961         // case, we don't have any particular type for the vector size, but
1962         // we can provide one if necessary.
1963         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
1964                                              S.Context.UnsignedIntTy, true,
1965                                              Info, Deduced);
1966       }
1967 
1968       if (const auto *VectorArg = dyn_cast<DependentVectorType>(Arg)) {
1969         // Perform deduction on the element types.
1970         if (Sema::TemplateDeductionResult Result =
1971                 DeduceTemplateArgumentsByTypeMatch(
1972                     S, TemplateParams, VectorParam->getElementType(),
1973                     VectorArg->getElementType(), Info, Deduced, TDF))
1974           return Result;
1975 
1976         // Perform deduction on the vector size, if we can.
1977         NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
1978             Info, VectorParam->getSizeExpr());
1979         if (!NTTP)
1980           return Sema::TDK_Success;
1981 
1982         return DeduceNonTypeTemplateArgument(
1983             S, TemplateParams, NTTP, VectorArg->getSizeExpr(), Info, Deduced);
1984       }
1985 
1986       return Sema::TDK_NonDeducedMismatch;
1987     }
1988 
1989     //     (clang extension)
1990     //
1991     //     T __attribute__(((ext_vector_type(N))))
1992     case Type::DependentSizedExtVector: {
1993       const DependentSizedExtVectorType *VectorParam
1994         = cast<DependentSizedExtVectorType>(Param);
1995 
1996       if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1997         // Perform deduction on the element types.
1998         if (Sema::TemplateDeductionResult Result
1999               = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2000                                                   VectorParam->getElementType(),
2001                                                    VectorArg->getElementType(),
2002                                                    Info, Deduced, TDF))
2003           return Result;
2004 
2005         // Perform deduction on the vector size, if we can.
2006         NonTypeTemplateParmDecl *NTTP
2007           = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
2008         if (!NTTP)
2009           return Sema::TDK_Success;
2010 
2011         llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2012         ArgSize = VectorArg->getNumElements();
2013         // Note that we use the "array bound" rules here; just like in that
2014         // case, we don't have any particular type for the vector size, but
2015         // we can provide one if necessary.
2016         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2017                                              S.Context.IntTy, true, Info,
2018                                              Deduced);
2019       }
2020 
2021       if (const DependentSizedExtVectorType *VectorArg
2022                                 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
2023         // Perform deduction on the element types.
2024         if (Sema::TemplateDeductionResult Result
2025             = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2026                                                  VectorParam->getElementType(),
2027                                                  VectorArg->getElementType(),
2028                                                  Info, Deduced, TDF))
2029           return Result;
2030 
2031         // Perform deduction on the vector size, if we can.
2032         NonTypeTemplateParmDecl *NTTP
2033           = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
2034         if (!NTTP)
2035           return Sema::TDK_Success;
2036 
2037         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2038                                              VectorArg->getSizeExpr(),
2039                                              Info, Deduced);
2040       }
2041 
2042       return Sema::TDK_NonDeducedMismatch;
2043     }
2044 
2045     //     (clang extension)
2046     //
2047     //     T __attribute__(((address_space(N))))
2048     case Type::DependentAddressSpace: {
2049       const DependentAddressSpaceType *AddressSpaceParam =
2050           cast<DependentAddressSpaceType>(Param);
2051 
2052       if (const DependentAddressSpaceType *AddressSpaceArg =
2053               dyn_cast<DependentAddressSpaceType>(Arg)) {
2054         // Perform deduction on the pointer type.
2055         if (Sema::TemplateDeductionResult Result =
2056                 DeduceTemplateArgumentsByTypeMatch(
2057                     S, TemplateParams, AddressSpaceParam->getPointeeType(),
2058                     AddressSpaceArg->getPointeeType(), Info, Deduced, TDF))
2059           return Result;
2060 
2061         // Perform deduction on the address space, if we can.
2062         NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
2063             Info, AddressSpaceParam->getAddrSpaceExpr());
2064         if (!NTTP)
2065           return Sema::TDK_Success;
2066 
2067         return DeduceNonTypeTemplateArgument(
2068             S, TemplateParams, NTTP, AddressSpaceArg->getAddrSpaceExpr(), Info,
2069             Deduced);
2070       }
2071 
2072       if (isTargetAddressSpace(Arg.getAddressSpace())) {
2073         llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2074                                      false);
2075         ArgAddressSpace = toTargetAddressSpace(Arg.getAddressSpace());
2076 
2077         // Perform deduction on the pointer types.
2078         if (Sema::TemplateDeductionResult Result =
2079                 DeduceTemplateArgumentsByTypeMatch(
2080                     S, TemplateParams, AddressSpaceParam->getPointeeType(),
2081                     S.Context.removeAddrSpaceQualType(Arg), Info, Deduced, TDF))
2082           return Result;
2083 
2084         // Perform deduction on the address space, if we can.
2085         NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
2086             Info, AddressSpaceParam->getAddrSpaceExpr());
2087         if (!NTTP)
2088           return Sema::TDK_Success;
2089 
2090         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2091                                              ArgAddressSpace, S.Context.IntTy,
2092                                              true, Info, Deduced);
2093       }
2094 
2095       return Sema::TDK_NonDeducedMismatch;
2096     }
2097 
2098     case Type::TypeOfExpr:
2099     case Type::TypeOf:
2100     case Type::DependentName:
2101     case Type::UnresolvedUsing:
2102     case Type::Decltype:
2103     case Type::UnaryTransform:
2104     case Type::Auto:
2105     case Type::DeducedTemplateSpecialization:
2106     case Type::DependentTemplateSpecialization:
2107     case Type::PackExpansion:
2108     case Type::Pipe:
2109       // No template argument deduction for these types
2110       return Sema::TDK_Success;
2111   }
2112 
2113   llvm_unreachable("Invalid Type Class!");
2114 }
2115 
2116 static Sema::TemplateDeductionResult
2117 DeduceTemplateArguments(Sema &S,
2118                         TemplateParameterList *TemplateParams,
2119                         const TemplateArgument &Param,
2120                         TemplateArgument Arg,
2121                         TemplateDeductionInfo &Info,
2122                         SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
2123   // If the template argument is a pack expansion, perform template argument
2124   // deduction against the pattern of that expansion. This only occurs during
2125   // partial ordering.
2126   if (Arg.isPackExpansion())
2127     Arg = Arg.getPackExpansionPattern();
2128 
2129   switch (Param.getKind()) {
2130   case TemplateArgument::Null:
2131     llvm_unreachable("Null template argument in parameter list");
2132 
2133   case TemplateArgument::Type:
2134     if (Arg.getKind() == TemplateArgument::Type)
2135       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2136                                                 Param.getAsType(),
2137                                                 Arg.getAsType(),
2138                                                 Info, Deduced, 0);
2139     Info.FirstArg = Param;
2140     Info.SecondArg = Arg;
2141     return Sema::TDK_NonDeducedMismatch;
2142 
2143   case TemplateArgument::Template:
2144     if (Arg.getKind() == TemplateArgument::Template)
2145       return DeduceTemplateArguments(S, TemplateParams,
2146                                      Param.getAsTemplate(),
2147                                      Arg.getAsTemplate(), Info, Deduced);
2148     Info.FirstArg = Param;
2149     Info.SecondArg = Arg;
2150     return Sema::TDK_NonDeducedMismatch;
2151 
2152   case TemplateArgument::TemplateExpansion:
2153     llvm_unreachable("caller should handle pack expansions");
2154 
2155   case TemplateArgument::Declaration:
2156     if (Arg.getKind() == TemplateArgument::Declaration &&
2157         isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
2158       return Sema::TDK_Success;
2159 
2160     Info.FirstArg = Param;
2161     Info.SecondArg = Arg;
2162     return Sema::TDK_NonDeducedMismatch;
2163 
2164   case TemplateArgument::NullPtr:
2165     if (Arg.getKind() == TemplateArgument::NullPtr &&
2166         S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
2167       return Sema::TDK_Success;
2168 
2169     Info.FirstArg = Param;
2170     Info.SecondArg = Arg;
2171     return Sema::TDK_NonDeducedMismatch;
2172 
2173   case TemplateArgument::Integral:
2174     if (Arg.getKind() == TemplateArgument::Integral) {
2175       if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
2176         return Sema::TDK_Success;
2177 
2178       Info.FirstArg = Param;
2179       Info.SecondArg = Arg;
2180       return Sema::TDK_NonDeducedMismatch;
2181     }
2182 
2183     if (Arg.getKind() == TemplateArgument::Expression) {
2184       Info.FirstArg = Param;
2185       Info.SecondArg = Arg;
2186       return Sema::TDK_NonDeducedMismatch;
2187     }
2188 
2189     Info.FirstArg = Param;
2190     Info.SecondArg = Arg;
2191     return Sema::TDK_NonDeducedMismatch;
2192 
2193   case TemplateArgument::Expression:
2194     if (NonTypeTemplateParmDecl *NTTP
2195           = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
2196       if (Arg.getKind() == TemplateArgument::Integral)
2197         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2198                                              Arg.getAsIntegral(),
2199                                              Arg.getIntegralType(),
2200                                              /*ArrayBound=*/false,
2201                                              Info, Deduced);
2202       if (Arg.getKind() == TemplateArgument::NullPtr)
2203         return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
2204                                              Arg.getNullPtrType(),
2205                                              Info, Deduced);
2206       if (Arg.getKind() == TemplateArgument::Expression)
2207         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2208                                              Arg.getAsExpr(), Info, Deduced);
2209       if (Arg.getKind() == TemplateArgument::Declaration)
2210         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2211                                              Arg.getAsDecl(),
2212                                              Arg.getParamTypeForDecl(),
2213                                              Info, Deduced);
2214 
2215       Info.FirstArg = Param;
2216       Info.SecondArg = Arg;
2217       return Sema::TDK_NonDeducedMismatch;
2218     }
2219 
2220     // Can't deduce anything, but that's okay.
2221     return Sema::TDK_Success;
2222 
2223   case TemplateArgument::Pack:
2224     llvm_unreachable("Argument packs should be expanded by the caller!");
2225   }
2226 
2227   llvm_unreachable("Invalid TemplateArgument Kind!");
2228 }
2229 
2230 /// Determine whether there is a template argument to be used for
2231 /// deduction.
2232 ///
2233 /// This routine "expands" argument packs in-place, overriding its input
2234 /// parameters so that \c Args[ArgIdx] will be the available template argument.
2235 ///
2236 /// \returns true if there is another template argument (which will be at
2237 /// \c Args[ArgIdx]), false otherwise.
2238 static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
2239                                             unsigned &ArgIdx) {
2240   if (ArgIdx == Args.size())
2241     return false;
2242 
2243   const TemplateArgument &Arg = Args[ArgIdx];
2244   if (Arg.getKind() != TemplateArgument::Pack)
2245     return true;
2246 
2247   assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2248   Args = Arg.pack_elements();
2249   ArgIdx = 0;
2250   return ArgIdx < Args.size();
2251 }
2252 
2253 /// Determine whether the given set of template arguments has a pack
2254 /// expansion that is not the last template argument.
2255 static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
2256   bool FoundPackExpansion = false;
2257   for (const auto &A : Args) {
2258     if (FoundPackExpansion)
2259       return true;
2260 
2261     if (A.getKind() == TemplateArgument::Pack)
2262       return hasPackExpansionBeforeEnd(A.pack_elements());
2263 
2264     // FIXME: If this is a fixed-arity pack expansion from an outer level of
2265     // templates, it should not be treated as a pack expansion.
2266     if (A.isPackExpansion())
2267       FoundPackExpansion = true;
2268   }
2269 
2270   return false;
2271 }
2272 
2273 static Sema::TemplateDeductionResult
2274 DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
2275                         ArrayRef<TemplateArgument> Params,
2276                         ArrayRef<TemplateArgument> Args,
2277                         TemplateDeductionInfo &Info,
2278                         SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2279                         bool NumberOfArgumentsMustMatch) {
2280   // C++0x [temp.deduct.type]p9:
2281   //   If the template argument list of P contains a pack expansion that is not
2282   //   the last template argument, the entire template argument list is a
2283   //   non-deduced context.
2284   if (hasPackExpansionBeforeEnd(Params))
2285     return Sema::TDK_Success;
2286 
2287   // C++0x [temp.deduct.type]p9:
2288   //   If P has a form that contains <T> or <i>, then each argument Pi of the
2289   //   respective template argument list P is compared with the corresponding
2290   //   argument Ai of the corresponding template argument list of A.
2291   unsigned ArgIdx = 0, ParamIdx = 0;
2292   for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
2293     if (!Params[ParamIdx].isPackExpansion()) {
2294       // The simple case: deduce template arguments by matching Pi and Ai.
2295 
2296       // Check whether we have enough arguments.
2297       if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
2298         return NumberOfArgumentsMustMatch
2299                    ? Sema::TDK_MiscellaneousDeductionFailure
2300                    : Sema::TDK_Success;
2301 
2302       // C++1z [temp.deduct.type]p9:
2303       //   During partial ordering, if Ai was originally a pack expansion [and]
2304       //   Pi is not a pack expansion, template argument deduction fails.
2305       if (Args[ArgIdx].isPackExpansion())
2306         return Sema::TDK_MiscellaneousDeductionFailure;
2307 
2308       // Perform deduction for this Pi/Ai pair.
2309       if (Sema::TemplateDeductionResult Result
2310             = DeduceTemplateArguments(S, TemplateParams,
2311                                       Params[ParamIdx], Args[ArgIdx],
2312                                       Info, Deduced))
2313         return Result;
2314 
2315       // Move to the next argument.
2316       ++ArgIdx;
2317       continue;
2318     }
2319 
2320     // The parameter is a pack expansion.
2321 
2322     // C++0x [temp.deduct.type]p9:
2323     //   If Pi is a pack expansion, then the pattern of Pi is compared with
2324     //   each remaining argument in the template argument list of A. Each
2325     //   comparison deduces template arguments for subsequent positions in the
2326     //   template parameter packs expanded by Pi.
2327     TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
2328 
2329     // Prepare to deduce the packs within the pattern.
2330     PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2331 
2332     // Keep track of the deduced template arguments for each parameter pack
2333     // expanded by this pack expansion (the outer index) and for each
2334     // template argument (the inner SmallVectors).
2335     for (; hasTemplateArgumentForDeduction(Args, ArgIdx) &&
2336            PackScope.hasNextElement();
2337          ++ArgIdx) {
2338       // Deduce template arguments from the pattern.
2339       if (Sema::TemplateDeductionResult Result
2340             = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
2341                                       Info, Deduced))
2342         return Result;
2343 
2344       PackScope.nextPackElement();
2345     }
2346 
2347     // Build argument packs for each of the parameter packs expanded by this
2348     // pack expansion.
2349     if (auto Result = PackScope.finish())
2350       return Result;
2351   }
2352 
2353   return Sema::TDK_Success;
2354 }
2355 
2356 static Sema::TemplateDeductionResult
2357 DeduceTemplateArguments(Sema &S,
2358                         TemplateParameterList *TemplateParams,
2359                         const TemplateArgumentList &ParamList,
2360                         const TemplateArgumentList &ArgList,
2361                         TemplateDeductionInfo &Info,
2362                         SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
2363   return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
2364                                  ArgList.asArray(), Info, Deduced,
2365                                  /*NumberOfArgumentsMustMatch*/false);
2366 }
2367 
2368 /// Determine whether two template arguments are the same.
2369 static bool isSameTemplateArg(ASTContext &Context,
2370                               TemplateArgument X,
2371                               const TemplateArgument &Y,
2372                               bool PackExpansionMatchesPack = false) {
2373   // If we're checking deduced arguments (X) against original arguments (Y),
2374   // we will have flattened packs to non-expansions in X.
2375   if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2376     X = X.getPackExpansionPattern();
2377 
2378   if (X.getKind() != Y.getKind())
2379     return false;
2380 
2381   switch (X.getKind()) {
2382     case TemplateArgument::Null:
2383       llvm_unreachable("Comparing NULL template argument");
2384 
2385     case TemplateArgument::Type:
2386       return Context.getCanonicalType(X.getAsType()) ==
2387              Context.getCanonicalType(Y.getAsType());
2388 
2389     case TemplateArgument::Declaration:
2390       return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
2391 
2392     case TemplateArgument::NullPtr:
2393       return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2394 
2395     case TemplateArgument::Template:
2396     case TemplateArgument::TemplateExpansion:
2397       return Context.getCanonicalTemplateName(
2398                     X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2399              Context.getCanonicalTemplateName(
2400                     Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
2401 
2402     case TemplateArgument::Integral:
2403       return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2404 
2405     case TemplateArgument::Expression: {
2406       llvm::FoldingSetNodeID XID, YID;
2407       X.getAsExpr()->Profile(XID, Context, true);
2408       Y.getAsExpr()->Profile(YID, Context, true);
2409       return XID == YID;
2410     }
2411 
2412     case TemplateArgument::Pack:
2413       if (X.pack_size() != Y.pack_size())
2414         return false;
2415 
2416       for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2417                                         XPEnd = X.pack_end(),
2418                                            YP = Y.pack_begin();
2419            XP != XPEnd; ++XP, ++YP)
2420         if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
2421           return false;
2422 
2423       return true;
2424   }
2425 
2426   llvm_unreachable("Invalid TemplateArgument Kind!");
2427 }
2428 
2429 /// Allocate a TemplateArgumentLoc where all locations have
2430 /// been initialized to the given location.
2431 ///
2432 /// \param Arg The template argument we are producing template argument
2433 /// location information for.
2434 ///
2435 /// \param NTTPType For a declaration template argument, the type of
2436 /// the non-type template parameter that corresponds to this template
2437 /// argument. Can be null if no type sugar is available to add to the
2438 /// type from the template argument.
2439 ///
2440 /// \param Loc The source location to use for the resulting template
2441 /// argument.
2442 TemplateArgumentLoc
2443 Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2444                                     QualType NTTPType, SourceLocation Loc) {
2445   switch (Arg.getKind()) {
2446   case TemplateArgument::Null:
2447     llvm_unreachable("Can't get a NULL template argument here");
2448 
2449   case TemplateArgument::Type:
2450     return TemplateArgumentLoc(
2451         Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2452 
2453   case TemplateArgument::Declaration: {
2454     if (NTTPType.isNull())
2455       NTTPType = Arg.getParamTypeForDecl();
2456     Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2457                   .getAs<Expr>();
2458     return TemplateArgumentLoc(TemplateArgument(E), E);
2459   }
2460 
2461   case TemplateArgument::NullPtr: {
2462     if (NTTPType.isNull())
2463       NTTPType = Arg.getNullPtrType();
2464     Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2465                   .getAs<Expr>();
2466     return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2467                                E);
2468   }
2469 
2470   case TemplateArgument::Integral: {
2471     Expr *E =
2472         BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
2473     return TemplateArgumentLoc(TemplateArgument(E), E);
2474   }
2475 
2476     case TemplateArgument::Template:
2477     case TemplateArgument::TemplateExpansion: {
2478       NestedNameSpecifierLocBuilder Builder;
2479       TemplateName Template = Arg.getAsTemplate();
2480       if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2481         Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2482       else if (QualifiedTemplateName *QTN =
2483                    Template.getAsQualifiedTemplateName())
2484         Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2485 
2486       if (Arg.getKind() == TemplateArgument::Template)
2487         return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
2488                                    Loc);
2489 
2490       return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
2491                                  Loc, Loc);
2492     }
2493 
2494   case TemplateArgument::Expression:
2495     return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2496 
2497   case TemplateArgument::Pack:
2498     return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2499   }
2500 
2501   llvm_unreachable("Invalid TemplateArgument Kind!");
2502 }
2503 
2504 /// Convert the given deduced template argument and add it to the set of
2505 /// fully-converted template arguments.
2506 static bool
2507 ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2508                                DeducedTemplateArgument Arg,
2509                                NamedDecl *Template,
2510                                TemplateDeductionInfo &Info,
2511                                bool IsDeduced,
2512                                SmallVectorImpl<TemplateArgument> &Output) {
2513   auto ConvertArg = [&](DeducedTemplateArgument Arg,
2514                         unsigned ArgumentPackIndex) {
2515     // Convert the deduced template argument into a template
2516     // argument that we can check, almost as if the user had written
2517     // the template argument explicitly.
2518     TemplateArgumentLoc ArgLoc =
2519         S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
2520 
2521     // Check the template argument, converting it as necessary.
2522     return S.CheckTemplateArgument(
2523         Param, ArgLoc, Template, Template->getLocation(),
2524         Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
2525         IsDeduced
2526             ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2527                                               : Sema::CTAK_Deduced)
2528             : Sema::CTAK_Specified);
2529   };
2530 
2531   if (Arg.getKind() == TemplateArgument::Pack) {
2532     // This is a template argument pack, so check each of its arguments against
2533     // the template parameter.
2534     SmallVector<TemplateArgument, 2> PackedArgsBuilder;
2535     for (const auto &P : Arg.pack_elements()) {
2536       // When converting the deduced template argument, append it to the
2537       // general output list. We need to do this so that the template argument
2538       // checking logic has all of the prior template arguments available.
2539       DeducedTemplateArgument InnerArg(P);
2540       InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
2541       assert(InnerArg.getKind() != TemplateArgument::Pack &&
2542              "deduced nested pack");
2543       if (P.isNull()) {
2544         // We deduced arguments for some elements of this pack, but not for
2545         // all of them. This happens if we get a conditionally-non-deduced
2546         // context in a pack expansion (such as an overload set in one of the
2547         // arguments).
2548         S.Diag(Param->getLocation(),
2549                diag::err_template_arg_deduced_incomplete_pack)
2550           << Arg << Param;
2551         return true;
2552       }
2553       if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
2554         return true;
2555 
2556       // Move the converted template argument into our argument pack.
2557       PackedArgsBuilder.push_back(Output.pop_back_val());
2558     }
2559 
2560     // If the pack is empty, we still need to substitute into the parameter
2561     // itself, in case that substitution fails.
2562     if (PackedArgsBuilder.empty()) {
2563       LocalInstantiationScope Scope(S);
2564       TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
2565       MultiLevelTemplateArgumentList Args(TemplateArgs);
2566 
2567       if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2568         Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2569                                          NTTP, Output,
2570                                          Template->getSourceRange());
2571         if (Inst.isInvalid() ||
2572             S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2573                         NTTP->getDeclName()).isNull())
2574           return true;
2575       } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2576         Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2577                                          TTP, Output,
2578                                          Template->getSourceRange());
2579         if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2580           return true;
2581       }
2582       // For type parameters, no substitution is ever required.
2583     }
2584 
2585     // Create the resulting argument pack.
2586     Output.push_back(
2587         TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
2588     return false;
2589   }
2590 
2591   return ConvertArg(Arg, 0);
2592 }
2593 
2594 template<typename TemplateDeclT>
2595 static Sema::TemplateDeductionResult
2596 CheckDeducedArgumentConstraints(Sema& S, TemplateDeclT *Template,
2597                                 ArrayRef<TemplateArgument> DeducedArgs,
2598                                 TemplateDeductionInfo &Info) {
2599   llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
2600   Template->getAssociatedConstraints(AssociatedConstraints);
2601   if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints,
2602                                     DeducedArgs, Info.getLocation(),
2603                                     Info.AssociatedConstraintsSatisfaction) ||
2604       !Info.AssociatedConstraintsSatisfaction.IsSatisfied) {
2605     Info.reset(TemplateArgumentList::CreateCopy(S.Context, DeducedArgs));
2606     return Sema::TDK_ConstraintsNotSatisfied;
2607   }
2608   return Sema::TDK_Success;
2609 }
2610 
2611 // FIXME: This should not be a template, but
2612 // ClassTemplatePartialSpecializationDecl sadly does not derive from
2613 // TemplateDecl.
2614 template<typename TemplateDeclT>
2615 static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
2616     Sema &S, TemplateDeclT *Template, bool IsDeduced,
2617     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2618     TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2619     LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2620     unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2621   TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2622 
2623   for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2624     NamedDecl *Param = TemplateParams->getParam(I);
2625 
2626     // C++0x [temp.arg.explicit]p3:
2627     //    A trailing template parameter pack (14.5.3) not otherwise deduced will
2628     //    be deduced to an empty sequence of template arguments.
2629     // FIXME: Where did the word "trailing" come from?
2630     if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
2631       if (auto Result = PackDeductionScope(S, TemplateParams, Deduced, Info, I)
2632                             .finish(/*TreatNoDeductionsAsNonDeduced*/false))
2633         return Result;
2634     }
2635 
2636     if (!Deduced[I].isNull()) {
2637       if (I < NumAlreadyConverted) {
2638         // We may have had explicitly-specified template arguments for a
2639         // template parameter pack (that may or may not have been extended
2640         // via additional deduced arguments).
2641         if (Param->isParameterPack() && CurrentInstantiationScope &&
2642             CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2643           // Forget the partially-substituted pack; its substitution is now
2644           // complete.
2645           CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2646           // We still need to check the argument in case it was extended by
2647           // deduction.
2648         } else {
2649           // We have already fully type-checked and converted this
2650           // argument, because it was explicitly-specified. Just record the
2651           // presence of this argument.
2652           Builder.push_back(Deduced[I]);
2653           continue;
2654         }
2655       }
2656 
2657       // We may have deduced this argument, so it still needs to be
2658       // checked and converted.
2659       if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2660                                          IsDeduced, Builder)) {
2661         Info.Param = makeTemplateParameter(Param);
2662         // FIXME: These template arguments are temporary. Free them!
2663         Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2664         return Sema::TDK_SubstitutionFailure;
2665       }
2666 
2667       continue;
2668     }
2669 
2670     // Substitute into the default template argument, if available.
2671     bool HasDefaultArg = false;
2672     TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2673     if (!TD) {
2674       assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2675              isa<VarTemplatePartialSpecializationDecl>(Template));
2676       return Sema::TDK_Incomplete;
2677     }
2678 
2679     TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2680         TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2681         HasDefaultArg);
2682 
2683     // If there was no default argument, deduction is incomplete.
2684     if (DefArg.getArgument().isNull()) {
2685       Info.Param = makeTemplateParameter(
2686           const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2687       Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2688       if (PartialOverloading) break;
2689 
2690       return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2691                            : Sema::TDK_Incomplete;
2692     }
2693 
2694     // Check whether we can actually use the default argument.
2695     if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2696                                 TD->getSourceRange().getEnd(), 0, Builder,
2697                                 Sema::CTAK_Specified)) {
2698       Info.Param = makeTemplateParameter(
2699                          const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2700       // FIXME: These template arguments are temporary. Free them!
2701       Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2702       return Sema::TDK_SubstitutionFailure;
2703     }
2704 
2705     // If we get here, we successfully used the default template argument.
2706   }
2707 
2708   if (Sema::TemplateDeductionResult Result
2709         = CheckDeducedArgumentConstraints(S, Template, Builder, Info))
2710     return Result;
2711 
2712   return Sema::TDK_Success;
2713 }
2714 
2715 static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
2716   if (auto *DC = dyn_cast<DeclContext>(D))
2717     return DC;
2718   return D->getDeclContext();
2719 }
2720 
2721 template<typename T> struct IsPartialSpecialization {
2722   static constexpr bool value = false;
2723 };
2724 template<>
2725 struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2726   static constexpr bool value = true;
2727 };
2728 template<>
2729 struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2730   static constexpr bool value = true;
2731 };
2732 
2733 /// Complete template argument deduction for a partial specialization.
2734 template <typename T>
2735 static typename std::enable_if<IsPartialSpecialization<T>::value,
2736                                Sema::TemplateDeductionResult>::type
2737 FinishTemplateArgumentDeduction(
2738     Sema &S, T *Partial, bool IsPartialOrdering,
2739     const TemplateArgumentList &TemplateArgs,
2740     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2741     TemplateDeductionInfo &Info) {
2742   // Unevaluated SFINAE context.
2743   EnterExpressionEvaluationContext Unevaluated(
2744       S, Sema::ExpressionEvaluationContext::Unevaluated);
2745   Sema::SFINAETrap Trap(S);
2746 
2747   Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
2748 
2749   // C++ [temp.deduct.type]p2:
2750   //   [...] or if any template argument remains neither deduced nor
2751   //   explicitly specified, template argument deduction fails.
2752   SmallVector<TemplateArgument, 4> Builder;
2753   if (auto Result = ConvertDeducedTemplateArguments(
2754           S, Partial, IsPartialOrdering, Deduced, Info, Builder))
2755     return Result;
2756 
2757   // Form the template argument list from the deduced template arguments.
2758   TemplateArgumentList *DeducedArgumentList
2759     = TemplateArgumentList::CreateCopy(S.Context, Builder);
2760 
2761   Info.reset(DeducedArgumentList);
2762 
2763   // Substitute the deduced template arguments into the template
2764   // arguments of the class template partial specialization, and
2765   // verify that the instantiated template arguments are both valid
2766   // and are equivalent to the template arguments originally provided
2767   // to the class template.
2768   LocalInstantiationScope InstScope(S);
2769   auto *Template = Partial->getSpecializedTemplate();
2770   const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2771       Partial->getTemplateArgsAsWritten();
2772   const TemplateArgumentLoc *PartialTemplateArgs =
2773       PartialTemplArgInfo->getTemplateArgs();
2774 
2775   TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2776                                     PartialTemplArgInfo->RAngleLoc);
2777 
2778   if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
2779               InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2780     unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2781     if (ParamIdx >= Partial->getTemplateParameters()->size())
2782       ParamIdx = Partial->getTemplateParameters()->size() - 1;
2783 
2784     Decl *Param = const_cast<NamedDecl *>(
2785         Partial->getTemplateParameters()->getParam(ParamIdx));
2786     Info.Param = makeTemplateParameter(Param);
2787     Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2788     return Sema::TDK_SubstitutionFailure;
2789   }
2790 
2791   bool ConstraintsNotSatisfied;
2792   SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2793   if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2794                                   false, ConvertedInstArgs,
2795                                   /*UpdateArgsWithConversions=*/true,
2796                                   &ConstraintsNotSatisfied))
2797     return ConstraintsNotSatisfied ? Sema::TDK_ConstraintsNotSatisfied :
2798                                      Sema::TDK_SubstitutionFailure;
2799 
2800   TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2801   for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2802     TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2803     if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2804       Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2805       Info.FirstArg = TemplateArgs[I];
2806       Info.SecondArg = InstArg;
2807       return Sema::TDK_NonDeducedMismatch;
2808     }
2809   }
2810 
2811   if (Trap.hasErrorOccurred())
2812     return Sema::TDK_SubstitutionFailure;
2813 
2814   return Sema::TDK_Success;
2815 }
2816 
2817 /// Complete template argument deduction for a class or variable template,
2818 /// when partial ordering against a partial specialization.
2819 // FIXME: Factor out duplication with partial specialization version above.
2820 static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2821     Sema &S, TemplateDecl *Template, bool PartialOrdering,
2822     const TemplateArgumentList &TemplateArgs,
2823     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2824     TemplateDeductionInfo &Info) {
2825   // Unevaluated SFINAE context.
2826   EnterExpressionEvaluationContext Unevaluated(
2827       S, Sema::ExpressionEvaluationContext::Unevaluated);
2828   Sema::SFINAETrap Trap(S);
2829 
2830   Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2831 
2832   // C++ [temp.deduct.type]p2:
2833   //   [...] or if any template argument remains neither deduced nor
2834   //   explicitly specified, template argument deduction fails.
2835   SmallVector<TemplateArgument, 4> Builder;
2836   if (auto Result = ConvertDeducedTemplateArguments(
2837           S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2838     return Result;
2839 
2840   // Check that we produced the correct argument list.
2841   TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2842   for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2843     TemplateArgument InstArg = Builder[I];
2844     if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2845                            /*PackExpansionMatchesPack*/true)) {
2846       Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2847       Info.FirstArg = TemplateArgs[I];
2848       Info.SecondArg = InstArg;
2849       return Sema::TDK_NonDeducedMismatch;
2850     }
2851   }
2852 
2853   if (Trap.hasErrorOccurred())
2854     return Sema::TDK_SubstitutionFailure;
2855 
2856   return Sema::TDK_Success;
2857 }
2858 
2859 /// Perform template argument deduction to determine whether
2860 /// the given template arguments match the given class template
2861 /// partial specialization per C++ [temp.class.spec.match].
2862 Sema::TemplateDeductionResult
2863 Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
2864                               const TemplateArgumentList &TemplateArgs,
2865                               TemplateDeductionInfo &Info) {
2866   if (Partial->isInvalidDecl())
2867     return TDK_Invalid;
2868 
2869   // C++ [temp.class.spec.match]p2:
2870   //   A partial specialization matches a given actual template
2871   //   argument list if the template arguments of the partial
2872   //   specialization can be deduced from the actual template argument
2873   //   list (14.8.2).
2874 
2875   // Unevaluated SFINAE context.
2876   EnterExpressionEvaluationContext Unevaluated(
2877       *this, Sema::ExpressionEvaluationContext::Unevaluated);
2878   SFINAETrap Trap(*this);
2879 
2880   SmallVector<DeducedTemplateArgument, 4> Deduced;
2881   Deduced.resize(Partial->getTemplateParameters()->size());
2882   if (TemplateDeductionResult Result
2883         = ::DeduceTemplateArguments(*this,
2884                                     Partial->getTemplateParameters(),
2885                                     Partial->getTemplateArgs(),
2886                                     TemplateArgs, Info, Deduced))
2887     return Result;
2888 
2889   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2890   InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2891                              Info);
2892   if (Inst.isInvalid())
2893     return TDK_InstantiationDepth;
2894 
2895   if (Trap.hasErrorOccurred())
2896     return Sema::TDK_SubstitutionFailure;
2897 
2898   return ::FinishTemplateArgumentDeduction(
2899       *this, Partial, /*IsPartialOrdering=*/false, TemplateArgs, Deduced, Info);
2900 }
2901 
2902 /// Perform template argument deduction to determine whether
2903 /// the given template arguments match the given variable template
2904 /// partial specialization per C++ [temp.class.spec.match].
2905 Sema::TemplateDeductionResult
2906 Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2907                               const TemplateArgumentList &TemplateArgs,
2908                               TemplateDeductionInfo &Info) {
2909   if (Partial->isInvalidDecl())
2910     return TDK_Invalid;
2911 
2912   // C++ [temp.class.spec.match]p2:
2913   //   A partial specialization matches a given actual template
2914   //   argument list if the template arguments of the partial
2915   //   specialization can be deduced from the actual template argument
2916   //   list (14.8.2).
2917 
2918   // Unevaluated SFINAE context.
2919   EnterExpressionEvaluationContext Unevaluated(
2920       *this, Sema::ExpressionEvaluationContext::Unevaluated);
2921   SFINAETrap Trap(*this);
2922 
2923   SmallVector<DeducedTemplateArgument, 4> Deduced;
2924   Deduced.resize(Partial->getTemplateParameters()->size());
2925   if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2926           *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2927           TemplateArgs, Info, Deduced))
2928     return Result;
2929 
2930   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2931   InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2932                              Info);
2933   if (Inst.isInvalid())
2934     return TDK_InstantiationDepth;
2935 
2936   if (Trap.hasErrorOccurred())
2937     return Sema::TDK_SubstitutionFailure;
2938 
2939   return ::FinishTemplateArgumentDeduction(
2940       *this, Partial, /*IsPartialOrdering=*/false, TemplateArgs, Deduced, Info);
2941 }
2942 
2943 /// Determine whether the given type T is a simple-template-id type.
2944 static bool isSimpleTemplateIdType(QualType T) {
2945   if (const TemplateSpecializationType *Spec
2946         = T->getAs<TemplateSpecializationType>())
2947     return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
2948 
2949   // C++17 [temp.local]p2:
2950   //   the injected-class-name [...] is equivalent to the template-name followed
2951   //   by the template-arguments of the class template specialization or partial
2952   //   specialization enclosed in <>
2953   // ... which means it's equivalent to a simple-template-id.
2954   //
2955   // This only arises during class template argument deduction for a copy
2956   // deduction candidate, where it permits slicing.
2957   if (T->getAs<InjectedClassNameType>())
2958     return true;
2959 
2960   return false;
2961 }
2962 
2963 /// Substitute the explicitly-provided template arguments into the
2964 /// given function template according to C++ [temp.arg.explicit].
2965 ///
2966 /// \param FunctionTemplate the function template into which the explicit
2967 /// template arguments will be substituted.
2968 ///
2969 /// \param ExplicitTemplateArgs the explicitly-specified template
2970 /// arguments.
2971 ///
2972 /// \param Deduced the deduced template arguments, which will be populated
2973 /// with the converted and checked explicit template arguments.
2974 ///
2975 /// \param ParamTypes will be populated with the instantiated function
2976 /// parameters.
2977 ///
2978 /// \param FunctionType if non-NULL, the result type of the function template
2979 /// will also be instantiated and the pointed-to value will be updated with
2980 /// the instantiated function type.
2981 ///
2982 /// \param Info if substitution fails for any reason, this object will be
2983 /// populated with more information about the failure.
2984 ///
2985 /// \returns TDK_Success if substitution was successful, or some failure
2986 /// condition.
2987 Sema::TemplateDeductionResult
2988 Sema::SubstituteExplicitTemplateArguments(
2989                                       FunctionTemplateDecl *FunctionTemplate,
2990                                TemplateArgumentListInfo &ExplicitTemplateArgs,
2991                        SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2992                                  SmallVectorImpl<QualType> &ParamTypes,
2993                                           QualType *FunctionType,
2994                                           TemplateDeductionInfo &Info) {
2995   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2996   TemplateParameterList *TemplateParams
2997     = FunctionTemplate->getTemplateParameters();
2998 
2999   if (ExplicitTemplateArgs.size() == 0) {
3000     // No arguments to substitute; just copy over the parameter types and
3001     // fill in the function type.
3002     for (auto P : Function->parameters())
3003       ParamTypes.push_back(P->getType());
3004 
3005     if (FunctionType)
3006       *FunctionType = Function->getType();
3007     return TDK_Success;
3008   }
3009 
3010   // Unevaluated SFINAE context.
3011   EnterExpressionEvaluationContext Unevaluated(
3012       *this, Sema::ExpressionEvaluationContext::Unevaluated);
3013   SFINAETrap Trap(*this);
3014 
3015   // C++ [temp.arg.explicit]p3:
3016   //   Template arguments that are present shall be specified in the
3017   //   declaration order of their corresponding template-parameters. The
3018   //   template argument list shall not specify more template-arguments than
3019   //   there are corresponding template-parameters.
3020   SmallVector<TemplateArgument, 4> Builder;
3021 
3022   // Enter a new template instantiation context where we check the
3023   // explicitly-specified template arguments against this function template,
3024   // and then substitute them into the function parameter types.
3025   SmallVector<TemplateArgument, 4> DeducedArgs;
3026   InstantiatingTemplate Inst(
3027       *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3028       CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
3029   if (Inst.isInvalid())
3030     return TDK_InstantiationDepth;
3031 
3032   if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
3033                                 ExplicitTemplateArgs, true, Builder, false) ||
3034       Trap.hasErrorOccurred()) {
3035     unsigned Index = Builder.size();
3036     if (Index >= TemplateParams->size())
3037       return TDK_SubstitutionFailure;
3038     Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3039     return TDK_InvalidExplicitArguments;
3040   }
3041 
3042   // Form the template argument list from the explicitly-specified
3043   // template arguments.
3044   TemplateArgumentList *ExplicitArgumentList
3045     = TemplateArgumentList::CreateCopy(Context, Builder);
3046   Info.setExplicitArgs(ExplicitArgumentList);
3047 
3048   // Template argument deduction and the final substitution should be
3049   // done in the context of the templated declaration.  Explicit
3050   // argument substitution, on the other hand, needs to happen in the
3051   // calling context.
3052   ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3053 
3054   // If we deduced template arguments for a template parameter pack,
3055   // note that the template argument pack is partially substituted and record
3056   // the explicit template arguments. They'll be used as part of deduction
3057   // for this template parameter pack.
3058   unsigned PartiallySubstitutedPackIndex = -1u;
3059   if (!Builder.empty()) {
3060     const TemplateArgument &Arg = Builder.back();
3061     if (Arg.getKind() == TemplateArgument::Pack) {
3062       auto *Param = TemplateParams->getParam(Builder.size() - 1);
3063       // If this is a fully-saturated fixed-size pack, it should be
3064       // fully-substituted, not partially-substituted.
3065       Optional<unsigned> Expansions = getExpandedPackSize(Param);
3066       if (!Expansions || Arg.pack_size() < *Expansions) {
3067         PartiallySubstitutedPackIndex = Builder.size() - 1;
3068         CurrentInstantiationScope->SetPartiallySubstitutedPack(
3069             Param, Arg.pack_begin(), Arg.pack_size());
3070       }
3071     }
3072   }
3073 
3074   const FunctionProtoType *Proto
3075     = Function->getType()->getAs<FunctionProtoType>();
3076   assert(Proto && "Function template does not have a prototype?");
3077 
3078   // Isolate our substituted parameters from our caller.
3079   LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3080 
3081   ExtParameterInfoBuilder ExtParamInfos;
3082 
3083   // Instantiate the types of each of the function parameters given the
3084   // explicitly-specified template arguments. If the function has a trailing
3085   // return type, substitute it after the arguments to ensure we substitute
3086   // in lexical order.
3087   if (Proto->hasTrailingReturn()) {
3088     if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3089                        Proto->getExtParameterInfosOrNull(),
3090                        MultiLevelTemplateArgumentList(*ExplicitArgumentList),
3091                        ParamTypes, /*params*/ nullptr, ExtParamInfos))
3092       return TDK_SubstitutionFailure;
3093   }
3094 
3095   // Instantiate the return type.
3096   QualType ResultType;
3097   {
3098     // C++11 [expr.prim.general]p3:
3099     //   If a declaration declares a member function or member function
3100     //   template of a class X, the expression this is a prvalue of type
3101     //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3102     //   and the end of the function-definition, member-declarator, or
3103     //   declarator.
3104     Qualifiers ThisTypeQuals;
3105     CXXRecordDecl *ThisContext = nullptr;
3106     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3107       ThisContext = Method->getParent();
3108       ThisTypeQuals = Method->getMethodQualifiers();
3109     }
3110 
3111     CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3112                                getLangOpts().CPlusPlus11);
3113 
3114     ResultType =
3115         SubstType(Proto->getReturnType(),
3116                   MultiLevelTemplateArgumentList(*ExplicitArgumentList),
3117                   Function->getTypeSpecStartLoc(), Function->getDeclName());
3118     if (ResultType.isNull() || Trap.hasErrorOccurred())
3119       return TDK_SubstitutionFailure;
3120     // CUDA: Kernel function must have 'void' return type.
3121     if (getLangOpts().CUDA)
3122       if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3123         Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3124             << Function->getType() << Function->getSourceRange();
3125         return TDK_SubstitutionFailure;
3126       }
3127   }
3128 
3129   // Instantiate the types of each of the function parameters given the
3130   // explicitly-specified template arguments if we didn't do so earlier.
3131   if (!Proto->hasTrailingReturn() &&
3132       SubstParmTypes(Function->getLocation(), Function->parameters(),
3133                      Proto->getExtParameterInfosOrNull(),
3134                      MultiLevelTemplateArgumentList(*ExplicitArgumentList),
3135                      ParamTypes, /*params*/ nullptr, ExtParamInfos))
3136     return TDK_SubstitutionFailure;
3137 
3138   if (FunctionType) {
3139     auto EPI = Proto->getExtProtoInfo();
3140     EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3141 
3142     // In C++1z onwards, exception specifications are part of the function type,
3143     // so substitution into the type must also substitute into the exception
3144     // specification.
3145     SmallVector<QualType, 4> ExceptionStorage;
3146     if (getLangOpts().CPlusPlus17 &&
3147         SubstExceptionSpec(
3148             Function->getLocation(), EPI.ExceptionSpec, ExceptionStorage,
3149             MultiLevelTemplateArgumentList(*ExplicitArgumentList)))
3150       return TDK_SubstitutionFailure;
3151 
3152     *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3153                                       Function->getLocation(),
3154                                       Function->getDeclName(),
3155                                       EPI);
3156     if (FunctionType->isNull() || Trap.hasErrorOccurred())
3157       return TDK_SubstitutionFailure;
3158   }
3159 
3160   // C++ [temp.arg.explicit]p2:
3161   //   Trailing template arguments that can be deduced (14.8.2) may be
3162   //   omitted from the list of explicit template-arguments. If all of the
3163   //   template arguments can be deduced, they may all be omitted; in this
3164   //   case, the empty template argument list <> itself may also be omitted.
3165   //
3166   // Take all of the explicitly-specified arguments and put them into
3167   // the set of deduced template arguments. The partially-substituted
3168   // parameter pack, however, will be set to NULL since the deduction
3169   // mechanism handles the partially-substituted argument pack directly.
3170   Deduced.reserve(TemplateParams->size());
3171   for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
3172     const TemplateArgument &Arg = ExplicitArgumentList->get(I);
3173     if (I == PartiallySubstitutedPackIndex)
3174       Deduced.push_back(DeducedTemplateArgument());
3175     else
3176       Deduced.push_back(Arg);
3177   }
3178 
3179   return TDK_Success;
3180 }
3181 
3182 /// Check whether the deduced argument type for a call to a function
3183 /// template matches the actual argument type per C++ [temp.deduct.call]p4.
3184 static Sema::TemplateDeductionResult
3185 CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info,
3186                               Sema::OriginalCallArg OriginalArg,
3187                               QualType DeducedA) {
3188   ASTContext &Context = S.Context;
3189 
3190   auto Failed = [&]() -> Sema::TemplateDeductionResult {
3191     Info.FirstArg = TemplateArgument(DeducedA);
3192     Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3193     Info.CallArgIndex = OriginalArg.ArgIdx;
3194     return OriginalArg.DecomposedParam ? Sema::TDK_DeducedMismatchNested
3195                                        : Sema::TDK_DeducedMismatch;
3196   };
3197 
3198   QualType A = OriginalArg.OriginalArgType;
3199   QualType OriginalParamType = OriginalArg.OriginalParamType;
3200 
3201   // Check for type equality (top-level cv-qualifiers are ignored).
3202   if (Context.hasSameUnqualifiedType(A, DeducedA))
3203     return Sema::TDK_Success;
3204 
3205   // Strip off references on the argument types; they aren't needed for
3206   // the following checks.
3207   if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3208     DeducedA = DeducedARef->getPointeeType();
3209   if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3210     A = ARef->getPointeeType();
3211 
3212   // C++ [temp.deduct.call]p4:
3213   //   [...] However, there are three cases that allow a difference:
3214   //     - If the original P is a reference type, the deduced A (i.e., the
3215   //       type referred to by the reference) can be more cv-qualified than
3216   //       the transformed A.
3217   if (const ReferenceType *OriginalParamRef
3218       = OriginalParamType->getAs<ReferenceType>()) {
3219     // We don't want to keep the reference around any more.
3220     OriginalParamType = OriginalParamRef->getPointeeType();
3221 
3222     // FIXME: Resolve core issue (no number yet): if the original P is a
3223     // reference type and the transformed A is function type "noexcept F",
3224     // the deduced A can be F.
3225     QualType Tmp;
3226     if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
3227       return Sema::TDK_Success;
3228 
3229     Qualifiers AQuals = A.getQualifiers();
3230     Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3231 
3232     // Under Objective-C++ ARC, the deduced type may have implicitly
3233     // been given strong or (when dealing with a const reference)
3234     // unsafe_unretained lifetime. If so, update the original
3235     // qualifiers to include this lifetime.
3236     if (S.getLangOpts().ObjCAutoRefCount &&
3237         ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3238           AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
3239          (DeducedAQuals.hasConst() &&
3240           DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3241       AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3242     }
3243 
3244     if (AQuals == DeducedAQuals) {
3245       // Qualifiers match; there's nothing to do.
3246     } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
3247       return Failed();
3248     } else {
3249       // Qualifiers are compatible, so have the argument type adopt the
3250       // deduced argument type's qualifiers as if we had performed the
3251       // qualification conversion.
3252       A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3253     }
3254   }
3255 
3256   //    - The transformed A can be another pointer or pointer to member
3257   //      type that can be converted to the deduced A via a function pointer
3258   //      conversion and/or a qualification conversion.
3259   //
3260   // Also allow conversions which merely strip __attribute__((noreturn)) from
3261   // function types (recursively).
3262   bool ObjCLifetimeConversion = false;
3263   QualType ResultTy;
3264   if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3265       (S.IsQualificationConversion(A, DeducedA, false,
3266                                    ObjCLifetimeConversion) ||
3267        S.IsFunctionConversion(A, DeducedA, ResultTy)))
3268     return Sema::TDK_Success;
3269 
3270   //    - If P is a class and P has the form simple-template-id, then the
3271   //      transformed A can be a derived class of the deduced A. [...]
3272   //     [...] Likewise, if P is a pointer to a class of the form
3273   //      simple-template-id, the transformed A can be a pointer to a
3274   //      derived class pointed to by the deduced A.
3275   if (const PointerType *OriginalParamPtr
3276       = OriginalParamType->getAs<PointerType>()) {
3277     if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3278       if (const PointerType *APtr = A->getAs<PointerType>()) {
3279         if (A->getPointeeType()->isRecordType()) {
3280           OriginalParamType = OriginalParamPtr->getPointeeType();
3281           DeducedA = DeducedAPtr->getPointeeType();
3282           A = APtr->getPointeeType();
3283         }
3284       }
3285     }
3286   }
3287 
3288   if (Context.hasSameUnqualifiedType(A, DeducedA))
3289     return Sema::TDK_Success;
3290 
3291   if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3292       S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3293     return Sema::TDK_Success;
3294 
3295   return Failed();
3296 }
3297 
3298 /// Find the pack index for a particular parameter index in an instantiation of
3299 /// a function template with specific arguments.
3300 ///
3301 /// \return The pack index for whichever pack produced this parameter, or -1
3302 ///         if this was not produced by a parameter. Intended to be used as the
3303 ///         ArgumentPackSubstitutionIndex for further substitutions.
3304 // FIXME: We should track this in OriginalCallArgs so we don't need to
3305 // reconstruct it here.
3306 static unsigned getPackIndexForParam(Sema &S,
3307                                      FunctionTemplateDecl *FunctionTemplate,
3308                                      const MultiLevelTemplateArgumentList &Args,
3309                                      unsigned ParamIdx) {
3310   unsigned Idx = 0;
3311   for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3312     if (PD->isParameterPack()) {
3313       unsigned NumExpansions =
3314           S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
3315       if (Idx + NumExpansions > ParamIdx)
3316         return ParamIdx - Idx;
3317       Idx += NumExpansions;
3318     } else {
3319       if (Idx == ParamIdx)
3320         return -1; // Not a pack expansion
3321       ++Idx;
3322     }
3323   }
3324 
3325   llvm_unreachable("parameter index would not be produced from template");
3326 }
3327 
3328 /// Finish template argument deduction for a function template,
3329 /// checking the deduced template arguments for completeness and forming
3330 /// the function template specialization.
3331 ///
3332 /// \param OriginalCallArgs If non-NULL, the original call arguments against
3333 /// which the deduced argument types should be compared.
3334 Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
3335     FunctionTemplateDecl *FunctionTemplate,
3336     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3337     unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3338     TemplateDeductionInfo &Info,
3339     SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3340     bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
3341   // Unevaluated SFINAE context.
3342   EnterExpressionEvaluationContext Unevaluated(
3343       *this, Sema::ExpressionEvaluationContext::Unevaluated);
3344   SFINAETrap Trap(*this);
3345 
3346   // Enter a new template instantiation context while we instantiate the
3347   // actual function declaration.
3348   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3349   InstantiatingTemplate Inst(
3350       *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3351       CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
3352   if (Inst.isInvalid())
3353     return TDK_InstantiationDepth;
3354 
3355   ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3356 
3357   // C++ [temp.deduct.type]p2:
3358   //   [...] or if any template argument remains neither deduced nor
3359   //   explicitly specified, template argument deduction fails.
3360   SmallVector<TemplateArgument, 4> Builder;
3361   if (auto Result = ConvertDeducedTemplateArguments(
3362           *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
3363           CurrentInstantiationScope, NumExplicitlySpecified,
3364           PartialOverloading))
3365     return Result;
3366 
3367   // C++ [temp.deduct.call]p10: [DR1391]
3368   //   If deduction succeeds for all parameters that contain
3369   //   template-parameters that participate in template argument deduction,
3370   //   and all template arguments are explicitly specified, deduced, or
3371   //   obtained from default template arguments, remaining parameters are then
3372   //   compared with the corresponding arguments. For each remaining parameter
3373   //   P with a type that was non-dependent before substitution of any
3374   //   explicitly-specified template arguments, if the corresponding argument
3375   //   A cannot be implicitly converted to P, deduction fails.
3376   if (CheckNonDependent())
3377     return TDK_NonDependentConversionFailure;
3378 
3379   // Form the template argument list from the deduced template arguments.
3380   TemplateArgumentList *DeducedArgumentList
3381     = TemplateArgumentList::CreateCopy(Context, Builder);
3382   Info.reset(DeducedArgumentList);
3383 
3384   // Substitute the deduced template arguments into the function template
3385   // declaration to produce the function template specialization.
3386   DeclContext *Owner = FunctionTemplate->getDeclContext();
3387   if (FunctionTemplate->getFriendObjectKind())
3388     Owner = FunctionTemplate->getLexicalDeclContext();
3389   MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
3390   Specialization = cast_or_null<FunctionDecl>(
3391       SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
3392   if (!Specialization || Specialization->isInvalidDecl())
3393     return TDK_SubstitutionFailure;
3394 
3395   assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
3396          FunctionTemplate->getCanonicalDecl());
3397 
3398   // If the template argument list is owned by the function template
3399   // specialization, release it.
3400   if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
3401       !Trap.hasErrorOccurred())
3402     Info.take();
3403 
3404   // There may have been an error that did not prevent us from constructing a
3405   // declaration. Mark the declaration invalid and return with a substitution
3406   // failure.
3407   if (Trap.hasErrorOccurred()) {
3408     Specialization->setInvalidDecl(true);
3409     return TDK_SubstitutionFailure;
3410   }
3411 
3412   if (OriginalCallArgs) {
3413     // C++ [temp.deduct.call]p4:
3414     //   In general, the deduction process attempts to find template argument
3415     //   values that will make the deduced A identical to A (after the type A
3416     //   is transformed as described above). [...]
3417     llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
3418     for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3419       OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
3420 
3421       auto ParamIdx = OriginalArg.ArgIdx;
3422       if (ParamIdx >= Specialization->getNumParams())
3423         // FIXME: This presumably means a pack ended up smaller than we
3424         // expected while deducing. Should this not result in deduction
3425         // failure? Can it even happen?
3426         continue;
3427 
3428       QualType DeducedA;
3429       if (!OriginalArg.DecomposedParam) {
3430         // P is one of the function parameters, just look up its substituted
3431         // type.
3432         DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
3433       } else {
3434         // P is a decomposed element of a parameter corresponding to a
3435         // braced-init-list argument. Substitute back into P to find the
3436         // deduced A.
3437         QualType &CacheEntry =
3438             DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3439         if (CacheEntry.isNull()) {
3440           ArgumentPackSubstitutionIndexRAII PackIndex(
3441               *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3442                                           ParamIdx));
3443           CacheEntry =
3444               SubstType(OriginalArg.OriginalParamType, SubstArgs,
3445                         Specialization->getTypeSpecStartLoc(),
3446                         Specialization->getDeclName());
3447         }
3448         DeducedA = CacheEntry;
3449       }
3450 
3451       if (auto TDK =
3452               CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA))
3453         return TDK;
3454     }
3455   }
3456 
3457   // If we suppressed any diagnostics while performing template argument
3458   // deduction, and if we haven't already instantiated this declaration,
3459   // keep track of these diagnostics. They'll be emitted if this specialization
3460   // is actually used.
3461   if (Info.diag_begin() != Info.diag_end()) {
3462     SuppressedDiagnosticsMap::iterator
3463       Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3464     if (Pos == SuppressedDiagnostics.end())
3465         SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3466           .append(Info.diag_begin(), Info.diag_end());
3467   }
3468 
3469   return TDK_Success;
3470 }
3471 
3472 /// Gets the type of a function for template-argument-deducton
3473 /// purposes when it's considered as part of an overload set.
3474 static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
3475                                   FunctionDecl *Fn) {
3476   // We may need to deduce the return type of the function now.
3477   if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
3478       S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
3479     return {};
3480 
3481   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
3482     if (Method->isInstance()) {
3483       // An instance method that's referenced in a form that doesn't
3484       // look like a member pointer is just invalid.
3485       if (!R.HasFormOfMemberPointer)
3486         return {};
3487 
3488       return S.Context.getMemberPointerType(Fn->getType(),
3489                S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
3490     }
3491 
3492   if (!R.IsAddressOfOperand) return Fn->getType();
3493   return S.Context.getPointerType(Fn->getType());
3494 }
3495 
3496 /// Apply the deduction rules for overload sets.
3497 ///
3498 /// \return the null type if this argument should be treated as an
3499 /// undeduced context
3500 static QualType
3501 ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
3502                             Expr *Arg, QualType ParamType,
3503                             bool ParamWasReference) {
3504 
3505   OverloadExpr::FindResult R = OverloadExpr::find(Arg);
3506 
3507   OverloadExpr *Ovl = R.Expression;
3508 
3509   // C++0x [temp.deduct.call]p4
3510   unsigned TDF = 0;
3511   if (ParamWasReference)
3512     TDF |= TDF_ParamWithReferenceType;
3513   if (R.IsAddressOfOperand)
3514     TDF |= TDF_IgnoreQualifiers;
3515 
3516   // C++0x [temp.deduct.call]p6:
3517   //   When P is a function type, pointer to function type, or pointer
3518   //   to member function type:
3519 
3520   if (!ParamType->isFunctionType() &&
3521       !ParamType->isFunctionPointerType() &&
3522       !ParamType->isMemberFunctionPointerType()) {
3523     if (Ovl->hasExplicitTemplateArgs()) {
3524       // But we can still look for an explicit specialization.
3525       if (FunctionDecl *ExplicitSpec
3526             = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
3527         return GetTypeOfFunction(S, R, ExplicitSpec);
3528     }
3529 
3530     DeclAccessPair DAP;
3531     if (FunctionDecl *Viable =
3532             S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3533       return GetTypeOfFunction(S, R, Viable);
3534 
3535     return {};
3536   }
3537 
3538   // Gather the explicit template arguments, if any.
3539   TemplateArgumentListInfo ExplicitTemplateArgs;
3540   if (Ovl->hasExplicitTemplateArgs())
3541     Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
3542   QualType Match;
3543   for (UnresolvedSetIterator I = Ovl->decls_begin(),
3544          E = Ovl->decls_end(); I != E; ++I) {
3545     NamedDecl *D = (*I)->getUnderlyingDecl();
3546 
3547     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3548       //   - If the argument is an overload set containing one or more
3549       //     function templates, the parameter is treated as a
3550       //     non-deduced context.
3551       if (!Ovl->hasExplicitTemplateArgs())
3552         return {};
3553 
3554       // Otherwise, see if we can resolve a function type
3555       FunctionDecl *Specialization = nullptr;
3556       TemplateDeductionInfo Info(Ovl->getNameLoc());
3557       if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3558                                     Specialization, Info))
3559         continue;
3560 
3561       D = Specialization;
3562     }
3563 
3564     FunctionDecl *Fn = cast<FunctionDecl>(D);
3565     QualType ArgType = GetTypeOfFunction(S, R, Fn);
3566     if (ArgType.isNull()) continue;
3567 
3568     // Function-to-pointer conversion.
3569     if (!ParamWasReference && ParamType->isPointerType() &&
3570         ArgType->isFunctionType())
3571       ArgType = S.Context.getPointerType(ArgType);
3572 
3573     //   - If the argument is an overload set (not containing function
3574     //     templates), trial argument deduction is attempted using each
3575     //     of the members of the set. If deduction succeeds for only one
3576     //     of the overload set members, that member is used as the
3577     //     argument value for the deduction. If deduction succeeds for
3578     //     more than one member of the overload set the parameter is
3579     //     treated as a non-deduced context.
3580 
3581     // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3582     //   Type deduction is done independently for each P/A pair, and
3583     //   the deduced template argument values are then combined.
3584     // So we do not reject deductions which were made elsewhere.
3585     SmallVector<DeducedTemplateArgument, 8>
3586       Deduced(TemplateParams->size());
3587     TemplateDeductionInfo Info(Ovl->getNameLoc());
3588     Sema::TemplateDeductionResult Result
3589       = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3590                                            ArgType, Info, Deduced, TDF);
3591     if (Result) continue;
3592     if (!Match.isNull())
3593       return {};
3594     Match = ArgType;
3595   }
3596 
3597   return Match;
3598 }
3599 
3600 /// Perform the adjustments to the parameter and argument types
3601 /// described in C++ [temp.deduct.call].
3602 ///
3603 /// \returns true if the caller should not attempt to perform any template
3604 /// argument deduction based on this P/A pair because the argument is an
3605 /// overloaded function set that could not be resolved.
3606 static bool AdjustFunctionParmAndArgTypesForDeduction(
3607     Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3608     QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) {
3609   // C++0x [temp.deduct.call]p3:
3610   //   If P is a cv-qualified type, the top level cv-qualifiers of P's type
3611   //   are ignored for type deduction.
3612   if (ParamType.hasQualifiers())
3613     ParamType = ParamType.getUnqualifiedType();
3614 
3615   //   [...] If P is a reference type, the type referred to by P is
3616   //   used for type deduction.
3617   const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
3618   if (ParamRefType)
3619     ParamType = ParamRefType->getPointeeType();
3620 
3621   // Overload sets usually make this parameter an undeduced context,
3622   // but there are sometimes special circumstances.  Typically
3623   // involving a template-id-expr.
3624   if (ArgType == S.Context.OverloadTy) {
3625     ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3626                                           Arg, ParamType,
3627                                           ParamRefType != nullptr);
3628     if (ArgType.isNull())
3629       return true;
3630   }
3631 
3632   if (ParamRefType) {
3633     // If the argument has incomplete array type, try to complete its type.
3634     if (ArgType->isIncompleteArrayType()) {
3635       S.completeExprArrayBound(Arg);
3636       ArgType = Arg->getType();
3637     }
3638 
3639     // C++1z [temp.deduct.call]p3:
3640     //   If P is a forwarding reference and the argument is an lvalue, the type
3641     //   "lvalue reference to A" is used in place of A for type deduction.
3642     if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
3643         Arg->isLValue())
3644       ArgType = S.Context.getLValueReferenceType(ArgType);
3645   } else {
3646     // C++ [temp.deduct.call]p2:
3647     //   If P is not a reference type:
3648     //   - If A is an array type, the pointer type produced by the
3649     //     array-to-pointer standard conversion (4.2) is used in place of
3650     //     A for type deduction; otherwise,
3651     if (ArgType->isArrayType())
3652       ArgType = S.Context.getArrayDecayedType(ArgType);
3653     //   - If A is a function type, the pointer type produced by the
3654     //     function-to-pointer standard conversion (4.3) is used in place
3655     //     of A for type deduction; otherwise,
3656     else if (ArgType->isFunctionType())
3657       ArgType = S.Context.getPointerType(ArgType);
3658     else {
3659       // - If A is a cv-qualified type, the top level cv-qualifiers of A's
3660       //   type are ignored for type deduction.
3661       ArgType = ArgType.getUnqualifiedType();
3662     }
3663   }
3664 
3665   // C++0x [temp.deduct.call]p4:
3666   //   In general, the deduction process attempts to find template argument
3667   //   values that will make the deduced A identical to A (after the type A
3668   //   is transformed as described above). [...]
3669   TDF = TDF_SkipNonDependent;
3670 
3671   //     - If the original P is a reference type, the deduced A (i.e., the
3672   //       type referred to by the reference) can be more cv-qualified than
3673   //       the transformed A.
3674   if (ParamRefType)
3675     TDF |= TDF_ParamWithReferenceType;
3676   //     - The transformed A can be another pointer or pointer to member
3677   //       type that can be converted to the deduced A via a qualification
3678   //       conversion (4.4).
3679   if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3680       ArgType->isObjCObjectPointerType())
3681     TDF |= TDF_IgnoreQualifiers;
3682   //     - If P is a class and P has the form simple-template-id, then the
3683   //       transformed A can be a derived class of the deduced A. Likewise,
3684   //       if P is a pointer to a class of the form simple-template-id, the
3685   //       transformed A can be a pointer to a derived class pointed to by
3686   //       the deduced A.
3687   if (isSimpleTemplateIdType(ParamType) ||
3688       (isa<PointerType>(ParamType) &&
3689        isSimpleTemplateIdType(
3690                               ParamType->getAs<PointerType>()->getPointeeType())))
3691     TDF |= TDF_DerivedClass;
3692 
3693   return false;
3694 }
3695 
3696 static bool
3697 hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3698                                QualType T);
3699 
3700 static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
3701     Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3702     QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
3703     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3704     SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
3705     bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
3706 
3707 /// Attempt template argument deduction from an initializer list
3708 ///        deemed to be an argument in a function call.
3709 static Sema::TemplateDeductionResult DeduceFromInitializerList(
3710     Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3711     InitListExpr *ILE, TemplateDeductionInfo &Info,
3712     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3713     SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
3714     unsigned TDF) {
3715   // C++ [temp.deduct.call]p1: (CWG 1591)
3716   //   If removing references and cv-qualifiers from P gives
3717   //   std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3718   //   a non-empty initializer list, then deduction is performed instead for
3719   //   each element of the initializer list, taking P0 as a function template
3720   //   parameter type and the initializer element as its argument
3721   //
3722   // We've already removed references and cv-qualifiers here.
3723   if (!ILE->getNumInits())
3724     return Sema::TDK_Success;
3725 
3726   QualType ElTy;
3727   auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3728   if (ArrTy)
3729     ElTy = ArrTy->getElementType();
3730   else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3731     //   Otherwise, an initializer list argument causes the parameter to be
3732     //   considered a non-deduced context
3733     return Sema::TDK_Success;
3734   }
3735 
3736   // Resolving a core issue: a braced-init-list containing any designators is
3737   // a non-deduced context.
3738   for (Expr *E : ILE->inits())
3739     if (isa<DesignatedInitExpr>(E))
3740       return Sema::TDK_Success;
3741 
3742   // Deduction only needs to be done for dependent types.
3743   if (ElTy->isDependentType()) {
3744     for (Expr *E : ILE->inits()) {
3745       if (auto Result = DeduceTemplateArgumentsFromCallArgument(
3746               S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true,
3747               ArgIdx, TDF))
3748         return Result;
3749     }
3750   }
3751 
3752   //   in the P0[N] case, if N is a non-type template parameter, N is deduced
3753   //   from the length of the initializer list.
3754   if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
3755     // Determine the array bound is something we can deduce.
3756     if (NonTypeTemplateParmDecl *NTTP =
3757             getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
3758       // We can perform template argument deduction for the given non-type
3759       // template parameter.
3760       // C++ [temp.deduct.type]p13:
3761       //   The type of N in the type T[N] is std::size_t.
3762       QualType T = S.Context.getSizeType();
3763       llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
3764       if (auto Result = DeduceNonTypeTemplateArgument(
3765               S, TemplateParams, NTTP, llvm::APSInt(Size), T,
3766               /*ArrayBound=*/true, Info, Deduced))
3767         return Result;
3768     }
3769   }
3770 
3771   return Sema::TDK_Success;
3772 }
3773 
3774 /// Perform template argument deduction per [temp.deduct.call] for a
3775 ///        single parameter / argument pair.
3776 static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
3777     Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3778     QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
3779     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3780     SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
3781     bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
3782   QualType ArgType = Arg->getType();
3783   QualType OrigParamType = ParamType;
3784 
3785   //   If P is a reference type [...]
3786   //   If P is a cv-qualified type [...]
3787   if (AdjustFunctionParmAndArgTypesForDeduction(
3788           S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF))
3789     return Sema::TDK_Success;
3790 
3791   //   If [...] the argument is a non-empty initializer list [...]
3792   if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3793     return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
3794                                      Deduced, OriginalCallArgs, ArgIdx, TDF);
3795 
3796   //   [...] the deduction process attempts to find template argument values
3797   //   that will make the deduced A identical to A
3798   //
3799   // Keep track of the argument type and corresponding parameter index,
3800   // so we can check for compatibility between the deduced A and A.
3801   OriginalCallArgs.push_back(
3802       Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
3803   return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3804                                             ArgType, Info, Deduced, TDF);
3805 }
3806 
3807 /// Perform template argument deduction from a function call
3808 /// (C++ [temp.deduct.call]).
3809 ///
3810 /// \param FunctionTemplate the function template for which we are performing
3811 /// template argument deduction.
3812 ///
3813 /// \param ExplicitTemplateArgs the explicit template arguments provided
3814 /// for this call.
3815 ///
3816 /// \param Args the function call arguments
3817 ///
3818 /// \param Specialization if template argument deduction was successful,
3819 /// this will be set to the function template specialization produced by
3820 /// template argument deduction.
3821 ///
3822 /// \param Info the argument will be updated to provide additional information
3823 /// about template argument deduction.
3824 ///
3825 /// \param CheckNonDependent A callback to invoke to check conversions for
3826 /// non-dependent parameters, between deduction and substitution, per DR1391.
3827 /// If this returns true, substitution will be skipped and we return
3828 /// TDK_NonDependentConversionFailure. The callback is passed the parameter
3829 /// types (after substituting explicit template arguments).
3830 ///
3831 /// \returns the result of template argument deduction.
3832 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3833     FunctionTemplateDecl *FunctionTemplate,
3834     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3835     FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3836     bool PartialOverloading,
3837     llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
3838   if (FunctionTemplate->isInvalidDecl())
3839     return TDK_Invalid;
3840 
3841   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3842   unsigned NumParams = Function->getNumParams();
3843 
3844   unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
3845 
3846   // C++ [temp.deduct.call]p1:
3847   //   Template argument deduction is done by comparing each function template
3848   //   parameter type (call it P) with the type of the corresponding argument
3849   //   of the call (call it A) as described below.
3850   if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
3851     return TDK_TooFewArguments;
3852   else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
3853     const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
3854     if (Proto->isTemplateVariadic())
3855       /* Do nothing */;
3856     else if (!Proto->isVariadic())
3857       return TDK_TooManyArguments;
3858   }
3859 
3860   // The types of the parameters from which we will perform template argument
3861   // deduction.
3862   LocalInstantiationScope InstScope(*this);
3863   TemplateParameterList *TemplateParams
3864     = FunctionTemplate->getTemplateParameters();
3865   SmallVector<DeducedTemplateArgument, 4> Deduced;
3866   SmallVector<QualType, 8> ParamTypes;
3867   unsigned NumExplicitlySpecified = 0;
3868   if (ExplicitTemplateArgs) {
3869     TemplateDeductionResult Result =
3870       SubstituteExplicitTemplateArguments(FunctionTemplate,
3871                                           *ExplicitTemplateArgs,
3872                                           Deduced,
3873                                           ParamTypes,
3874                                           nullptr,
3875                                           Info);
3876     if (Result)
3877       return Result;
3878 
3879     NumExplicitlySpecified = Deduced.size();
3880   } else {
3881     // Just fill in the parameter types from the function declaration.
3882     for (unsigned I = 0; I != NumParams; ++I)
3883       ParamTypes.push_back(Function->getParamDecl(I)->getType());
3884   }
3885 
3886   SmallVector<OriginalCallArg, 8> OriginalCallArgs;
3887 
3888   // Deduce an argument of type ParamType from an expression with index ArgIdx.
3889   auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
3890     // C++ [demp.deduct.call]p1: (DR1391)
3891     //   Template argument deduction is done by comparing each function template
3892     //   parameter that contains template-parameters that participate in
3893     //   template argument deduction ...
3894     if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3895       return Sema::TDK_Success;
3896 
3897     //   ... with the type of the corresponding argument
3898     return DeduceTemplateArgumentsFromCallArgument(
3899         *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced,
3900         OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
3901   };
3902 
3903   // Deduce template arguments from the function parameters.
3904   Deduced.resize(TemplateParams->size());
3905   SmallVector<QualType, 8> ParamTypesForArgChecking;
3906   for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
3907        ParamIdx != NumParamTypes; ++ParamIdx) {
3908     QualType ParamType = ParamTypes[ParamIdx];
3909 
3910     const PackExpansionType *ParamExpansion =
3911         dyn_cast<PackExpansionType>(ParamType);
3912     if (!ParamExpansion) {
3913       // Simple case: matching a function parameter to a function argument.
3914       if (ArgIdx >= Args.size())
3915         break;
3916 
3917       ParamTypesForArgChecking.push_back(ParamType);
3918       if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
3919         return Result;
3920 
3921       continue;
3922     }
3923 
3924     QualType ParamPattern = ParamExpansion->getPattern();
3925     PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3926                                  ParamPattern);
3927 
3928     // C++0x [temp.deduct.call]p1:
3929     //   For a function parameter pack that occurs at the end of the
3930     //   parameter-declaration-list, the type A of each remaining argument of
3931     //   the call is compared with the type P of the declarator-id of the
3932     //   function parameter pack. Each comparison deduces template arguments
3933     //   for subsequent positions in the template parameter packs expanded by
3934     //   the function parameter pack. When a function parameter pack appears
3935     //   in a non-deduced context [not at the end of the list], the type of
3936     //   that parameter pack is never deduced.
3937     //
3938     // FIXME: The above rule allows the size of the parameter pack to change
3939     // after we skip it (in the non-deduced case). That makes no sense, so
3940     // we instead notionally deduce the pack against N arguments, where N is
3941     // the length of the explicitly-specified pack if it's expanded by the
3942     // parameter pack and 0 otherwise, and we treat each deduction as a
3943     // non-deduced context.
3944     if (ParamIdx + 1 == NumParamTypes || PackScope.hasFixedArity()) {
3945       for (; ArgIdx < Args.size() && PackScope.hasNextElement();
3946            PackScope.nextPackElement(), ++ArgIdx) {
3947         ParamTypesForArgChecking.push_back(ParamPattern);
3948         if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3949           return Result;
3950       }
3951     } else {
3952       // If the parameter type contains an explicitly-specified pack that we
3953       // could not expand, skip the number of parameters notionally created
3954       // by the expansion.
3955       Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions();
3956       if (NumExpansions && !PackScope.isPartiallyExpanded()) {
3957         for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
3958              ++I, ++ArgIdx) {
3959           ParamTypesForArgChecking.push_back(ParamPattern);
3960           // FIXME: Should we add OriginalCallArgs for these? What if the
3961           // corresponding argument is a list?
3962           PackScope.nextPackElement();
3963         }
3964       }
3965     }
3966 
3967     // Build argument packs for each of the parameter packs expanded by this
3968     // pack expansion.
3969     if (auto Result = PackScope.finish())
3970       return Result;
3971   }
3972 
3973   // Capture the context in which the function call is made. This is the context
3974   // that is needed when the accessibility of template arguments is checked.
3975   DeclContext *CallingCtx = CurContext;
3976 
3977   return FinishTemplateArgumentDeduction(
3978       FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
3979       &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
3980         ContextRAII SavedContext(*this, CallingCtx);
3981         return CheckNonDependent(ParamTypesForArgChecking);
3982       });
3983 }
3984 
3985 QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3986                                    QualType FunctionType,
3987                                    bool AdjustExceptionSpec) {
3988   if (ArgFunctionType.isNull())
3989     return ArgFunctionType;
3990 
3991   const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
3992   const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
3993   FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3994   bool Rebuild = false;
3995 
3996   CallingConv CC = FunctionTypeP->getCallConv();
3997   if (EPI.ExtInfo.getCC() != CC) {
3998     EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3999     Rebuild = true;
4000   }
4001 
4002   bool NoReturn = FunctionTypeP->getNoReturnAttr();
4003   if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4004     EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4005     Rebuild = true;
4006   }
4007 
4008   if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4009                               ArgFunctionTypeP->hasExceptionSpec())) {
4010     EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4011     Rebuild = true;
4012   }
4013 
4014   if (!Rebuild)
4015     return ArgFunctionType;
4016 
4017   return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4018                                  ArgFunctionTypeP->getParamTypes(), EPI);
4019 }
4020 
4021 /// Deduce template arguments when taking the address of a function
4022 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
4023 /// a template.
4024 ///
4025 /// \param FunctionTemplate the function template for which we are performing
4026 /// template argument deduction.
4027 ///
4028 /// \param ExplicitTemplateArgs the explicitly-specified template
4029 /// arguments.
4030 ///
4031 /// \param ArgFunctionType the function type that will be used as the
4032 /// "argument" type (A) when performing template argument deduction from the
4033 /// function template's function type. This type may be NULL, if there is no
4034 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
4035 ///
4036 /// \param Specialization if template argument deduction was successful,
4037 /// this will be set to the function template specialization produced by
4038 /// template argument deduction.
4039 ///
4040 /// \param Info the argument will be updated to provide additional information
4041 /// about template argument deduction.
4042 ///
4043 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4044 /// the address of a function template per [temp.deduct.funcaddr] and
4045 /// [over.over]. If \c false, we are looking up a function template
4046 /// specialization based on its signature, per [temp.deduct.decl].
4047 ///
4048 /// \returns the result of template argument deduction.
4049 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4050     FunctionTemplateDecl *FunctionTemplate,
4051     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4052     FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4053     bool IsAddressOfFunction) {
4054   if (FunctionTemplate->isInvalidDecl())
4055     return TDK_Invalid;
4056 
4057   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4058   TemplateParameterList *TemplateParams
4059     = FunctionTemplate->getTemplateParameters();
4060   QualType FunctionType = Function->getType();
4061 
4062   // Substitute any explicit template arguments.
4063   LocalInstantiationScope InstScope(*this);
4064   SmallVector<DeducedTemplateArgument, 4> Deduced;
4065   unsigned NumExplicitlySpecified = 0;
4066   SmallVector<QualType, 4> ParamTypes;
4067   if (ExplicitTemplateArgs) {
4068     if (TemplateDeductionResult Result
4069           = SubstituteExplicitTemplateArguments(FunctionTemplate,
4070                                                 *ExplicitTemplateArgs,
4071                                                 Deduced, ParamTypes,
4072                                                 &FunctionType, Info))
4073       return Result;
4074 
4075     NumExplicitlySpecified = Deduced.size();
4076   }
4077 
4078   // When taking the address of a function, we require convertibility of
4079   // the resulting function type. Otherwise, we allow arbitrary mismatches
4080   // of calling convention and noreturn.
4081   if (!IsAddressOfFunction)
4082     ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4083                                           /*AdjustExceptionSpec*/false);
4084 
4085   // Unevaluated SFINAE context.
4086   EnterExpressionEvaluationContext Unevaluated(
4087       *this, Sema::ExpressionEvaluationContext::Unevaluated);
4088   SFINAETrap Trap(*this);
4089 
4090   Deduced.resize(TemplateParams->size());
4091 
4092   // If the function has a deduced return type, substitute it for a dependent
4093   // type so that we treat it as a non-deduced context in what follows. If we
4094   // are looking up by signature, the signature type should also have a deduced
4095   // return type, which we instead expect to exactly match.
4096   bool HasDeducedReturnType = false;
4097   if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
4098       Function->getReturnType()->getContainedAutoType()) {
4099     FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
4100     HasDeducedReturnType = true;
4101   }
4102 
4103   if (!ArgFunctionType.isNull()) {
4104     unsigned TDF =
4105         TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType;
4106     // Deduce template arguments from the function type.
4107     if (TemplateDeductionResult Result
4108           = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
4109                                                FunctionType, ArgFunctionType,
4110                                                Info, Deduced, TDF))
4111       return Result;
4112   }
4113 
4114   if (TemplateDeductionResult Result
4115         = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
4116                                           NumExplicitlySpecified,
4117                                           Specialization, Info))
4118     return Result;
4119 
4120   // If the function has a deduced return type, deduce it now, so we can check
4121   // that the deduced function type matches the requested type.
4122   if (HasDeducedReturnType &&
4123       Specialization->getReturnType()->isUndeducedType() &&
4124       DeduceReturnType(Specialization, Info.getLocation(), false))
4125     return TDK_MiscellaneousDeductionFailure;
4126 
4127   // If the function has a dependent exception specification, resolve it now,
4128   // so we can check that the exception specification matches.
4129   auto *SpecializationFPT =
4130       Specialization->getType()->castAs<FunctionProtoType>();
4131   if (getLangOpts().CPlusPlus17 &&
4132       isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
4133       !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
4134     return TDK_MiscellaneousDeductionFailure;
4135 
4136   // Adjust the exception specification of the argument to match the
4137   // substituted and resolved type we just formed. (Calling convention and
4138   // noreturn can't be dependent, so we don't actually need this for them
4139   // right now.)
4140   QualType SpecializationType = Specialization->getType();
4141   if (!IsAddressOfFunction)
4142     ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4143                                           /*AdjustExceptionSpec*/true);
4144 
4145   // If the requested function type does not match the actual type of the
4146   // specialization with respect to arguments of compatible pointer to function
4147   // types, template argument deduction fails.
4148   if (!ArgFunctionType.isNull()) {
4149     if (IsAddressOfFunction &&
4150         !isSameOrCompatibleFunctionType(
4151             Context.getCanonicalType(SpecializationType),
4152             Context.getCanonicalType(ArgFunctionType)))
4153       return TDK_MiscellaneousDeductionFailure;
4154 
4155     if (!IsAddressOfFunction &&
4156         !Context.hasSameType(SpecializationType, ArgFunctionType))
4157       return TDK_MiscellaneousDeductionFailure;
4158   }
4159 
4160   return TDK_Success;
4161 }
4162 
4163 /// Deduce template arguments for a templated conversion
4164 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
4165 /// conversion function template specialization.
4166 Sema::TemplateDeductionResult
4167 Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
4168                               QualType ToType,
4169                               CXXConversionDecl *&Specialization,
4170                               TemplateDeductionInfo &Info) {
4171   if (ConversionTemplate->isInvalidDecl())
4172     return TDK_Invalid;
4173 
4174   CXXConversionDecl *ConversionGeneric
4175     = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4176 
4177   QualType FromType = ConversionGeneric->getConversionType();
4178 
4179   // Canonicalize the types for deduction.
4180   QualType P = Context.getCanonicalType(FromType);
4181   QualType A = Context.getCanonicalType(ToType);
4182 
4183   // C++0x [temp.deduct.conv]p2:
4184   //   If P is a reference type, the type referred to by P is used for
4185   //   type deduction.
4186   if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4187     P = PRef->getPointeeType();
4188 
4189   // C++0x [temp.deduct.conv]p4:
4190   //   [...] If A is a reference type, the type referred to by A is used
4191   //   for type deduction.
4192   if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4193     A = ARef->getPointeeType();
4194     // We work around a defect in the standard here: cv-qualifiers are also
4195     // removed from P and A in this case, unless P was a reference type. This
4196     // seems to mostly match what other compilers are doing.
4197     if (!FromType->getAs<ReferenceType>()) {
4198       A = A.getUnqualifiedType();
4199       P = P.getUnqualifiedType();
4200     }
4201 
4202   // C++ [temp.deduct.conv]p3:
4203   //
4204   //   If A is not a reference type:
4205   } else {
4206     assert(!A->isReferenceType() && "Reference types were handled above");
4207 
4208     //   - If P is an array type, the pointer type produced by the
4209     //     array-to-pointer standard conversion (4.2) is used in place
4210     //     of P for type deduction; otherwise,
4211     if (P->isArrayType())
4212       P = Context.getArrayDecayedType(P);
4213     //   - If P is a function type, the pointer type produced by the
4214     //     function-to-pointer standard conversion (4.3) is used in
4215     //     place of P for type deduction; otherwise,
4216     else if (P->isFunctionType())
4217       P = Context.getPointerType(P);
4218     //   - If P is a cv-qualified type, the top level cv-qualifiers of
4219     //     P's type are ignored for type deduction.
4220     else
4221       P = P.getUnqualifiedType();
4222 
4223     // C++0x [temp.deduct.conv]p4:
4224     //   If A is a cv-qualified type, the top level cv-qualifiers of A's
4225     //   type are ignored for type deduction. If A is a reference type, the type
4226     //   referred to by A is used for type deduction.
4227     A = A.getUnqualifiedType();
4228   }
4229 
4230   // Unevaluated SFINAE context.
4231   EnterExpressionEvaluationContext Unevaluated(
4232       *this, Sema::ExpressionEvaluationContext::Unevaluated);
4233   SFINAETrap Trap(*this);
4234 
4235   // C++ [temp.deduct.conv]p1:
4236   //   Template argument deduction is done by comparing the return
4237   //   type of the template conversion function (call it P) with the
4238   //   type that is required as the result of the conversion (call it
4239   //   A) as described in 14.8.2.4.
4240   TemplateParameterList *TemplateParams
4241     = ConversionTemplate->getTemplateParameters();
4242   SmallVector<DeducedTemplateArgument, 4> Deduced;
4243   Deduced.resize(TemplateParams->size());
4244 
4245   // C++0x [temp.deduct.conv]p4:
4246   //   In general, the deduction process attempts to find template
4247   //   argument values that will make the deduced A identical to
4248   //   A. However, there are two cases that allow a difference:
4249   unsigned TDF = 0;
4250   //     - If the original A is a reference type, A can be more
4251   //       cv-qualified than the deduced A (i.e., the type referred to
4252   //       by the reference)
4253   if (ToType->isReferenceType())
4254     TDF |= TDF_ArgWithReferenceType;
4255   //     - The deduced A can be another pointer or pointer to member
4256   //       type that can be converted to A via a qualification
4257   //       conversion.
4258   //
4259   // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4260   // both P and A are pointers or member pointers. In this case, we
4261   // just ignore cv-qualifiers completely).
4262   if ((P->isPointerType() && A->isPointerType()) ||
4263       (P->isMemberPointerType() && A->isMemberPointerType()))
4264     TDF |= TDF_IgnoreQualifiers;
4265   if (TemplateDeductionResult Result
4266         = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
4267                                              P, A, Info, Deduced, TDF))
4268     return Result;
4269 
4270   // Create an Instantiation Scope for finalizing the operator.
4271   LocalInstantiationScope InstScope(*this);
4272   // Finish template argument deduction.
4273   FunctionDecl *ConversionSpecialized = nullptr;
4274   TemplateDeductionResult Result
4275       = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
4276                                         ConversionSpecialized, Info);
4277   Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
4278   return Result;
4279 }
4280 
4281 /// Deduce template arguments for a function template when there is
4282 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
4283 ///
4284 /// \param FunctionTemplate the function template for which we are performing
4285 /// template argument deduction.
4286 ///
4287 /// \param ExplicitTemplateArgs the explicitly-specified template
4288 /// arguments.
4289 ///
4290 /// \param Specialization if template argument deduction was successful,
4291 /// this will be set to the function template specialization produced by
4292 /// template argument deduction.
4293 ///
4294 /// \param Info the argument will be updated to provide additional information
4295 /// about template argument deduction.
4296 ///
4297 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4298 /// the address of a function template in a context where we do not have a
4299 /// target type, per [over.over]. If \c false, we are looking up a function
4300 /// template specialization based on its signature, which only happens when
4301 /// deducing a function parameter type from an argument that is a template-id
4302 /// naming a function template specialization.
4303 ///
4304 /// \returns the result of template argument deduction.
4305 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4306     FunctionTemplateDecl *FunctionTemplate,
4307     TemplateArgumentListInfo *ExplicitTemplateArgs,
4308     FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4309     bool IsAddressOfFunction) {
4310   return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
4311                                  QualType(), Specialization, Info,
4312                                  IsAddressOfFunction);
4313 }
4314 
4315 namespace {
4316   struct DependentAuto { bool IsPack; };
4317 
4318   /// Substitute the 'auto' specifier or deduced template specialization type
4319   /// specifier within a type for a given replacement type.
4320   class SubstituteDeducedTypeTransform :
4321       public TreeTransform<SubstituteDeducedTypeTransform> {
4322     QualType Replacement;
4323     bool ReplacementIsPack;
4324     bool UseTypeSugar;
4325 
4326   public:
4327     SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
4328         : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef), Replacement(),
4329           ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
4330 
4331     SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4332                                    bool UseTypeSugar = true)
4333         : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4334           Replacement(Replacement), ReplacementIsPack(false),
4335           UseTypeSugar(UseTypeSugar) {}
4336 
4337     QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4338       assert(isa<TemplateTypeParmType>(Replacement) &&
4339              "unexpected unsugared replacement kind");
4340       QualType Result = Replacement;
4341       TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
4342       NewTL.setNameLoc(TL.getNameLoc());
4343       return Result;
4344     }
4345 
4346     QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4347       // If we're building the type pattern to deduce against, don't wrap the
4348       // substituted type in an AutoType. Certain template deduction rules
4349       // apply only when a template type parameter appears directly (and not if
4350       // the parameter is found through desugaring). For instance:
4351       //   auto &&lref = lvalue;
4352       // must transform into "rvalue reference to T" not "rvalue reference to
4353       // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
4354       //
4355       // FIXME: Is this still necessary?
4356       if (!UseTypeSugar)
4357         return TransformDesugared(TLB, TL);
4358 
4359       QualType Result = SemaRef.Context.getAutoType(
4360           Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
4361           ReplacementIsPack);
4362       auto NewTL = TLB.push<AutoTypeLoc>(Result);
4363       NewTL.setNameLoc(TL.getNameLoc());
4364       return Result;
4365     }
4366 
4367     QualType TransformDeducedTemplateSpecializationType(
4368         TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
4369       if (!UseTypeSugar)
4370         return TransformDesugared(TLB, TL);
4371 
4372       QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
4373           TL.getTypePtr()->getTemplateName(),
4374           Replacement, Replacement.isNull());
4375       auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
4376       NewTL.setNameLoc(TL.getNameLoc());
4377       return Result;
4378     }
4379 
4380     ExprResult TransformLambdaExpr(LambdaExpr *E) {
4381       // Lambdas never need to be transformed.
4382       return E;
4383     }
4384 
4385     QualType Apply(TypeLoc TL) {
4386       // Create some scratch storage for the transformed type locations.
4387       // FIXME: We're just going to throw this information away. Don't build it.
4388       TypeLocBuilder TLB;
4389       TLB.reserve(TL.getFullDataSize());
4390       return TransformType(TLB, TL);
4391     }
4392   };
4393 
4394 } // namespace
4395 
4396 Sema::DeduceAutoResult
4397 Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4398                      Optional<unsigned> DependentDeductionDepth) {
4399   return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4400                         DependentDeductionDepth);
4401 }
4402 
4403 /// Attempt to produce an informative diagostic explaining why auto deduction
4404 /// failed.
4405 /// \return \c true if diagnosed, \c false if not.
4406 static bool diagnoseAutoDeductionFailure(Sema &S,
4407                                          Sema::TemplateDeductionResult TDK,
4408                                          TemplateDeductionInfo &Info,
4409                                          ArrayRef<SourceRange> Ranges) {
4410   switch (TDK) {
4411   case Sema::TDK_Inconsistent: {
4412     // Inconsistent deduction means we were deducing from an initializer list.
4413     auto D = S.Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction);
4414     D << Info.FirstArg << Info.SecondArg;
4415     for (auto R : Ranges)
4416       D << R;
4417     return true;
4418   }
4419 
4420   // FIXME: Are there other cases for which a custom diagnostic is more useful
4421   // than the basic "types don't match" diagnostic?
4422 
4423   default:
4424     return false;
4425   }
4426 }
4427 
4428 /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
4429 ///
4430 /// Note that this is done even if the initializer is dependent. (This is
4431 /// necessary to support partial ordering of templates using 'auto'.)
4432 /// A dependent type will be produced when deducing from a dependent type.
4433 ///
4434 /// \param Type the type pattern using the auto type-specifier.
4435 /// \param Init the initializer for the variable whose type is to be deduced.
4436 /// \param Result if type deduction was successful, this will be set to the
4437 ///        deduced type.
4438 /// \param DependentDeductionDepth Set if we should permit deduction in
4439 ///        dependent cases. This is necessary for template partial ordering with
4440 ///        'auto' template parameters. The value specified is the template
4441 ///        parameter depth at which we should perform 'auto' deduction.
4442 Sema::DeduceAutoResult
4443 Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4444                      Optional<unsigned> DependentDeductionDepth) {
4445   if (Init->getType()->isNonOverloadPlaceholderType()) {
4446     ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4447     if (NonPlaceholder.isInvalid())
4448       return DAR_FailedAlreadyDiagnosed;
4449     Init = NonPlaceholder.get();
4450   }
4451 
4452   DependentAuto DependentResult = {
4453       /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
4454 
4455   if (!DependentDeductionDepth &&
4456       (Type.getType()->isDependentType() || Init->isTypeDependent() ||
4457        Init->containsUnexpandedParameterPack())) {
4458     Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
4459     assert(!Result.isNull() && "substituting DependentTy can't fail");
4460     return DAR_Succeeded;
4461   }
4462 
4463   // Find the depth of template parameter to synthesize.
4464   unsigned Depth = DependentDeductionDepth.getValueOr(0);
4465 
4466   // If this is a 'decltype(auto)' specifier, do the decltype dance.
4467   // Since 'decltype(auto)' can only occur at the top of the type, we
4468   // don't need to go digging for it.
4469   if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
4470     if (AT->isDecltypeAuto()) {
4471       if (isa<InitListExpr>(Init)) {
4472         Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
4473         return DAR_FailedAlreadyDiagnosed;
4474       }
4475 
4476       ExprResult ER = CheckPlaceholderExpr(Init);
4477       if (ER.isInvalid())
4478         return DAR_FailedAlreadyDiagnosed;
4479       Init = ER.get();
4480       QualType Deduced = BuildDecltypeType(Init, Init->getBeginLoc(), false);
4481       if (Deduced.isNull())
4482         return DAR_FailedAlreadyDiagnosed;
4483       // FIXME: Support a non-canonical deduced type for 'auto'.
4484       Deduced = Context.getCanonicalType(Deduced);
4485       Result = SubstituteDeducedTypeTransform(*this, Deduced).Apply(Type);
4486       if (Result.isNull())
4487         return DAR_FailedAlreadyDiagnosed;
4488       return DAR_Succeeded;
4489     } else if (!getLangOpts().CPlusPlus) {
4490       if (isa<InitListExpr>(Init)) {
4491         Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c);
4492         return DAR_FailedAlreadyDiagnosed;
4493       }
4494     }
4495   }
4496 
4497   SourceLocation Loc = Init->getExprLoc();
4498 
4499   LocalInstantiationScope InstScope(*this);
4500 
4501   // Build template<class TemplParam> void Func(FuncParam);
4502   TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4503       Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
4504   QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4505   NamedDecl *TemplParamPtr = TemplParam;
4506   FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4507       Loc, Loc, TemplParamPtr, Loc, nullptr);
4508 
4509   QualType FuncParam =
4510       SubstituteDeducedTypeTransform(*this, TemplArg, /*UseTypeSugar*/false)
4511           .Apply(Type);
4512   assert(!FuncParam.isNull() &&
4513          "substituting template parameter for 'auto' failed");
4514 
4515   // Deduce type of TemplParam in Func(Init)
4516   SmallVector<DeducedTemplateArgument, 1> Deduced;
4517   Deduced.resize(1);
4518 
4519   TemplateDeductionInfo Info(Loc, Depth);
4520 
4521   // If deduction failed, don't diagnose if the initializer is dependent; it
4522   // might acquire a matching type in the instantiation.
4523   auto DeductionFailed = [&](TemplateDeductionResult TDK,
4524                              ArrayRef<SourceRange> Ranges) -> DeduceAutoResult {
4525     if (Init->isTypeDependent()) {
4526       Result =
4527           SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
4528       assert(!Result.isNull() && "substituting DependentTy can't fail");
4529       return DAR_Succeeded;
4530     }
4531     if (diagnoseAutoDeductionFailure(*this, TDK, Info, Ranges))
4532       return DAR_FailedAlreadyDiagnosed;
4533     return DAR_Failed;
4534   };
4535 
4536   SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4537 
4538   InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
4539   if (InitList) {
4540     // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce
4541     // against that. Such deduction only succeeds if removing cv-qualifiers and
4542     // references results in std::initializer_list<T>.
4543     if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
4544       return DAR_Failed;
4545 
4546     // Resolving a core issue: a braced-init-list containing any designators is
4547     // a non-deduced context.
4548     for (Expr *E : InitList->inits())
4549       if (isa<DesignatedInitExpr>(E))
4550         return DAR_Failed;
4551 
4552     SourceRange DeducedFromInitRange;
4553     for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
4554       Expr *Init = InitList->getInit(i);
4555 
4556       if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
4557               *this, TemplateParamsSt.get(), 0, TemplArg, Init,
4558               Info, Deduced, OriginalCallArgs, /*Decomposed*/ true,
4559               /*ArgIdx*/ 0, /*TDF*/ 0))
4560         return DeductionFailed(TDK, {DeducedFromInitRange,
4561                                      Init->getSourceRange()});
4562 
4563       if (DeducedFromInitRange.isInvalid() &&
4564           Deduced[0].getKind() != TemplateArgument::Null)
4565         DeducedFromInitRange = Init->getSourceRange();
4566     }
4567   } else {
4568     if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4569       Diag(Loc, diag::err_auto_bitfield);
4570       return DAR_FailedAlreadyDiagnosed;
4571     }
4572 
4573     if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
4574             *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced,
4575             OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0))
4576       return DeductionFailed(TDK, {});
4577   }
4578 
4579   // Could be null if somehow 'auto' appears in a non-deduced context.
4580   if (Deduced[0].getKind() != TemplateArgument::Type)
4581     return DeductionFailed(TDK_Incomplete, {});
4582 
4583   QualType DeducedType = Deduced[0].getAsType();
4584 
4585   if (InitList) {
4586     DeducedType = BuildStdInitializerList(DeducedType, Loc);
4587     if (DeducedType.isNull())
4588       return DAR_FailedAlreadyDiagnosed;
4589   }
4590 
4591   Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
4592   if (Result.isNull())
4593     return DAR_FailedAlreadyDiagnosed;
4594 
4595   // Check that the deduced argument type is compatible with the original
4596   // argument type per C++ [temp.deduct.call]p4.
4597   QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
4598   for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
4599     assert((bool)InitList == OriginalArg.DecomposedParam &&
4600            "decomposed non-init-list in auto deduction?");
4601     if (auto TDK =
4602             CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA)) {
4603       Result = QualType();
4604       return DeductionFailed(TDK, {});
4605     }
4606   }
4607 
4608   return DAR_Succeeded;
4609 }
4610 
4611 QualType Sema::SubstAutoType(QualType TypeWithAuto,
4612                              QualType TypeToReplaceAuto) {
4613   if (TypeToReplaceAuto->isDependentType())
4614     return SubstituteDeducedTypeTransform(
4615                *this, DependentAuto{
4616                           TypeToReplaceAuto->containsUnexpandedParameterPack()})
4617         .TransformType(TypeWithAuto);
4618   return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
4619       .TransformType(TypeWithAuto);
4620 }
4621 
4622 TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4623                                               QualType TypeToReplaceAuto) {
4624   if (TypeToReplaceAuto->isDependentType())
4625     return SubstituteDeducedTypeTransform(
4626                *this,
4627                DependentAuto{
4628                    TypeToReplaceAuto->containsUnexpandedParameterPack()})
4629         .TransformType(TypeWithAuto);
4630   return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
4631       .TransformType(TypeWithAuto);
4632 }
4633 
4634 QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
4635                                QualType TypeToReplaceAuto) {
4636   return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
4637                                         /*UseTypeSugar*/ false)
4638       .TransformType(TypeWithAuto);
4639 }
4640 
4641 void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4642   if (isa<InitListExpr>(Init))
4643     Diag(VDecl->getLocation(),
4644          VDecl->isInitCapture()
4645              ? diag::err_init_capture_deduction_failure_from_init_list
4646              : diag::err_auto_var_deduction_failure_from_init_list)
4647       << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4648   else
4649     Diag(VDecl->getLocation(),
4650          VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4651                                 : diag::err_auto_var_deduction_failure)
4652       << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4653       << Init->getSourceRange();
4654 }
4655 
4656 bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4657                             bool Diagnose) {
4658   assert(FD->getReturnType()->isUndeducedType());
4659 
4660   // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
4661   // within the return type from the call operator's type.
4662   if (isLambdaConversionOperator(FD)) {
4663     CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
4664     FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
4665 
4666     // For a generic lambda, instantiate the call operator if needed.
4667     if (auto *Args = FD->getTemplateSpecializationArgs()) {
4668       CallOp = InstantiateFunctionDeclaration(
4669           CallOp->getDescribedFunctionTemplate(), Args, Loc);
4670       if (!CallOp || CallOp->isInvalidDecl())
4671         return true;
4672 
4673       // We might need to deduce the return type by instantiating the definition
4674       // of the operator() function.
4675       if (CallOp->getReturnType()->isUndeducedType()) {
4676         runWithSufficientStackSpace(Loc, [&] {
4677           InstantiateFunctionDefinition(Loc, CallOp);
4678         });
4679       }
4680     }
4681 
4682     if (CallOp->isInvalidDecl())
4683       return true;
4684     assert(!CallOp->getReturnType()->isUndeducedType() &&
4685            "failed to deduce lambda return type");
4686 
4687     // Build the new return type from scratch.
4688     QualType RetType = getLambdaConversionFunctionResultType(
4689         CallOp->getType()->castAs<FunctionProtoType>());
4690     if (FD->getReturnType()->getAs<PointerType>())
4691       RetType = Context.getPointerType(RetType);
4692     else {
4693       assert(FD->getReturnType()->getAs<BlockPointerType>());
4694       RetType = Context.getBlockPointerType(RetType);
4695     }
4696     Context.adjustDeducedFunctionResultType(FD, RetType);
4697     return false;
4698   }
4699 
4700   if (FD->getTemplateInstantiationPattern()) {
4701     runWithSufficientStackSpace(Loc, [&] {
4702       InstantiateFunctionDefinition(Loc, FD);
4703     });
4704   }
4705 
4706   bool StillUndeduced = FD->getReturnType()->isUndeducedType();
4707   if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4708     Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4709     Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4710   }
4711 
4712   return StillUndeduced;
4713 }
4714 
4715 /// If this is a non-static member function,
4716 static void
4717 AddImplicitObjectParameterType(ASTContext &Context,
4718                                CXXMethodDecl *Method,
4719                                SmallVectorImpl<QualType> &ArgTypes) {
4720   // C++11 [temp.func.order]p3:
4721   //   [...] The new parameter is of type "reference to cv A," where cv are
4722   //   the cv-qualifiers of the function template (if any) and A is
4723   //   the class of which the function template is a member.
4724   //
4725   // The standard doesn't say explicitly, but we pick the appropriate kind of
4726   // reference type based on [over.match.funcs]p4.
4727   QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4728   ArgTy = Context.getQualifiedType(ArgTy, Method->getMethodQualifiers());
4729   if (Method->getRefQualifier() == RQ_RValue)
4730     ArgTy = Context.getRValueReferenceType(ArgTy);
4731   else
4732     ArgTy = Context.getLValueReferenceType(ArgTy);
4733   ArgTypes.push_back(ArgTy);
4734 }
4735 
4736 /// Determine whether the function template \p FT1 is at least as
4737 /// specialized as \p FT2.
4738 static bool isAtLeastAsSpecializedAs(Sema &S,
4739                                      SourceLocation Loc,
4740                                      FunctionTemplateDecl *FT1,
4741                                      FunctionTemplateDecl *FT2,
4742                                      TemplatePartialOrderingContext TPOC,
4743                                      unsigned NumCallArguments1) {
4744   FunctionDecl *FD1 = FT1->getTemplatedDecl();
4745   FunctionDecl *FD2 = FT2->getTemplatedDecl();
4746   const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4747   const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
4748 
4749   assert(Proto1 && Proto2 && "Function templates must have prototypes");
4750   TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
4751   SmallVector<DeducedTemplateArgument, 4> Deduced;
4752   Deduced.resize(TemplateParams->size());
4753 
4754   // C++0x [temp.deduct.partial]p3:
4755   //   The types used to determine the ordering depend on the context in which
4756   //   the partial ordering is done:
4757   TemplateDeductionInfo Info(Loc);
4758   SmallVector<QualType, 4> Args2;
4759   switch (TPOC) {
4760   case TPOC_Call: {
4761     //   - In the context of a function call, the function parameter types are
4762     //     used.
4763     CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4764     CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
4765 
4766     // C++11 [temp.func.order]p3:
4767     //   [...] If only one of the function templates is a non-static
4768     //   member, that function template is considered to have a new
4769     //   first parameter inserted in its function parameter list. The
4770     //   new parameter is of type "reference to cv A," where cv are
4771     //   the cv-qualifiers of the function template (if any) and A is
4772     //   the class of which the function template is a member.
4773     //
4774     // Note that we interpret this to mean "if one of the function
4775     // templates is a non-static member and the other is a non-member";
4776     // otherwise, the ordering rules for static functions against non-static
4777     // functions don't make any sense.
4778     //
4779     // C++98/03 doesn't have this provision but we've extended DR532 to cover
4780     // it as wording was broken prior to it.
4781     SmallVector<QualType, 4> Args1;
4782 
4783     unsigned NumComparedArguments = NumCallArguments1;
4784 
4785     if (!Method2 && Method1 && !Method1->isStatic()) {
4786       // Compare 'this' from Method1 against first parameter from Method2.
4787       AddImplicitObjectParameterType(S.Context, Method1, Args1);
4788       ++NumComparedArguments;
4789     } else if (!Method1 && Method2 && !Method2->isStatic()) {
4790       // Compare 'this' from Method2 against first parameter from Method1.
4791       AddImplicitObjectParameterType(S.Context, Method2, Args2);
4792     }
4793 
4794     Args1.insert(Args1.end(), Proto1->param_type_begin(),
4795                  Proto1->param_type_end());
4796     Args2.insert(Args2.end(), Proto2->param_type_begin(),
4797                  Proto2->param_type_end());
4798 
4799     // C++ [temp.func.order]p5:
4800     //   The presence of unused ellipsis and default arguments has no effect on
4801     //   the partial ordering of function templates.
4802     if (Args1.size() > NumComparedArguments)
4803       Args1.resize(NumComparedArguments);
4804     if (Args2.size() > NumComparedArguments)
4805       Args2.resize(NumComparedArguments);
4806     if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4807                                 Args1.data(), Args1.size(), Info, Deduced,
4808                                 TDF_None, /*PartialOrdering=*/true))
4809       return false;
4810 
4811     break;
4812   }
4813 
4814   case TPOC_Conversion:
4815     //   - In the context of a call to a conversion operator, the return types
4816     //     of the conversion function templates are used.
4817     if (DeduceTemplateArgumentsByTypeMatch(
4818             S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4819             Info, Deduced, TDF_None,
4820             /*PartialOrdering=*/true))
4821       return false;
4822     break;
4823 
4824   case TPOC_Other:
4825     //   - In other contexts (14.6.6.2) the function template's function type
4826     //     is used.
4827     if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4828                                            FD2->getType(), FD1->getType(),
4829                                            Info, Deduced, TDF_None,
4830                                            /*PartialOrdering=*/true))
4831       return false;
4832     break;
4833   }
4834 
4835   // C++0x [temp.deduct.partial]p11:
4836   //   In most cases, all template parameters must have values in order for
4837   //   deduction to succeed, but for partial ordering purposes a template
4838   //   parameter may remain without a value provided it is not used in the
4839   //   types being used for partial ordering. [ Note: a template parameter used
4840   //   in a non-deduced context is considered used. -end note]
4841   unsigned ArgIdx = 0, NumArgs = Deduced.size();
4842   for (; ArgIdx != NumArgs; ++ArgIdx)
4843     if (Deduced[ArgIdx].isNull())
4844       break;
4845 
4846   // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4847   // to substitute the deduced arguments back into the template and check that
4848   // we get the right type.
4849 
4850   if (ArgIdx == NumArgs) {
4851     // All template arguments were deduced. FT1 is at least as specialized
4852     // as FT2.
4853     return true;
4854   }
4855 
4856   // Figure out which template parameters were used.
4857   llvm::SmallBitVector UsedParameters(TemplateParams->size());
4858   switch (TPOC) {
4859   case TPOC_Call:
4860     for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4861       ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
4862                                    TemplateParams->getDepth(),
4863                                    UsedParameters);
4864     break;
4865 
4866   case TPOC_Conversion:
4867     ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4868                                  TemplateParams->getDepth(), UsedParameters);
4869     break;
4870 
4871   case TPOC_Other:
4872     ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
4873                                  TemplateParams->getDepth(),
4874                                  UsedParameters);
4875     break;
4876   }
4877 
4878   for (; ArgIdx != NumArgs; ++ArgIdx)
4879     // If this argument had no value deduced but was used in one of the types
4880     // used for partial ordering, then deduction fails.
4881     if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4882       return false;
4883 
4884   return true;
4885 }
4886 
4887 /// Determine whether this a function template whose parameter-type-list
4888 /// ends with a function parameter pack.
4889 static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4890   FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4891   unsigned NumParams = Function->getNumParams();
4892   if (NumParams == 0)
4893     return false;
4894 
4895   ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4896   if (!Last->isParameterPack())
4897     return false;
4898 
4899   // Make sure that no previous parameter is a parameter pack.
4900   while (--NumParams > 0) {
4901     if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4902       return false;
4903   }
4904 
4905   return true;
4906 }
4907 
4908 /// Returns the more specialized function template according
4909 /// to the rules of function template partial ordering (C++ [temp.func.order]).
4910 ///
4911 /// \param FT1 the first function template
4912 ///
4913 /// \param FT2 the second function template
4914 ///
4915 /// \param TPOC the context in which we are performing partial ordering of
4916 /// function templates.
4917 ///
4918 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
4919 /// only when \c TPOC is \c TPOC_Call.
4920 ///
4921 /// \param NumCallArguments2 The number of arguments in the call to FT2, used
4922 /// only when \c TPOC is \c TPOC_Call.
4923 ///
4924 /// \returns the more specialized function template. If neither
4925 /// template is more specialized, returns NULL.
4926 FunctionTemplateDecl *
4927 Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4928                                  FunctionTemplateDecl *FT2,
4929                                  SourceLocation Loc,
4930                                  TemplatePartialOrderingContext TPOC,
4931                                  unsigned NumCallArguments1,
4932                                  unsigned NumCallArguments2) {
4933   bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
4934                                           NumCallArguments1);
4935   bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
4936                                           NumCallArguments2);
4937 
4938   if (Better1 != Better2) // We have a clear winner
4939     return Better1 ? FT1 : FT2;
4940 
4941   if (!Better1 && !Better2) // Neither is better than the other
4942     return nullptr;
4943 
4944   // FIXME: This mimics what GCC implements, but doesn't match up with the
4945   // proposed resolution for core issue 692. This area needs to be sorted out,
4946   // but for now we attempt to maintain compatibility.
4947   bool Variadic1 = isVariadicFunctionTemplate(FT1);
4948   bool Variadic2 = isVariadicFunctionTemplate(FT2);
4949   if (Variadic1 != Variadic2)
4950     return Variadic1? FT2 : FT1;
4951 
4952   return nullptr;
4953 }
4954 
4955 /// Determine if the two templates are equivalent.
4956 static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4957   if (T1 == T2)
4958     return true;
4959 
4960   if (!T1 || !T2)
4961     return false;
4962 
4963   return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4964 }
4965 
4966 /// Retrieve the most specialized of the given function template
4967 /// specializations.
4968 ///
4969 /// \param SpecBegin the start iterator of the function template
4970 /// specializations that we will be comparing.
4971 ///
4972 /// \param SpecEnd the end iterator of the function template
4973 /// specializations, paired with \p SpecBegin.
4974 ///
4975 /// \param Loc the location where the ambiguity or no-specializations
4976 /// diagnostic should occur.
4977 ///
4978 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
4979 /// no matching candidates.
4980 ///
4981 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4982 /// occurs.
4983 ///
4984 /// \param CandidateDiag partial diagnostic used for each function template
4985 /// specialization that is a candidate in the ambiguous ordering. One parameter
4986 /// in this diagnostic should be unbound, which will correspond to the string
4987 /// describing the template arguments for the function template specialization.
4988 ///
4989 /// \returns the most specialized function template specialization, if
4990 /// found. Otherwise, returns SpecEnd.
4991 UnresolvedSetIterator Sema::getMostSpecialized(
4992     UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4993     TemplateSpecCandidateSet &FailedCandidates,
4994     SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4995     const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4996     bool Complain, QualType TargetType) {
4997   if (SpecBegin == SpecEnd) {
4998     if (Complain) {
4999       Diag(Loc, NoneDiag);
5000       FailedCandidates.NoteCandidates(*this, Loc);
5001     }
5002     return SpecEnd;
5003   }
5004 
5005   if (SpecBegin + 1 == SpecEnd)
5006     return SpecBegin;
5007 
5008   // Find the function template that is better than all of the templates it
5009   // has been compared to.
5010   UnresolvedSetIterator Best = SpecBegin;
5011   FunctionTemplateDecl *BestTemplate
5012     = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
5013   assert(BestTemplate && "Not a function template specialization?");
5014   for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
5015     FunctionTemplateDecl *Challenger
5016       = cast<FunctionDecl>(*I)->getPrimaryTemplate();
5017     assert(Challenger && "Not a function template specialization?");
5018     if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
5019                                                   Loc, TPOC_Other, 0, 0),
5020                        Challenger)) {
5021       Best = I;
5022       BestTemplate = Challenger;
5023     }
5024   }
5025 
5026   // Make sure that the "best" function template is more specialized than all
5027   // of the others.
5028   bool Ambiguous = false;
5029   for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
5030     FunctionTemplateDecl *Challenger
5031       = cast<FunctionDecl>(*I)->getPrimaryTemplate();
5032     if (I != Best &&
5033         !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
5034                                                    Loc, TPOC_Other, 0, 0),
5035                         BestTemplate)) {
5036       Ambiguous = true;
5037       break;
5038     }
5039   }
5040 
5041   if (!Ambiguous) {
5042     // We found an answer. Return it.
5043     return Best;
5044   }
5045 
5046   // Diagnose the ambiguity.
5047   if (Complain) {
5048     Diag(Loc, AmbigDiag);
5049 
5050     // FIXME: Can we order the candidates in some sane way?
5051     for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
5052       PartialDiagnostic PD = CandidateDiag;
5053       const auto *FD = cast<FunctionDecl>(*I);
5054       PD << FD << getTemplateArgumentBindingsText(
5055                       FD->getPrimaryTemplate()->getTemplateParameters(),
5056                       *FD->getTemplateSpecializationArgs());
5057       if (!TargetType.isNull())
5058         HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
5059       Diag((*I)->getLocation(), PD);
5060     }
5061   }
5062 
5063   return SpecEnd;
5064 }
5065 
5066 /// Determine whether one partial specialization, P1, is at least as
5067 /// specialized than another, P2.
5068 ///
5069 /// \tparam TemplateLikeDecl The kind of P2, which must be a
5070 /// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
5071 /// \param T1 The injected-class-name of P1 (faked for a variable template).
5072 /// \param T2 The injected-class-name of P2 (faked for a variable template).
5073 template<typename TemplateLikeDecl>
5074 static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
5075                                      TemplateLikeDecl *P2,
5076                                      TemplateDeductionInfo &Info) {
5077   // TODO: Concepts: Regard constraints
5078   // C++ [temp.class.order]p1:
5079   //   For two class template partial specializations, the first is at least as
5080   //   specialized as the second if, given the following rewrite to two
5081   //   function templates, the first function template is at least as
5082   //   specialized as the second according to the ordering rules for function
5083   //   templates (14.6.6.2):
5084   //     - the first function template has the same template parameters as the
5085   //       first partial specialization and has a single function parameter
5086   //       whose type is a class template specialization with the template
5087   //       arguments of the first partial specialization, and
5088   //     - the second function template has the same template parameters as the
5089   //       second partial specialization and has a single function parameter
5090   //       whose type is a class template specialization with the template
5091   //       arguments of the second partial specialization.
5092   //
5093   // Rather than synthesize function templates, we merely perform the
5094   // equivalent partial ordering by performing deduction directly on
5095   // the template arguments of the class template partial
5096   // specializations. This computation is slightly simpler than the
5097   // general problem of function template partial ordering, because
5098   // class template partial specializations are more constrained. We
5099   // know that every template parameter is deducible from the class
5100   // template partial specialization's template arguments, for
5101   // example.
5102   SmallVector<DeducedTemplateArgument, 4> Deduced;
5103 
5104   // Determine whether P1 is at least as specialized as P2.
5105   Deduced.resize(P2->getTemplateParameters()->size());
5106   if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
5107                                          T2, T1, Info, Deduced, TDF_None,
5108                                          /*PartialOrdering=*/true))
5109     return false;
5110 
5111   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
5112                                                Deduced.end());
5113   Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
5114                                    Info);
5115   auto *TST1 = T1->castAs<TemplateSpecializationType>();
5116   if (FinishTemplateArgumentDeduction(
5117           S, P2, /*IsPartialOrdering=*/true,
5118           TemplateArgumentList(TemplateArgumentList::OnStack,
5119                                TST1->template_arguments()),
5120           Deduced, Info))
5121     return false;
5122 
5123   return true;
5124 }
5125 
5126 /// Returns the more specialized class template partial specialization
5127 /// according to the rules of partial ordering of class template partial
5128 /// specializations (C++ [temp.class.order]).
5129 ///
5130 /// \param PS1 the first class template partial specialization
5131 ///
5132 /// \param PS2 the second class template partial specialization
5133 ///
5134 /// \returns the more specialized class template partial specialization. If
5135 /// neither partial specialization is more specialized, returns NULL.
5136 ClassTemplatePartialSpecializationDecl *
5137 Sema::getMoreSpecializedPartialSpecialization(
5138                                   ClassTemplatePartialSpecializationDecl *PS1,
5139                                   ClassTemplatePartialSpecializationDecl *PS2,
5140                                               SourceLocation Loc) {
5141   QualType PT1 = PS1->getInjectedSpecializationType();
5142   QualType PT2 = PS2->getInjectedSpecializationType();
5143 
5144   TemplateDeductionInfo Info(Loc);
5145   bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
5146   bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
5147 
5148   if (Better1 == Better2)
5149     return nullptr;
5150 
5151   return Better1 ? PS1 : PS2;
5152 }
5153 
5154 bool Sema::isMoreSpecializedThanPrimary(
5155     ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
5156   ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
5157   QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
5158   QualType PartialT = Spec->getInjectedSpecializationType();
5159   if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
5160     return false;
5161   if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
5162     Info.clearSFINAEDiagnostic();
5163     return false;
5164   }
5165   return true;
5166 }
5167 
5168 VarTemplatePartialSpecializationDecl *
5169 Sema::getMoreSpecializedPartialSpecialization(
5170     VarTemplatePartialSpecializationDecl *PS1,
5171     VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
5172   // Pretend the variable template specializations are class template
5173   // specializations and form a fake injected class name type for comparison.
5174   assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
5175          "the partial specializations being compared should specialize"
5176          " the same template.");
5177   TemplateName Name(PS1->getSpecializedTemplate());
5178   TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
5179   QualType PT1 = Context.getTemplateSpecializationType(
5180       CanonTemplate, PS1->getTemplateArgs().asArray());
5181   QualType PT2 = Context.getTemplateSpecializationType(
5182       CanonTemplate, PS2->getTemplateArgs().asArray());
5183 
5184   TemplateDeductionInfo Info(Loc);
5185   bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
5186   bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
5187 
5188   if (Better1 == Better2)
5189     return nullptr;
5190 
5191   return Better1 ? PS1 : PS2;
5192 }
5193 
5194 bool Sema::isMoreSpecializedThanPrimary(
5195     VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
5196   TemplateDecl *Primary = Spec->getSpecializedTemplate();
5197   // FIXME: Cache the injected template arguments rather than recomputing
5198   // them for each partial specialization.
5199   SmallVector<TemplateArgument, 8> PrimaryArgs;
5200   Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
5201                                   PrimaryArgs);
5202 
5203   TemplateName CanonTemplate =
5204       Context.getCanonicalTemplateName(TemplateName(Primary));
5205   QualType PrimaryT = Context.getTemplateSpecializationType(
5206       CanonTemplate, PrimaryArgs);
5207   QualType PartialT = Context.getTemplateSpecializationType(
5208       CanonTemplate, Spec->getTemplateArgs().asArray());
5209   if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
5210     return false;
5211   if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
5212     Info.clearSFINAEDiagnostic();
5213     return false;
5214   }
5215   return true;
5216 }
5217 
5218 bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
5219      TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
5220   // C++1z [temp.arg.template]p4: (DR 150)
5221   //   A template template-parameter P is at least as specialized as a
5222   //   template template-argument A if, given the following rewrite to two
5223   //   function templates...
5224 
5225   // Rather than synthesize function templates, we merely perform the
5226   // equivalent partial ordering by performing deduction directly on
5227   // the template parameter lists of the template template parameters.
5228   //
5229   //   Given an invented class template X with the template parameter list of
5230   //   A (including default arguments):
5231   TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
5232   TemplateParameterList *A = AArg->getTemplateParameters();
5233 
5234   //    - Each function template has a single function parameter whose type is
5235   //      a specialization of X with template arguments corresponding to the
5236   //      template parameters from the respective function template
5237   SmallVector<TemplateArgument, 8> AArgs;
5238   Context.getInjectedTemplateArgs(A, AArgs);
5239 
5240   // Check P's arguments against A's parameter list. This will fill in default
5241   // template arguments as needed. AArgs are already correct by construction.
5242   // We can't just use CheckTemplateIdType because that will expand alias
5243   // templates.
5244   SmallVector<TemplateArgument, 4> PArgs;
5245   {
5246     SFINAETrap Trap(*this);
5247 
5248     Context.getInjectedTemplateArgs(P, PArgs);
5249     TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
5250     for (unsigned I = 0, N = P->size(); I != N; ++I) {
5251       // Unwrap packs that getInjectedTemplateArgs wrapped around pack
5252       // expansions, to form an "as written" argument list.
5253       TemplateArgument Arg = PArgs[I];
5254       if (Arg.getKind() == TemplateArgument::Pack) {
5255         assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
5256         Arg = *Arg.pack_begin();
5257       }
5258       PArgList.addArgument(getTrivialTemplateArgumentLoc(
5259           Arg, QualType(), P->getParam(I)->getLocation()));
5260     }
5261     PArgs.clear();
5262 
5263     // C++1z [temp.arg.template]p3:
5264     //   If the rewrite produces an invalid type, then P is not at least as
5265     //   specialized as A.
5266     if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
5267         Trap.hasErrorOccurred())
5268       return false;
5269   }
5270 
5271   QualType AType = Context.getTemplateSpecializationType(X, AArgs);
5272   QualType PType = Context.getTemplateSpecializationType(X, PArgs);
5273 
5274   //   ... the function template corresponding to P is at least as specialized
5275   //   as the function template corresponding to A according to the partial
5276   //   ordering rules for function templates.
5277   TemplateDeductionInfo Info(Loc, A->getDepth());
5278   return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
5279 }
5280 
5281 /// Mark the template parameters that are used by the given
5282 /// expression.
5283 static void
5284 MarkUsedTemplateParameters(ASTContext &Ctx,
5285                            const Expr *E,
5286                            bool OnlyDeduced,
5287                            unsigned Depth,
5288                            llvm::SmallBitVector &Used) {
5289   // We can deduce from a pack expansion.
5290   if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
5291     E = Expansion->getPattern();
5292 
5293   // Skip through any implicit casts we added while type-checking, and any
5294   // substitutions performed by template alias expansion.
5295   while (true) {
5296     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
5297       E = ICE->getSubExpr();
5298     else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(E))
5299       E = CE->getSubExpr();
5300     else if (const SubstNonTypeTemplateParmExpr *Subst =
5301                dyn_cast<SubstNonTypeTemplateParmExpr>(E))
5302       E = Subst->getReplacement();
5303     else
5304       break;
5305   }
5306 
5307   // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
5308   // find other occurrences of template parameters.
5309   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
5310   if (!DRE)
5311     return;
5312 
5313   const NonTypeTemplateParmDecl *NTTP
5314     = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
5315   if (!NTTP)
5316     return;
5317 
5318   if (NTTP->getDepth() == Depth)
5319     Used[NTTP->getIndex()] = true;
5320 
5321   // In C++17 mode, additional arguments may be deduced from the type of a
5322   // non-type argument.
5323   if (Ctx.getLangOpts().CPlusPlus17)
5324     MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
5325 }
5326 
5327 /// Mark the template parameters that are used by the given
5328 /// nested name specifier.
5329 static void
5330 MarkUsedTemplateParameters(ASTContext &Ctx,
5331                            NestedNameSpecifier *NNS,
5332                            bool OnlyDeduced,
5333                            unsigned Depth,
5334                            llvm::SmallBitVector &Used) {
5335   if (!NNS)
5336     return;
5337 
5338   MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
5339                              Used);
5340   MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
5341                              OnlyDeduced, Depth, Used);
5342 }
5343 
5344 /// Mark the template parameters that are used by the given
5345 /// template name.
5346 static void
5347 MarkUsedTemplateParameters(ASTContext &Ctx,
5348                            TemplateName Name,
5349                            bool OnlyDeduced,
5350                            unsigned Depth,
5351                            llvm::SmallBitVector &Used) {
5352   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
5353     if (TemplateTemplateParmDecl *TTP
5354           = dyn_cast<TemplateTemplateParmDecl>(Template)) {
5355       if (TTP->getDepth() == Depth)
5356         Used[TTP->getIndex()] = true;
5357     }
5358     return;
5359   }
5360 
5361   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
5362     MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
5363                                Depth, Used);
5364   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
5365     MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
5366                                Depth, Used);
5367 }
5368 
5369 /// Mark the template parameters that are used by the given
5370 /// type.
5371 static void
5372 MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
5373                            bool OnlyDeduced,
5374                            unsigned Depth,
5375                            llvm::SmallBitVector &Used) {
5376   if (T.isNull())
5377     return;
5378 
5379   // Non-dependent types have nothing deducible
5380   if (!T->isDependentType())
5381     return;
5382 
5383   T = Ctx.getCanonicalType(T);
5384   switch (T->getTypeClass()) {
5385   case Type::Pointer:
5386     MarkUsedTemplateParameters(Ctx,
5387                                cast<PointerType>(T)->getPointeeType(),
5388                                OnlyDeduced,
5389                                Depth,
5390                                Used);
5391     break;
5392 
5393   case Type::BlockPointer:
5394     MarkUsedTemplateParameters(Ctx,
5395                                cast<BlockPointerType>(T)->getPointeeType(),
5396                                OnlyDeduced,
5397                                Depth,
5398                                Used);
5399     break;
5400 
5401   case Type::LValueReference:
5402   case Type::RValueReference:
5403     MarkUsedTemplateParameters(Ctx,
5404                                cast<ReferenceType>(T)->getPointeeType(),
5405                                OnlyDeduced,
5406                                Depth,
5407                                Used);
5408     break;
5409 
5410   case Type::MemberPointer: {
5411     const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
5412     MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
5413                                Depth, Used);
5414     MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
5415                                OnlyDeduced, Depth, Used);
5416     break;
5417   }
5418 
5419   case Type::DependentSizedArray:
5420     MarkUsedTemplateParameters(Ctx,
5421                                cast<DependentSizedArrayType>(T)->getSizeExpr(),
5422                                OnlyDeduced, Depth, Used);
5423     // Fall through to check the element type
5424     LLVM_FALLTHROUGH;
5425 
5426   case Type::ConstantArray:
5427   case Type::IncompleteArray:
5428     MarkUsedTemplateParameters(Ctx,
5429                                cast<ArrayType>(T)->getElementType(),
5430                                OnlyDeduced, Depth, Used);
5431     break;
5432 
5433   case Type::Vector:
5434   case Type::ExtVector:
5435     MarkUsedTemplateParameters(Ctx,
5436                                cast<VectorType>(T)->getElementType(),
5437                                OnlyDeduced, Depth, Used);
5438     break;
5439 
5440   case Type::DependentVector: {
5441     const auto *VecType = cast<DependentVectorType>(T);
5442     MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
5443                                Depth, Used);
5444     MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
5445                                Used);
5446     break;
5447   }
5448   case Type::DependentSizedExtVector: {
5449     const DependentSizedExtVectorType *VecType
5450       = cast<DependentSizedExtVectorType>(T);
5451     MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
5452                                Depth, Used);
5453     MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
5454                                Depth, Used);
5455     break;
5456   }
5457 
5458   case Type::DependentAddressSpace: {
5459     const DependentAddressSpaceType *DependentASType =
5460         cast<DependentAddressSpaceType>(T);
5461     MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
5462                                OnlyDeduced, Depth, Used);
5463     MarkUsedTemplateParameters(Ctx,
5464                                DependentASType->getAddrSpaceExpr(),
5465                                OnlyDeduced, Depth, Used);
5466     break;
5467   }
5468 
5469   case Type::FunctionProto: {
5470     const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
5471     MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
5472                                Used);
5473     for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
5474       // C++17 [temp.deduct.type]p5:
5475       //   The non-deduced contexts are: [...]
5476       //   -- A function parameter pack that does not occur at the end of the
5477       //      parameter-declaration-list.
5478       if (!OnlyDeduced || I + 1 == N ||
5479           !Proto->getParamType(I)->getAs<PackExpansionType>()) {
5480         MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
5481                                    Depth, Used);
5482       } else {
5483         // FIXME: C++17 [temp.deduct.call]p1:
5484         //   When a function parameter pack appears in a non-deduced context,
5485         //   the type of that pack is never deduced.
5486         //
5487         // We should also track a set of "never deduced" parameters, and
5488         // subtract that from the list of deduced parameters after marking.
5489       }
5490     }
5491     if (auto *E = Proto->getNoexceptExpr())
5492       MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
5493     break;
5494   }
5495 
5496   case Type::TemplateTypeParm: {
5497     const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
5498     if (TTP->getDepth() == Depth)
5499       Used[TTP->getIndex()] = true;
5500     break;
5501   }
5502 
5503   case Type::SubstTemplateTypeParmPack: {
5504     const SubstTemplateTypeParmPackType *Subst
5505       = cast<SubstTemplateTypeParmPackType>(T);
5506     MarkUsedTemplateParameters(Ctx,
5507                                QualType(Subst->getReplacedParameter(), 0),
5508                                OnlyDeduced, Depth, Used);
5509     MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
5510                                OnlyDeduced, Depth, Used);
5511     break;
5512   }
5513 
5514   case Type::InjectedClassName:
5515     T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
5516     LLVM_FALLTHROUGH;
5517 
5518   case Type::TemplateSpecialization: {
5519     const TemplateSpecializationType *Spec
5520       = cast<TemplateSpecializationType>(T);
5521     MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
5522                                Depth, Used);
5523 
5524     // C++0x [temp.deduct.type]p9:
5525     //   If the template argument list of P contains a pack expansion that is
5526     //   not the last template argument, the entire template argument list is a
5527     //   non-deduced context.
5528     if (OnlyDeduced &&
5529         hasPackExpansionBeforeEnd(Spec->template_arguments()))
5530       break;
5531 
5532     for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
5533       MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
5534                                  Used);
5535     break;
5536   }
5537 
5538   case Type::Complex:
5539     if (!OnlyDeduced)
5540       MarkUsedTemplateParameters(Ctx,
5541                                  cast<ComplexType>(T)->getElementType(),
5542                                  OnlyDeduced, Depth, Used);
5543     break;
5544 
5545   case Type::Atomic:
5546     if (!OnlyDeduced)
5547       MarkUsedTemplateParameters(Ctx,
5548                                  cast<AtomicType>(T)->getValueType(),
5549                                  OnlyDeduced, Depth, Used);
5550     break;
5551 
5552   case Type::DependentName:
5553     if (!OnlyDeduced)
5554       MarkUsedTemplateParameters(Ctx,
5555                                  cast<DependentNameType>(T)->getQualifier(),
5556                                  OnlyDeduced, Depth, Used);
5557     break;
5558 
5559   case Type::DependentTemplateSpecialization: {
5560     // C++14 [temp.deduct.type]p5:
5561     //   The non-deduced contexts are:
5562     //     -- The nested-name-specifier of a type that was specified using a
5563     //        qualified-id
5564     //
5565     // C++14 [temp.deduct.type]p6:
5566     //   When a type name is specified in a way that includes a non-deduced
5567     //   context, all of the types that comprise that type name are also
5568     //   non-deduced.
5569     if (OnlyDeduced)
5570       break;
5571 
5572     const DependentTemplateSpecializationType *Spec
5573       = cast<DependentTemplateSpecializationType>(T);
5574 
5575     MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5576                                OnlyDeduced, Depth, Used);
5577 
5578     for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
5579       MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
5580                                  Used);
5581     break;
5582   }
5583 
5584   case Type::TypeOf:
5585     if (!OnlyDeduced)
5586       MarkUsedTemplateParameters(Ctx,
5587                                  cast<TypeOfType>(T)->getUnderlyingType(),
5588                                  OnlyDeduced, Depth, Used);
5589     break;
5590 
5591   case Type::TypeOfExpr:
5592     if (!OnlyDeduced)
5593       MarkUsedTemplateParameters(Ctx,
5594                                  cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5595                                  OnlyDeduced, Depth, Used);
5596     break;
5597 
5598   case Type::Decltype:
5599     if (!OnlyDeduced)
5600       MarkUsedTemplateParameters(Ctx,
5601                                  cast<DecltypeType>(T)->getUnderlyingExpr(),
5602                                  OnlyDeduced, Depth, Used);
5603     break;
5604 
5605   case Type::UnaryTransform:
5606     if (!OnlyDeduced)
5607       MarkUsedTemplateParameters(Ctx,
5608                                  cast<UnaryTransformType>(T)->getUnderlyingType(),
5609                                  OnlyDeduced, Depth, Used);
5610     break;
5611 
5612   case Type::PackExpansion:
5613     MarkUsedTemplateParameters(Ctx,
5614                                cast<PackExpansionType>(T)->getPattern(),
5615                                OnlyDeduced, Depth, Used);
5616     break;
5617 
5618   case Type::Auto:
5619   case Type::DeducedTemplateSpecialization:
5620     MarkUsedTemplateParameters(Ctx,
5621                                cast<DeducedType>(T)->getDeducedType(),
5622                                OnlyDeduced, Depth, Used);
5623     break;
5624 
5625   // None of these types have any template parameters in them.
5626   case Type::Builtin:
5627   case Type::VariableArray:
5628   case Type::FunctionNoProto:
5629   case Type::Record:
5630   case Type::Enum:
5631   case Type::ObjCInterface:
5632   case Type::ObjCObject:
5633   case Type::ObjCObjectPointer:
5634   case Type::UnresolvedUsing:
5635   case Type::Pipe:
5636 #define TYPE(Class, Base)
5637 #define ABSTRACT_TYPE(Class, Base)
5638 #define DEPENDENT_TYPE(Class, Base)
5639 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5640 #include "clang/AST/TypeNodes.inc"
5641     break;
5642   }
5643 }
5644 
5645 /// Mark the template parameters that are used by this
5646 /// template argument.
5647 static void
5648 MarkUsedTemplateParameters(ASTContext &Ctx,
5649                            const TemplateArgument &TemplateArg,
5650                            bool OnlyDeduced,
5651                            unsigned Depth,
5652                            llvm::SmallBitVector &Used) {
5653   switch (TemplateArg.getKind()) {
5654   case TemplateArgument::Null:
5655   case TemplateArgument::Integral:
5656   case TemplateArgument::Declaration:
5657     break;
5658 
5659   case TemplateArgument::NullPtr:
5660     MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5661                                Depth, Used);
5662     break;
5663 
5664   case TemplateArgument::Type:
5665     MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
5666                                Depth, Used);
5667     break;
5668 
5669   case TemplateArgument::Template:
5670   case TemplateArgument::TemplateExpansion:
5671     MarkUsedTemplateParameters(Ctx,
5672                                TemplateArg.getAsTemplateOrTemplatePattern(),
5673                                OnlyDeduced, Depth, Used);
5674     break;
5675 
5676   case TemplateArgument::Expression:
5677     MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
5678                                Depth, Used);
5679     break;
5680 
5681   case TemplateArgument::Pack:
5682     for (const auto &P : TemplateArg.pack_elements())
5683       MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
5684     break;
5685   }
5686 }
5687 
5688 /// Mark which template parameters can be deduced from a given
5689 /// template argument list.
5690 ///
5691 /// \param TemplateArgs the template argument list from which template
5692 /// parameters will be deduced.
5693 ///
5694 /// \param Used a bit vector whose elements will be set to \c true
5695 /// to indicate when the corresponding template parameter will be
5696 /// deduced.
5697 void
5698 Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
5699                                  bool OnlyDeduced, unsigned Depth,
5700                                  llvm::SmallBitVector &Used) {
5701   // C++0x [temp.deduct.type]p9:
5702   //   If the template argument list of P contains a pack expansion that is not
5703   //   the last template argument, the entire template argument list is a
5704   //   non-deduced context.
5705   if (OnlyDeduced &&
5706       hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
5707     return;
5708 
5709   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
5710     ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
5711                                  Depth, Used);
5712 }
5713 
5714 /// Marks all of the template parameters that will be deduced by a
5715 /// call to the given function template.
5716 void Sema::MarkDeducedTemplateParameters(
5717     ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5718     llvm::SmallBitVector &Deduced) {
5719   TemplateParameterList *TemplateParams
5720     = FunctionTemplate->getTemplateParameters();
5721   Deduced.clear();
5722   Deduced.resize(TemplateParams->size());
5723 
5724   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5725   for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
5726     ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
5727                                  true, TemplateParams->getDepth(), Deduced);
5728 }
5729 
5730 bool hasDeducibleTemplateParameters(Sema &S,
5731                                     FunctionTemplateDecl *FunctionTemplate,
5732                                     QualType T) {
5733   if (!T->isDependentType())
5734     return false;
5735 
5736   TemplateParameterList *TemplateParams
5737     = FunctionTemplate->getTemplateParameters();
5738   llvm::SmallBitVector Deduced(TemplateParams->size());
5739   ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
5740                                Deduced);
5741 
5742   return Deduced.any();
5743 }
5744