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