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