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