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