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