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