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