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