SemaTemplateDeduction.cpp revision 0972c867e72171f24052d7b6d307020c065f8a66
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/SemaDiagnostic.h" // FIXME: temporary!
16#include "clang/Sema/Template.h"
17#include "clang/Sema/TemplateDeduction.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/StmtVisitor.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include <algorithm>
25
26namespace clang {
27  using namespace sema;
28
29  /// \brief Various flags that control template argument deduction.
30  ///
31  /// These flags can be bitwise-OR'd together.
32  enum TemplateDeductionFlags {
33    /// \brief No template argument deduction flags, which indicates the
34    /// strictest results for template argument deduction (as used for, e.g.,
35    /// matching class template partial specializations).
36    TDF_None = 0,
37    /// \brief Within template argument deduction from a function call, we are
38    /// matching with a parameter type for which the original parameter was
39    /// a reference.
40    TDF_ParamWithReferenceType = 0x1,
41    /// \brief Within template argument deduction from a function call, we
42    /// are matching in a case where we ignore cv-qualifiers.
43    TDF_IgnoreQualifiers = 0x02,
44    /// \brief Within template argument deduction from a function call,
45    /// we are matching in a case where we can perform template argument
46    /// deduction from a template-id of a derived class of the argument type.
47    TDF_DerivedClass = 0x04,
48    /// \brief Allow non-dependent types to differ, e.g., when performing
49    /// template argument deduction from a function call where conversions
50    /// may apply.
51    TDF_SkipNonDependent = 0x08
52  };
53}
54
55using namespace clang;
56
57/// \brief Compare two APSInts, extending and switching the sign as
58/// necessary to compare their values regardless of underlying type.
59static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
60  if (Y.getBitWidth() > X.getBitWidth())
61    X = X.extend(Y.getBitWidth());
62  else if (Y.getBitWidth() < X.getBitWidth())
63    Y = Y.extend(X.getBitWidth());
64
65  // If there is a signedness mismatch, correct it.
66  if (X.isSigned() != Y.isSigned()) {
67    // If the signed value is negative, then the values cannot be the same.
68    if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
69      return false;
70
71    Y.setIsSigned(true);
72    X.setIsSigned(true);
73  }
74
75  return X == Y;
76}
77
78static Sema::TemplateDeductionResult
79DeduceTemplateArguments(Sema &S,
80                        TemplateParameterList *TemplateParams,
81                        const TemplateArgument &Param,
82                        const TemplateArgument &Arg,
83                        TemplateDeductionInfo &Info,
84                      llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced);
85
86static Sema::TemplateDeductionResult
87DeduceTemplateArguments(Sema &S,
88                        TemplateParameterList *TemplateParams,
89                        const TemplateArgument *Params, unsigned NumParams,
90                        const TemplateArgument *Args, unsigned NumArgs,
91                        TemplateDeductionInfo &Info,
92                        llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
93                        bool NumberOfArgumentsMustMatch = true);
94
95/// \brief If the given expression is of a form that permits the deduction
96/// of a non-type template parameter, return the declaration of that
97/// non-type template parameter.
98static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
99  if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
100    E = IC->getSubExpr();
101
102  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
103    return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
104
105  return 0;
106}
107
108/// \brief Deduce the value of the given non-type template parameter
109/// from the given constant.
110static Sema::TemplateDeductionResult
111DeduceNonTypeTemplateArgument(Sema &S,
112                              NonTypeTemplateParmDecl *NTTP,
113                              llvm::APSInt Value, QualType ValueType,
114                              bool DeducedFromArrayBound,
115                              TemplateDeductionInfo &Info,
116                    llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
117  assert(NTTP->getDepth() == 0 &&
118         "Cannot deduce non-type template argument with depth > 0");
119
120  if (Deduced[NTTP->getIndex()].isNull()) {
121    Deduced[NTTP->getIndex()] = DeducedTemplateArgument(Value, ValueType,
122                                                        DeducedFromArrayBound);
123    return Sema::TDK_Success;
124  }
125
126  if (Deduced[NTTP->getIndex()].getKind() != TemplateArgument::Integral) {
127    Info.Param = NTTP;
128    Info.FirstArg = Deduced[NTTP->getIndex()];
129    Info.SecondArg = TemplateArgument(Value, ValueType);
130    return Sema::TDK_Inconsistent;
131  }
132
133  // Extent the smaller of the two values.
134  llvm::APSInt PrevValue = *Deduced[NTTP->getIndex()].getAsIntegral();
135  if (!hasSameExtendedValue(PrevValue, Value)) {
136    Info.Param = NTTP;
137    Info.FirstArg = Deduced[NTTP->getIndex()];
138    Info.SecondArg = TemplateArgument(Value, ValueType);
139    return Sema::TDK_Inconsistent;
140  }
141
142  if (!DeducedFromArrayBound)
143    Deduced[NTTP->getIndex()].setDeducedFromArrayBound(false);
144
145  return Sema::TDK_Success;
146}
147
148/// \brief Deduce the value of the given non-type template parameter
149/// from the given type- or value-dependent expression.
150///
151/// \returns true if deduction succeeded, false otherwise.
152static Sema::TemplateDeductionResult
153DeduceNonTypeTemplateArgument(Sema &S,
154                              NonTypeTemplateParmDecl *NTTP,
155                              Expr *Value,
156                              TemplateDeductionInfo &Info,
157                    llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
158  assert(NTTP->getDepth() == 0 &&
159         "Cannot deduce non-type template argument with depth > 0");
160  assert((Value->isTypeDependent() || Value->isValueDependent()) &&
161         "Expression template argument must be type- or value-dependent.");
162
163  if (Deduced[NTTP->getIndex()].isNull()) {
164    Deduced[NTTP->getIndex()] = TemplateArgument(Value);
165    return Sema::TDK_Success;
166  }
167
168  if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Integral) {
169    // Okay, we deduced a constant in one case and a dependent expression
170    // in another case. FIXME: Later, we will check that instantiating the
171    // dependent expression gives us the constant value.
172    return Sema::TDK_Success;
173  }
174
175  if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Expression) {
176    // Compare the expressions for equality
177    llvm::FoldingSetNodeID ID1, ID2;
178    Deduced[NTTP->getIndex()].getAsExpr()->Profile(ID1, S.Context, true);
179    Value->Profile(ID2, S.Context, true);
180    if (ID1 == ID2)
181      return Sema::TDK_Success;
182
183    // FIXME: Fill in argument mismatch information
184    return Sema::TDK_NonDeducedMismatch;
185  }
186
187  return Sema::TDK_Success;
188}
189
190/// \brief Deduce the value of the given non-type template parameter
191/// from the given declaration.
192///
193/// \returns true if deduction succeeded, false otherwise.
194static Sema::TemplateDeductionResult
195DeduceNonTypeTemplateArgument(Sema &S,
196                              NonTypeTemplateParmDecl *NTTP,
197                              Decl *D,
198                              TemplateDeductionInfo &Info,
199                    llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
200  assert(NTTP->getDepth() == 0 &&
201         "Cannot deduce non-type template argument with depth > 0");
202
203  if (Deduced[NTTP->getIndex()].isNull()) {
204    Deduced[NTTP->getIndex()] = TemplateArgument(D->getCanonicalDecl());
205    return Sema::TDK_Success;
206  }
207
208  if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Expression) {
209    // Okay, we deduced a declaration in one case and a dependent expression
210    // in another case.
211    return Sema::TDK_Success;
212  }
213
214  if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Declaration) {
215    // Compare the declarations for equality
216    if (Deduced[NTTP->getIndex()].getAsDecl()->getCanonicalDecl() ==
217          D->getCanonicalDecl())
218      return Sema::TDK_Success;
219
220    // FIXME: Fill in argument mismatch information
221    return Sema::TDK_NonDeducedMismatch;
222  }
223
224  return Sema::TDK_Success;
225}
226
227static Sema::TemplateDeductionResult
228DeduceTemplateArguments(Sema &S,
229                        TemplateParameterList *TemplateParams,
230                        TemplateName Param,
231                        TemplateName Arg,
232                        TemplateDeductionInfo &Info,
233                    llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
234  TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
235  if (!ParamDecl) {
236    // The parameter type is dependent and is not a template template parameter,
237    // so there is nothing that we can deduce.
238    return Sema::TDK_Success;
239  }
240
241  if (TemplateTemplateParmDecl *TempParam
242        = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
243    // Bind the template template parameter to the given template name.
244    TemplateArgument &ExistingArg = Deduced[TempParam->getIndex()];
245    if (ExistingArg.isNull()) {
246      // This is the first deduction for this template template parameter.
247      ExistingArg = TemplateArgument(S.Context.getCanonicalTemplateName(Arg));
248      return Sema::TDK_Success;
249    }
250
251    // Verify that the previous binding matches this deduction.
252    assert(ExistingArg.getKind() == TemplateArgument::Template);
253    if (S.Context.hasSameTemplateName(ExistingArg.getAsTemplate(), Arg))
254      return Sema::TDK_Success;
255
256    // Inconsistent deduction.
257    Info.Param = TempParam;
258    Info.FirstArg = ExistingArg;
259    Info.SecondArg = TemplateArgument(Arg);
260    return Sema::TDK_Inconsistent;
261  }
262
263  // Verify that the two template names are equivalent.
264  if (S.Context.hasSameTemplateName(Param, Arg))
265    return Sema::TDK_Success;
266
267  // Mismatch of non-dependent template parameter to argument.
268  Info.FirstArg = TemplateArgument(Param);
269  Info.SecondArg = TemplateArgument(Arg);
270  return Sema::TDK_NonDeducedMismatch;
271}
272
273/// \brief Deduce the template arguments by comparing the template parameter
274/// type (which is a template-id) with the template argument type.
275///
276/// \param S the Sema
277///
278/// \param TemplateParams the template parameters that we are deducing
279///
280/// \param Param the parameter type
281///
282/// \param Arg the argument type
283///
284/// \param Info information about the template argument deduction itself
285///
286/// \param Deduced the deduced template arguments
287///
288/// \returns the result of template argument deduction so far. Note that a
289/// "success" result means that template argument deduction has not yet failed,
290/// but it may still fail, later, for other reasons.
291static Sema::TemplateDeductionResult
292DeduceTemplateArguments(Sema &S,
293                        TemplateParameterList *TemplateParams,
294                        const TemplateSpecializationType *Param,
295                        QualType Arg,
296                        TemplateDeductionInfo &Info,
297                    llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
298  assert(Arg.isCanonical() && "Argument type must be canonical");
299
300  // Check whether the template argument is a dependent template-id.
301  if (const TemplateSpecializationType *SpecArg
302        = dyn_cast<TemplateSpecializationType>(Arg)) {
303    // Perform template argument deduction for the template name.
304    if (Sema::TemplateDeductionResult Result
305          = DeduceTemplateArguments(S, TemplateParams,
306                                    Param->getTemplateName(),
307                                    SpecArg->getTemplateName(),
308                                    Info, Deduced))
309      return Result;
310
311
312    // Perform template argument deduction on each template
313    // argument. Ignore any missing/extra arguments, since they could be
314    // filled in by default arguments.
315    return DeduceTemplateArguments(S, TemplateParams,
316                                   Param->getArgs(), Param->getNumArgs(),
317                                   SpecArg->getArgs(), SpecArg->getNumArgs(),
318                                   Info, Deduced,
319                                   /*NumberOfArgumentsMustMatch=*/false);
320  }
321
322  // If the argument type is a class template specialization, we
323  // perform template argument deduction using its template
324  // arguments.
325  const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
326  if (!RecordArg)
327    return Sema::TDK_NonDeducedMismatch;
328
329  ClassTemplateSpecializationDecl *SpecArg
330    = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
331  if (!SpecArg)
332    return Sema::TDK_NonDeducedMismatch;
333
334  // Perform template argument deduction for the template name.
335  if (Sema::TemplateDeductionResult Result
336        = DeduceTemplateArguments(S,
337                                  TemplateParams,
338                                  Param->getTemplateName(),
339                               TemplateName(SpecArg->getSpecializedTemplate()),
340                                  Info, Deduced))
341    return Result;
342
343  // Perform template argument deduction for the template arguments.
344  return DeduceTemplateArguments(S, TemplateParams,
345                                 Param->getArgs(), Param->getNumArgs(),
346                                 SpecArg->getTemplateArgs().data(),
347                                 SpecArg->getTemplateArgs().size(),
348                                 Info, Deduced);
349}
350
351/// \brief Determines whether the given type is an opaque type that
352/// might be more qualified when instantiated.
353static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
354  switch (T->getTypeClass()) {
355  case Type::TypeOfExpr:
356  case Type::TypeOf:
357  case Type::DependentName:
358  case Type::Decltype:
359  case Type::UnresolvedUsing:
360    return true;
361
362  case Type::ConstantArray:
363  case Type::IncompleteArray:
364  case Type::VariableArray:
365  case Type::DependentSizedArray:
366    return IsPossiblyOpaquelyQualifiedType(
367                                      cast<ArrayType>(T)->getElementType());
368
369  default:
370    return false;
371  }
372}
373
374/// \brief Deduce the template arguments by comparing the parameter type and
375/// the argument type (C++ [temp.deduct.type]).
376///
377/// \param S the semantic analysis object within which we are deducing
378///
379/// \param TemplateParams the template parameters that we are deducing
380///
381/// \param ParamIn the parameter type
382///
383/// \param ArgIn the argument type
384///
385/// \param Info information about the template argument deduction itself
386///
387/// \param Deduced the deduced template arguments
388///
389/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
390/// how template argument deduction is performed.
391///
392/// \returns the result of template argument deduction so far. Note that a
393/// "success" result means that template argument deduction has not yet failed,
394/// but it may still fail, later, for other reasons.
395static Sema::TemplateDeductionResult
396DeduceTemplateArguments(Sema &S,
397                        TemplateParameterList *TemplateParams,
398                        QualType ParamIn, QualType ArgIn,
399                        TemplateDeductionInfo &Info,
400                     llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
401                        unsigned TDF) {
402  // We only want to look at the canonical types, since typedefs and
403  // sugar are not part of template argument deduction.
404  QualType Param = S.Context.getCanonicalType(ParamIn);
405  QualType Arg = S.Context.getCanonicalType(ArgIn);
406
407  // C++0x [temp.deduct.call]p4 bullet 1:
408  //   - If the original P is a reference type, the deduced A (i.e., the type
409  //     referred to by the reference) can be more cv-qualified than the
410  //     transformed A.
411  if (TDF & TDF_ParamWithReferenceType) {
412    Qualifiers Quals;
413    QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
414    Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
415                           Arg.getCVRQualifiersThroughArrayTypes());
416    Param = S.Context.getQualifiedType(UnqualParam, Quals);
417  }
418
419  // If the parameter type is not dependent, there is nothing to deduce.
420  if (!Param->isDependentType()) {
421    if (!(TDF & TDF_SkipNonDependent) && Param != Arg) {
422
423      return Sema::TDK_NonDeducedMismatch;
424    }
425
426    return Sema::TDK_Success;
427  }
428
429  // C++ [temp.deduct.type]p9:
430  //   A template type argument T, a template template argument TT or a
431  //   template non-type argument i can be deduced if P and A have one of
432  //   the following forms:
433  //
434  //     T
435  //     cv-list T
436  if (const TemplateTypeParmType *TemplateTypeParm
437        = Param->getAs<TemplateTypeParmType>()) {
438    unsigned Index = TemplateTypeParm->getIndex();
439    bool RecanonicalizeArg = false;
440
441    // If the argument type is an array type, move the qualifiers up to the
442    // top level, so they can be matched with the qualifiers on the parameter.
443    // FIXME: address spaces, ObjC GC qualifiers
444    if (isa<ArrayType>(Arg)) {
445      Qualifiers Quals;
446      Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
447      if (Quals) {
448        Arg = S.Context.getQualifiedType(Arg, Quals);
449        RecanonicalizeArg = true;
450      }
451    }
452
453    // The argument type can not be less qualified than the parameter
454    // type.
455    if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
456      Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
457      Info.FirstArg = TemplateArgument(Param);
458      Info.SecondArg = TemplateArgument(Arg);
459      return Sema::TDK_Underqualified;
460    }
461
462    assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
463    assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
464    QualType DeducedType = Arg;
465
466    // local manipulation is okay because it's canonical
467    DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
468    if (RecanonicalizeArg)
469      DeducedType = S.Context.getCanonicalType(DeducedType);
470
471    if (Deduced[Index].isNull())
472      Deduced[Index] = TemplateArgument(DeducedType);
473    else {
474      // C++ [temp.deduct.type]p2:
475      //   [...] If type deduction cannot be done for any P/A pair, or if for
476      //   any pair the deduction leads to more than one possible set of
477      //   deduced values, or if different pairs yield different deduced
478      //   values, or if any template argument remains neither deduced nor
479      //   explicitly specified, template argument deduction fails.
480      if (Deduced[Index].getAsType() != DeducedType) {
481        Info.Param
482          = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
483        Info.FirstArg = Deduced[Index];
484        Info.SecondArg = TemplateArgument(Arg);
485        return Sema::TDK_Inconsistent;
486      }
487    }
488    return Sema::TDK_Success;
489  }
490
491  // Set up the template argument deduction information for a failure.
492  Info.FirstArg = TemplateArgument(ParamIn);
493  Info.SecondArg = TemplateArgument(ArgIn);
494
495  // Check the cv-qualifiers on the parameter and argument types.
496  if (!(TDF & TDF_IgnoreQualifiers)) {
497    if (TDF & TDF_ParamWithReferenceType) {
498      if (Param.isMoreQualifiedThan(Arg))
499        return Sema::TDK_NonDeducedMismatch;
500    } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
501      if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
502        return Sema::TDK_NonDeducedMismatch;
503    }
504  }
505
506  switch (Param->getTypeClass()) {
507    // No deduction possible for these types
508    case Type::Builtin:
509      return Sema::TDK_NonDeducedMismatch;
510
511    //     T *
512    case Type::Pointer: {
513      QualType PointeeType;
514      if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
515        PointeeType = PointerArg->getPointeeType();
516      } else if (const ObjCObjectPointerType *PointerArg
517                   = Arg->getAs<ObjCObjectPointerType>()) {
518        PointeeType = PointerArg->getPointeeType();
519      } else {
520        return Sema::TDK_NonDeducedMismatch;
521      }
522
523      unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
524      return DeduceTemplateArguments(S, TemplateParams,
525                                   cast<PointerType>(Param)->getPointeeType(),
526                                     PointeeType,
527                                     Info, Deduced, SubTDF);
528    }
529
530    //     T &
531    case Type::LValueReference: {
532      const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
533      if (!ReferenceArg)
534        return Sema::TDK_NonDeducedMismatch;
535
536      return DeduceTemplateArguments(S, TemplateParams,
537                           cast<LValueReferenceType>(Param)->getPointeeType(),
538                                     ReferenceArg->getPointeeType(),
539                                     Info, Deduced, 0);
540    }
541
542    //     T && [C++0x]
543    case Type::RValueReference: {
544      const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
545      if (!ReferenceArg)
546        return Sema::TDK_NonDeducedMismatch;
547
548      return DeduceTemplateArguments(S, TemplateParams,
549                           cast<RValueReferenceType>(Param)->getPointeeType(),
550                                     ReferenceArg->getPointeeType(),
551                                     Info, Deduced, 0);
552    }
553
554    //     T [] (implied, but not stated explicitly)
555    case Type::IncompleteArray: {
556      const IncompleteArrayType *IncompleteArrayArg =
557        S.Context.getAsIncompleteArrayType(Arg);
558      if (!IncompleteArrayArg)
559        return Sema::TDK_NonDeducedMismatch;
560
561      unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
562      return DeduceTemplateArguments(S, TemplateParams,
563                     S.Context.getAsIncompleteArrayType(Param)->getElementType(),
564                                     IncompleteArrayArg->getElementType(),
565                                     Info, Deduced, SubTDF);
566    }
567
568    //     T [integer-constant]
569    case Type::ConstantArray: {
570      const ConstantArrayType *ConstantArrayArg =
571        S.Context.getAsConstantArrayType(Arg);
572      if (!ConstantArrayArg)
573        return Sema::TDK_NonDeducedMismatch;
574
575      const ConstantArrayType *ConstantArrayParm =
576        S.Context.getAsConstantArrayType(Param);
577      if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
578        return Sema::TDK_NonDeducedMismatch;
579
580      unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
581      return DeduceTemplateArguments(S, TemplateParams,
582                                     ConstantArrayParm->getElementType(),
583                                     ConstantArrayArg->getElementType(),
584                                     Info, Deduced, SubTDF);
585    }
586
587    //     type [i]
588    case Type::DependentSizedArray: {
589      const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
590      if (!ArrayArg)
591        return Sema::TDK_NonDeducedMismatch;
592
593      unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
594
595      // Check the element type of the arrays
596      const DependentSizedArrayType *DependentArrayParm
597        = S.Context.getAsDependentSizedArrayType(Param);
598      if (Sema::TemplateDeductionResult Result
599            = DeduceTemplateArguments(S, TemplateParams,
600                                      DependentArrayParm->getElementType(),
601                                      ArrayArg->getElementType(),
602                                      Info, Deduced, SubTDF))
603        return Result;
604
605      // Determine the array bound is something we can deduce.
606      NonTypeTemplateParmDecl *NTTP
607        = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
608      if (!NTTP)
609        return Sema::TDK_Success;
610
611      // We can perform template argument deduction for the given non-type
612      // template parameter.
613      assert(NTTP->getDepth() == 0 &&
614             "Cannot deduce non-type template argument at depth > 0");
615      if (const ConstantArrayType *ConstantArrayArg
616            = dyn_cast<ConstantArrayType>(ArrayArg)) {
617        llvm::APSInt Size(ConstantArrayArg->getSize());
618        return DeduceNonTypeTemplateArgument(S, NTTP, Size,
619                                             S.Context.getSizeType(),
620                                             /*ArrayBound=*/true,
621                                             Info, Deduced);
622      }
623      if (const DependentSizedArrayType *DependentArrayArg
624            = dyn_cast<DependentSizedArrayType>(ArrayArg))
625        return DeduceNonTypeTemplateArgument(S, NTTP,
626                                             DependentArrayArg->getSizeExpr(),
627                                             Info, Deduced);
628
629      // Incomplete type does not match a dependently-sized array type
630      return Sema::TDK_NonDeducedMismatch;
631    }
632
633    //     type(*)(T)
634    //     T(*)()
635    //     T(*)(T)
636    case Type::FunctionProto: {
637      const FunctionProtoType *FunctionProtoArg =
638        dyn_cast<FunctionProtoType>(Arg);
639      if (!FunctionProtoArg)
640        return Sema::TDK_NonDeducedMismatch;
641
642      const FunctionProtoType *FunctionProtoParam =
643        cast<FunctionProtoType>(Param);
644
645      if (FunctionProtoParam->getTypeQuals() !=
646          FunctionProtoArg->getTypeQuals())
647        return Sema::TDK_NonDeducedMismatch;
648
649      if (FunctionProtoParam->getNumArgs() != FunctionProtoArg->getNumArgs())
650        return Sema::TDK_NonDeducedMismatch;
651
652      if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
653        return Sema::TDK_NonDeducedMismatch;
654
655      // Check return types.
656      if (Sema::TemplateDeductionResult Result
657            = DeduceTemplateArguments(S, TemplateParams,
658                                      FunctionProtoParam->getResultType(),
659                                      FunctionProtoArg->getResultType(),
660                                      Info, Deduced, 0))
661        return Result;
662
663      for (unsigned I = 0, N = FunctionProtoParam->getNumArgs(); I != N; ++I) {
664        // Check argument types.
665        // FIXME: Variadic templates.
666        if (Sema::TemplateDeductionResult Result
667              = DeduceTemplateArguments(S, TemplateParams,
668                                        FunctionProtoParam->getArgType(I),
669                                        FunctionProtoArg->getArgType(I),
670                                        Info, Deduced, 0))
671          return Result;
672      }
673
674      return Sema::TDK_Success;
675    }
676
677    case Type::InjectedClassName: {
678      // Treat a template's injected-class-name as if the template
679      // specialization type had been used.
680      Param = cast<InjectedClassNameType>(Param)
681        ->getInjectedSpecializationType();
682      assert(isa<TemplateSpecializationType>(Param) &&
683             "injected class name is not a template specialization type");
684      // fall through
685    }
686
687    //     template-name<T> (where template-name refers to a class template)
688    //     template-name<i>
689    //     TT<T>
690    //     TT<i>
691    //     TT<>
692    case Type::TemplateSpecialization: {
693      const TemplateSpecializationType *SpecParam
694        = cast<TemplateSpecializationType>(Param);
695
696      // Try to deduce template arguments from the template-id.
697      Sema::TemplateDeductionResult Result
698        = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
699                                  Info, Deduced);
700
701      if (Result && (TDF & TDF_DerivedClass)) {
702        // C++ [temp.deduct.call]p3b3:
703        //   If P is a class, and P has the form template-id, then A can be a
704        //   derived class of the deduced A. Likewise, if P is a pointer to a
705        //   class of the form template-id, A can be a pointer to a derived
706        //   class pointed to by the deduced A.
707        //
708        // More importantly:
709        //   These alternatives are considered only if type deduction would
710        //   otherwise fail.
711        if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
712          // We cannot inspect base classes as part of deduction when the type
713          // is incomplete, so either instantiate any templates necessary to
714          // complete the type, or skip over it if it cannot be completed.
715          if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
716            return Result;
717
718          // Use data recursion to crawl through the list of base classes.
719          // Visited contains the set of nodes we have already visited, while
720          // ToVisit is our stack of records that we still need to visit.
721          llvm::SmallPtrSet<const RecordType *, 8> Visited;
722          llvm::SmallVector<const RecordType *, 8> ToVisit;
723          ToVisit.push_back(RecordT);
724          bool Successful = false;
725          llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
726          DeducedOrig = Deduced;
727          while (!ToVisit.empty()) {
728            // Retrieve the next class in the inheritance hierarchy.
729            const RecordType *NextT = ToVisit.back();
730            ToVisit.pop_back();
731
732            // If we have already seen this type, skip it.
733            if (!Visited.insert(NextT))
734              continue;
735
736            // If this is a base class, try to perform template argument
737            // deduction from it.
738            if (NextT != RecordT) {
739              Sema::TemplateDeductionResult BaseResult
740                = DeduceTemplateArguments(S, TemplateParams, SpecParam,
741                                          QualType(NextT, 0), Info, Deduced);
742
743              // If template argument deduction for this base was successful,
744              // note that we had some success. Otherwise, ignore any deductions
745              // from this base class.
746              if (BaseResult == Sema::TDK_Success) {
747                Successful = true;
748                DeducedOrig = Deduced;
749              }
750              else
751                Deduced = DeducedOrig;
752            }
753
754            // Visit base classes
755            CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
756            for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
757                                                 BaseEnd = Next->bases_end();
758                 Base != BaseEnd; ++Base) {
759              assert(Base->getType()->isRecordType() &&
760                     "Base class that isn't a record?");
761              ToVisit.push_back(Base->getType()->getAs<RecordType>());
762            }
763          }
764
765          if (Successful)
766            return Sema::TDK_Success;
767        }
768
769      }
770
771      return Result;
772    }
773
774    //     T type::*
775    //     T T::*
776    //     T (type::*)()
777    //     type (T::*)()
778    //     type (type::*)(T)
779    //     type (T::*)(T)
780    //     T (type::*)(T)
781    //     T (T::*)()
782    //     T (T::*)(T)
783    case Type::MemberPointer: {
784      const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
785      const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
786      if (!MemPtrArg)
787        return Sema::TDK_NonDeducedMismatch;
788
789      if (Sema::TemplateDeductionResult Result
790            = DeduceTemplateArguments(S, TemplateParams,
791                                      MemPtrParam->getPointeeType(),
792                                      MemPtrArg->getPointeeType(),
793                                      Info, Deduced,
794                                      TDF & TDF_IgnoreQualifiers))
795        return Result;
796
797      return DeduceTemplateArguments(S, TemplateParams,
798                                     QualType(MemPtrParam->getClass(), 0),
799                                     QualType(MemPtrArg->getClass(), 0),
800                                     Info, Deduced, 0);
801    }
802
803    //     (clang extension)
804    //
805    //     type(^)(T)
806    //     T(^)()
807    //     T(^)(T)
808    case Type::BlockPointer: {
809      const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
810      const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
811
812      if (!BlockPtrArg)
813        return Sema::TDK_NonDeducedMismatch;
814
815      return DeduceTemplateArguments(S, TemplateParams,
816                                     BlockPtrParam->getPointeeType(),
817                                     BlockPtrArg->getPointeeType(), Info,
818                                     Deduced, 0);
819    }
820
821    case Type::TypeOfExpr:
822    case Type::TypeOf:
823    case Type::DependentName:
824      // No template argument deduction for these types
825      return Sema::TDK_Success;
826
827    default:
828      break;
829  }
830
831  // FIXME: Many more cases to go (to go).
832  return Sema::TDK_Success;
833}
834
835static Sema::TemplateDeductionResult
836DeduceTemplateArguments(Sema &S,
837                        TemplateParameterList *TemplateParams,
838                        const TemplateArgument &Param,
839                        const TemplateArgument &Arg,
840                        TemplateDeductionInfo &Info,
841                    llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
842  switch (Param.getKind()) {
843  case TemplateArgument::Null:
844    assert(false && "Null template argument in parameter list");
845    break;
846
847  case TemplateArgument::Type:
848    if (Arg.getKind() == TemplateArgument::Type)
849      return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
850                                     Arg.getAsType(), Info, Deduced, 0);
851    Info.FirstArg = Param;
852    Info.SecondArg = Arg;
853    return Sema::TDK_NonDeducedMismatch;
854
855  case TemplateArgument::Template:
856    if (Arg.getKind() == TemplateArgument::Template)
857      return DeduceTemplateArguments(S, TemplateParams,
858                                     Param.getAsTemplate(),
859                                     Arg.getAsTemplate(), Info, Deduced);
860    Info.FirstArg = Param;
861    Info.SecondArg = Arg;
862    return Sema::TDK_NonDeducedMismatch;
863
864  case TemplateArgument::Declaration:
865    if (Arg.getKind() == TemplateArgument::Declaration &&
866        Param.getAsDecl()->getCanonicalDecl() ==
867          Arg.getAsDecl()->getCanonicalDecl())
868      return Sema::TDK_Success;
869
870    Info.FirstArg = Param;
871    Info.SecondArg = Arg;
872    return Sema::TDK_NonDeducedMismatch;
873
874  case TemplateArgument::Integral:
875    if (Arg.getKind() == TemplateArgument::Integral) {
876      if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
877        return Sema::TDK_Success;
878
879      Info.FirstArg = Param;
880      Info.SecondArg = Arg;
881      return Sema::TDK_NonDeducedMismatch;
882    }
883
884    if (Arg.getKind() == TemplateArgument::Expression) {
885      Info.FirstArg = Param;
886      Info.SecondArg = Arg;
887      return Sema::TDK_NonDeducedMismatch;
888    }
889
890    Info.FirstArg = Param;
891    Info.SecondArg = Arg;
892    return Sema::TDK_NonDeducedMismatch;
893
894  case TemplateArgument::Expression: {
895    if (NonTypeTemplateParmDecl *NTTP
896          = getDeducedParameterFromExpr(Param.getAsExpr())) {
897      if (Arg.getKind() == TemplateArgument::Integral)
898        return DeduceNonTypeTemplateArgument(S, NTTP,
899                                             *Arg.getAsIntegral(),
900                                             Arg.getIntegralType(),
901                                             /*ArrayBound=*/false,
902                                             Info, Deduced);
903      if (Arg.getKind() == TemplateArgument::Expression)
904        return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
905                                             Info, Deduced);
906      if (Arg.getKind() == TemplateArgument::Declaration)
907        return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
908                                             Info, Deduced);
909
910      Info.FirstArg = Param;
911      Info.SecondArg = Arg;
912      return Sema::TDK_NonDeducedMismatch;
913    }
914
915    // Can't deduce anything, but that's okay.
916    return Sema::TDK_Success;
917  }
918  case TemplateArgument::Pack:
919    llvm_unreachable("Argument packs should be expanded by the caller!");
920  }
921
922  return Sema::TDK_Success;
923}
924
925/// \brief Determine whether there is a template argument to be used for
926/// deduction.
927///
928/// This routine "expands" argument packs in-place, overriding its input
929/// parameters so that \c Args[ArgIdx] will be the available template argument.
930///
931/// \returns true if there is another template argument (which will be at
932/// \c Args[ArgIdx]), false otherwise.
933static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
934                                            unsigned &ArgIdx,
935                                            unsigned &NumArgs) {
936  if (ArgIdx == NumArgs)
937    return false;
938
939  const TemplateArgument &Arg = Args[ArgIdx];
940  if (Arg.getKind() != TemplateArgument::Pack)
941    return true;
942
943  assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
944  Args = Arg.pack_begin();
945  NumArgs = Arg.pack_size();
946  ArgIdx = 0;
947  return ArgIdx < NumArgs;
948}
949
950static Sema::TemplateDeductionResult
951DeduceTemplateArguments(Sema &S,
952                        TemplateParameterList *TemplateParams,
953                        const TemplateArgument *Params, unsigned NumParams,
954                        const TemplateArgument *Args, unsigned NumArgs,
955                        TemplateDeductionInfo &Info,
956                    llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
957                        bool NumberOfArgumentsMustMatch) {
958  unsigned ArgIdx = 0, ParamIdx = 0;
959  for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
960       ++ParamIdx) {
961    if (!Params[ParamIdx].isPackExpansion()) {
962      // The simple case: deduce template arguments by matching P and A.
963
964      // Check whether we have enough arguments.
965      if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
966        return NumberOfArgumentsMustMatch? Sema::TDK_TooFewArguments
967                                         : Sema::TDK_Success;
968
969      // Perform deduction for this P/A pair.
970      if (Sema::TemplateDeductionResult Result
971          = DeduceTemplateArguments(S, TemplateParams,
972                                    Params[ParamIdx], Args[ArgIdx],
973                                    Info, Deduced))
974        return Result;
975
976      // Move to the next argument.
977      ++ArgIdx;
978      continue;
979    }
980
981    // FIXME: Variadic templates.
982    // The parameter is a pack expansion, so we'll
983    // need to repeatedly unify arguments against the parameter, capturing
984    // the bindings for each expanded parameter pack.
985    S.Diag(Info.getLocation(), diag::err_pack_expansion_deduction);
986    return Sema::TDK_TooManyArguments;
987  }
988
989  // If there is an argument remaining, then we had too many arguments.
990  if (NumberOfArgumentsMustMatch &&
991      hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
992    return Sema::TDK_TooManyArguments;
993
994  return Sema::TDK_Success;
995}
996
997static Sema::TemplateDeductionResult
998DeduceTemplateArguments(Sema &S,
999                        TemplateParameterList *TemplateParams,
1000                        const TemplateArgumentList &ParamList,
1001                        const TemplateArgumentList &ArgList,
1002                        TemplateDeductionInfo &Info,
1003                    llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
1004  return DeduceTemplateArguments(S, TemplateParams,
1005                                 ParamList.data(), ParamList.size(),
1006                                 ArgList.data(), ArgList.size(),
1007                                 Info, Deduced);
1008}
1009
1010/// \brief Determine whether two template arguments are the same.
1011static bool isSameTemplateArg(ASTContext &Context,
1012                              const TemplateArgument &X,
1013                              const TemplateArgument &Y) {
1014  if (X.getKind() != Y.getKind())
1015    return false;
1016
1017  switch (X.getKind()) {
1018    case TemplateArgument::Null:
1019      assert(false && "Comparing NULL template argument");
1020      break;
1021
1022    case TemplateArgument::Type:
1023      return Context.getCanonicalType(X.getAsType()) ==
1024             Context.getCanonicalType(Y.getAsType());
1025
1026    case TemplateArgument::Declaration:
1027      return X.getAsDecl()->getCanonicalDecl() ==
1028             Y.getAsDecl()->getCanonicalDecl();
1029
1030    case TemplateArgument::Template:
1031      return Context.getCanonicalTemplateName(X.getAsTemplate())
1032               .getAsVoidPointer() ==
1033             Context.getCanonicalTemplateName(Y.getAsTemplate())
1034               .getAsVoidPointer();
1035
1036    case TemplateArgument::Integral:
1037      return *X.getAsIntegral() == *Y.getAsIntegral();
1038
1039    case TemplateArgument::Expression: {
1040      llvm::FoldingSetNodeID XID, YID;
1041      X.getAsExpr()->Profile(XID, Context, true);
1042      Y.getAsExpr()->Profile(YID, Context, true);
1043      return XID == YID;
1044    }
1045
1046    case TemplateArgument::Pack:
1047      if (X.pack_size() != Y.pack_size())
1048        return false;
1049
1050      for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1051                                        XPEnd = X.pack_end(),
1052                                           YP = Y.pack_begin();
1053           XP != XPEnd; ++XP, ++YP)
1054        if (!isSameTemplateArg(Context, *XP, *YP))
1055          return false;
1056
1057      return true;
1058  }
1059
1060  return false;
1061}
1062
1063/// \brief Helper function to build a TemplateParameter when we don't
1064/// know its type statically.
1065static TemplateParameter makeTemplateParameter(Decl *D) {
1066  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
1067    return TemplateParameter(TTP);
1068  else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
1069    return TemplateParameter(NTTP);
1070
1071  return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
1072}
1073
1074/// Complete template argument deduction for a class template partial
1075/// specialization.
1076static Sema::TemplateDeductionResult
1077FinishTemplateArgumentDeduction(Sema &S,
1078                                ClassTemplatePartialSpecializationDecl *Partial,
1079                                const TemplateArgumentList &TemplateArgs,
1080                      llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1081                                TemplateDeductionInfo &Info) {
1082  // Trap errors.
1083  Sema::SFINAETrap Trap(S);
1084
1085  Sema::ContextRAII SavedContext(S, Partial);
1086
1087  // C++ [temp.deduct.type]p2:
1088  //   [...] or if any template argument remains neither deduced nor
1089  //   explicitly specified, template argument deduction fails.
1090  llvm::SmallVector<TemplateArgument, 4> Builder;
1091  for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
1092    if (Deduced[I].isNull()) {
1093      Decl *Param
1094        = const_cast<NamedDecl *>(
1095                                Partial->getTemplateParameters()->getParam(I));
1096      Info.Param = makeTemplateParameter(Param);
1097      return Sema::TDK_Incomplete;
1098    }
1099
1100    Builder.push_back(Deduced[I]);
1101  }
1102
1103  // Form the template argument list from the deduced template arguments.
1104  TemplateArgumentList *DeducedArgumentList
1105    = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1106                                       Builder.size());
1107
1108  Info.reset(DeducedArgumentList);
1109
1110  // Substitute the deduced template arguments into the template
1111  // arguments of the class template partial specialization, and
1112  // verify that the instantiated template arguments are both valid
1113  // and are equivalent to the template arguments originally provided
1114  // to the class template.
1115  // FIXME: Do we have to correct the types of deduced non-type template
1116  // arguments (in particular, integral non-type template arguments?).
1117  LocalInstantiationScope InstScope(S);
1118  ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1119  const TemplateArgumentLoc *PartialTemplateArgs
1120    = Partial->getTemplateArgsAsWritten();
1121  unsigned N = Partial->getNumTemplateArgsAsWritten();
1122
1123  // Note that we don't provide the langle and rangle locations.
1124  TemplateArgumentListInfo InstArgs;
1125
1126  for (unsigned I = 0; I != N; ++I) {
1127    Decl *Param = const_cast<NamedDecl *>(
1128                    ClassTemplate->getTemplateParameters()->getParam(I));
1129    TemplateArgumentLoc InstArg;
1130    if (S.Subst(PartialTemplateArgs[I], InstArg,
1131                MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1132      Info.Param = makeTemplateParameter(Param);
1133      Info.FirstArg = PartialTemplateArgs[I].getArgument();
1134      return Sema::TDK_SubstitutionFailure;
1135    }
1136    InstArgs.addArgument(InstArg);
1137  }
1138
1139  llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
1140  if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
1141                                InstArgs, false, ConvertedInstArgs))
1142    return Sema::TDK_SubstitutionFailure;
1143
1144  for (unsigned I = 0, E = ConvertedInstArgs.size(); I != E; ++I) {
1145    TemplateArgument InstArg = ConvertedInstArgs.data()[I];
1146
1147    Decl *Param = const_cast<NamedDecl *>(
1148                    ClassTemplate->getTemplateParameters()->getParam(I));
1149
1150    if (InstArg.getKind() == TemplateArgument::Expression) {
1151      // When the argument is an expression, check the expression result
1152      // against the actual template parameter to get down to the canonical
1153      // template argument.
1154      // FIXME: Variadic templates.
1155      Expr *InstExpr = InstArg.getAsExpr();
1156      if (NonTypeTemplateParmDecl *NTTP
1157            = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1158        if (S.CheckTemplateArgument(NTTP, NTTP->getType(), InstExpr, InstArg)) {
1159          Info.Param = makeTemplateParameter(Param);
1160          Info.FirstArg = Partial->getTemplateArgs()[I];
1161          return Sema::TDK_SubstitutionFailure;
1162        }
1163      }
1164    }
1165
1166    if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
1167      Info.Param = makeTemplateParameter(Param);
1168      Info.FirstArg = TemplateArgs[I];
1169      Info.SecondArg = InstArg;
1170      return Sema::TDK_NonDeducedMismatch;
1171    }
1172  }
1173
1174  if (Trap.hasErrorOccurred())
1175    return Sema::TDK_SubstitutionFailure;
1176
1177  return Sema::TDK_Success;
1178}
1179
1180/// \brief Perform template argument deduction to determine whether
1181/// the given template arguments match the given class template
1182/// partial specialization per C++ [temp.class.spec.match].
1183Sema::TemplateDeductionResult
1184Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
1185                              const TemplateArgumentList &TemplateArgs,
1186                              TemplateDeductionInfo &Info) {
1187  // C++ [temp.class.spec.match]p2:
1188  //   A partial specialization matches a given actual template
1189  //   argument list if the template arguments of the partial
1190  //   specialization can be deduced from the actual template argument
1191  //   list (14.8.2).
1192  SFINAETrap Trap(*this);
1193  llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
1194  Deduced.resize(Partial->getTemplateParameters()->size());
1195  if (TemplateDeductionResult Result
1196        = ::DeduceTemplateArguments(*this,
1197                                    Partial->getTemplateParameters(),
1198                                    Partial->getTemplateArgs(),
1199                                    TemplateArgs, Info, Deduced))
1200    return Result;
1201
1202  InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
1203                             Deduced.data(), Deduced.size(), Info);
1204  if (Inst)
1205    return TDK_InstantiationDepth;
1206
1207  if (Trap.hasErrorOccurred())
1208    return Sema::TDK_SubstitutionFailure;
1209
1210  return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1211                                           Deduced, Info);
1212}
1213
1214/// \brief Determine whether the given type T is a simple-template-id type.
1215static bool isSimpleTemplateIdType(QualType T) {
1216  if (const TemplateSpecializationType *Spec
1217        = T->getAs<TemplateSpecializationType>())
1218    return Spec->getTemplateName().getAsTemplateDecl() != 0;
1219
1220  return false;
1221}
1222
1223/// \brief Substitute the explicitly-provided template arguments into the
1224/// given function template according to C++ [temp.arg.explicit].
1225///
1226/// \param FunctionTemplate the function template into which the explicit
1227/// template arguments will be substituted.
1228///
1229/// \param ExplicitTemplateArguments the explicitly-specified template
1230/// arguments.
1231///
1232/// \param Deduced the deduced template arguments, which will be populated
1233/// with the converted and checked explicit template arguments.
1234///
1235/// \param ParamTypes will be populated with the instantiated function
1236/// parameters.
1237///
1238/// \param FunctionType if non-NULL, the result type of the function template
1239/// will also be instantiated and the pointed-to value will be updated with
1240/// the instantiated function type.
1241///
1242/// \param Info if substitution fails for any reason, this object will be
1243/// populated with more information about the failure.
1244///
1245/// \returns TDK_Success if substitution was successful, or some failure
1246/// condition.
1247Sema::TemplateDeductionResult
1248Sema::SubstituteExplicitTemplateArguments(
1249                                      FunctionTemplateDecl *FunctionTemplate,
1250                        const TemplateArgumentListInfo &ExplicitTemplateArgs,
1251                       llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1252                                 llvm::SmallVectorImpl<QualType> &ParamTypes,
1253                                          QualType *FunctionType,
1254                                          TemplateDeductionInfo &Info) {
1255  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1256  TemplateParameterList *TemplateParams
1257    = FunctionTemplate->getTemplateParameters();
1258
1259  if (ExplicitTemplateArgs.size() == 0) {
1260    // No arguments to substitute; just copy over the parameter types and
1261    // fill in the function type.
1262    for (FunctionDecl::param_iterator P = Function->param_begin(),
1263                                   PEnd = Function->param_end();
1264         P != PEnd;
1265         ++P)
1266      ParamTypes.push_back((*P)->getType());
1267
1268    if (FunctionType)
1269      *FunctionType = Function->getType();
1270    return TDK_Success;
1271  }
1272
1273  // Substitution of the explicit template arguments into a function template
1274  /// is a SFINAE context. Trap any errors that might occur.
1275  SFINAETrap Trap(*this);
1276
1277  // C++ [temp.arg.explicit]p3:
1278  //   Template arguments that are present shall be specified in the
1279  //   declaration order of their corresponding template-parameters. The
1280  //   template argument list shall not specify more template-arguments than
1281  //   there are corresponding template-parameters.
1282  llvm::SmallVector<TemplateArgument, 4> Builder;
1283
1284  // Enter a new template instantiation context where we check the
1285  // explicitly-specified template arguments against this function template,
1286  // and then substitute them into the function parameter types.
1287  InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
1288                             FunctionTemplate, Deduced.data(), Deduced.size(),
1289           ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1290                             Info);
1291  if (Inst)
1292    return TDK_InstantiationDepth;
1293
1294  if (CheckTemplateArgumentList(FunctionTemplate,
1295                                SourceLocation(),
1296                                ExplicitTemplateArgs,
1297                                true,
1298                                Builder) || Trap.hasErrorOccurred()) {
1299    unsigned Index = Builder.size();
1300    if (Index >= TemplateParams->size())
1301      Index = TemplateParams->size() - 1;
1302    Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
1303    return TDK_InvalidExplicitArguments;
1304  }
1305
1306  // Form the template argument list from the explicitly-specified
1307  // template arguments.
1308  TemplateArgumentList *ExplicitArgumentList
1309    = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
1310  Info.reset(ExplicitArgumentList);
1311
1312  // Template argument deduction and the final substitution should be
1313  // done in the context of the templated declaration.  Explicit
1314  // argument substitution, on the other hand, needs to happen in the
1315  // calling context.
1316  ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1317
1318  // Instantiate the types of each of the function parameters given the
1319  // explicitly-specified template arguments.
1320  for (FunctionDecl::param_iterator P = Function->param_begin(),
1321                                PEnd = Function->param_end();
1322       P != PEnd;
1323       ++P) {
1324    QualType ParamType
1325      = SubstType((*P)->getType(),
1326                  MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1327                  (*P)->getLocation(), (*P)->getDeclName());
1328    if (ParamType.isNull() || Trap.hasErrorOccurred())
1329      return TDK_SubstitutionFailure;
1330
1331    ParamTypes.push_back(ParamType);
1332  }
1333
1334  // If the caller wants a full function type back, instantiate the return
1335  // type and form that function type.
1336  if (FunctionType) {
1337    // FIXME: exception-specifications?
1338    const FunctionProtoType *Proto
1339      = Function->getType()->getAs<FunctionProtoType>();
1340    assert(Proto && "Function template does not have a prototype?");
1341
1342    QualType ResultType
1343      = SubstType(Proto->getResultType(),
1344                  MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1345                  Function->getTypeSpecStartLoc(),
1346                  Function->getDeclName());
1347    if (ResultType.isNull() || Trap.hasErrorOccurred())
1348      return TDK_SubstitutionFailure;
1349
1350    *FunctionType = BuildFunctionType(ResultType,
1351                                      ParamTypes.data(), ParamTypes.size(),
1352                                      Proto->isVariadic(),
1353                                      Proto->getTypeQuals(),
1354                                      Function->getLocation(),
1355                                      Function->getDeclName(),
1356                                      Proto->getExtInfo());
1357    if (FunctionType->isNull() || Trap.hasErrorOccurred())
1358      return TDK_SubstitutionFailure;
1359  }
1360
1361  // C++ [temp.arg.explicit]p2:
1362  //   Trailing template arguments that can be deduced (14.8.2) may be
1363  //   omitted from the list of explicit template-arguments. If all of the
1364  //   template arguments can be deduced, they may all be omitted; in this
1365  //   case, the empty template argument list <> itself may also be omitted.
1366  //
1367  // Take all of the explicitly-specified arguments and put them into the
1368  // set of deduced template arguments.
1369  //
1370  // FIXME: Variadic templates?
1371  Deduced.reserve(TemplateParams->size());
1372  for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I)
1373    Deduced.push_back(ExplicitArgumentList->get(I));
1374
1375  return TDK_Success;
1376}
1377
1378/// \brief Allocate a TemplateArgumentLoc where all locations have
1379/// been initialized to the given location.
1380///
1381/// \param S The semantic analysis object.
1382///
1383/// \param The template argument we are producing template argument
1384/// location information for.
1385///
1386/// \param NTTPType For a declaration template argument, the type of
1387/// the non-type template parameter that corresponds to this template
1388/// argument.
1389///
1390/// \param Loc The source location to use for the resulting template
1391/// argument.
1392static TemplateArgumentLoc
1393getTrivialTemplateArgumentLoc(Sema &S,
1394                              const TemplateArgument &Arg,
1395                              QualType NTTPType,
1396                              SourceLocation Loc) {
1397  switch (Arg.getKind()) {
1398  case TemplateArgument::Null:
1399    llvm_unreachable("Can't get a NULL template argument here");
1400    break;
1401
1402  case TemplateArgument::Type:
1403    return TemplateArgumentLoc(Arg,
1404                    S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1405
1406  case TemplateArgument::Declaration: {
1407    Expr *E
1408      = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
1409                                                              .takeAs<Expr>();
1410    return TemplateArgumentLoc(TemplateArgument(E), E);
1411  }
1412
1413  case TemplateArgument::Integral: {
1414    Expr *E
1415      = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
1416    return TemplateArgumentLoc(TemplateArgument(E), E);
1417  }
1418
1419  case TemplateArgument::Template:
1420    return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1421
1422  case TemplateArgument::Expression:
1423    return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1424
1425  case TemplateArgument::Pack:
1426    return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1427  }
1428
1429  return TemplateArgumentLoc();
1430}
1431
1432/// \brief Finish template argument deduction for a function template,
1433/// checking the deduced template arguments for completeness and forming
1434/// the function template specialization.
1435Sema::TemplateDeductionResult
1436Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
1437                       llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1438                                      unsigned NumExplicitlySpecified,
1439                                      FunctionDecl *&Specialization,
1440                                      TemplateDeductionInfo &Info) {
1441  TemplateParameterList *TemplateParams
1442    = FunctionTemplate->getTemplateParameters();
1443
1444  // Template argument deduction for function templates in a SFINAE context.
1445  // Trap any errors that might occur.
1446  SFINAETrap Trap(*this);
1447
1448  // Enter a new template instantiation context while we instantiate the
1449  // actual function declaration.
1450  InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
1451                             FunctionTemplate, Deduced.data(), Deduced.size(),
1452              ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
1453                             Info);
1454  if (Inst)
1455    return TDK_InstantiationDepth;
1456
1457  ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1458
1459  // C++ [temp.deduct.type]p2:
1460  //   [...] or if any template argument remains neither deduced nor
1461  //   explicitly specified, template argument deduction fails.
1462  llvm::SmallVector<TemplateArgument, 4> Builder;
1463  for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
1464    // FIXME: Variadic templates. Unwrap argument packs?
1465    NamedDecl *Param = FunctionTemplate->getTemplateParameters()->getParam(I);
1466    if (!Deduced[I].isNull()) {
1467      if (I < NumExplicitlySpecified) {
1468        // We have already fully type-checked and converted this
1469        // argument, because it was explicitly-specified. Just record the
1470        // presence of this argument.
1471        Builder.push_back(Deduced[I]);
1472        continue;
1473      }
1474
1475      // We have deduced this argument, so it still needs to be
1476      // checked and converted.
1477
1478      // First, for a non-type template parameter type that is
1479      // initialized by a declaration, we need the type of the
1480      // corresponding non-type template parameter.
1481      QualType NTTPType;
1482      if (NonTypeTemplateParmDecl *NTTP
1483                                = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1484        if (Deduced[I].getKind() == TemplateArgument::Declaration) {
1485          NTTPType = NTTP->getType();
1486          if (NTTPType->isDependentType()) {
1487            TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1488                                              Builder.data(), Builder.size());
1489            NTTPType = SubstType(NTTPType,
1490                                 MultiLevelTemplateArgumentList(TemplateArgs),
1491                                 NTTP->getLocation(),
1492                                 NTTP->getDeclName());
1493            if (NTTPType.isNull()) {
1494              Info.Param = makeTemplateParameter(Param);
1495              // FIXME: These template arguments are temporary. Free them!
1496              Info.reset(TemplateArgumentList::CreateCopy(Context,
1497                                                          Builder.data(),
1498                                                          Builder.size()));
1499              return TDK_SubstitutionFailure;
1500            }
1501          }
1502        }
1503      }
1504
1505      // Convert the deduced template argument into a template
1506      // argument that we can check, almost as if the user had written
1507      // the template argument explicitly.
1508      TemplateArgumentLoc Arg = getTrivialTemplateArgumentLoc(*this,
1509                                                              Deduced[I],
1510                                                              NTTPType,
1511                                                            Info.getLocation());
1512
1513      // Check the template argument, converting it as necessary.
1514      if (CheckTemplateArgument(Param, Arg,
1515                                FunctionTemplate,
1516                                FunctionTemplate->getLocation(),
1517                                FunctionTemplate->getSourceRange().getEnd(),
1518                                Builder,
1519                                Deduced[I].wasDeducedFromArrayBound()
1520                                  ? CTAK_DeducedFromArrayBound
1521                                  : CTAK_Deduced)) {
1522        Info.Param = makeTemplateParameter(
1523                         const_cast<NamedDecl *>(TemplateParams->getParam(I)));
1524        // FIXME: These template arguments are temporary. Free them!
1525        Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
1526                                                    Builder.size()));
1527        return TDK_SubstitutionFailure;
1528      }
1529
1530      continue;
1531    }
1532
1533    // Substitute into the default template argument, if available.
1534    TemplateArgumentLoc DefArg
1535      = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
1536                                              FunctionTemplate->getLocation(),
1537                                  FunctionTemplate->getSourceRange().getEnd(),
1538                                                Param,
1539                                                Builder);
1540
1541    // If there was no default argument, deduction is incomplete.
1542    if (DefArg.getArgument().isNull()) {
1543      Info.Param = makeTemplateParameter(
1544                         const_cast<NamedDecl *>(TemplateParams->getParam(I)));
1545      return TDK_Incomplete;
1546    }
1547
1548    // Check whether we can actually use the default argument.
1549    if (CheckTemplateArgument(Param, DefArg,
1550                              FunctionTemplate,
1551                              FunctionTemplate->getLocation(),
1552                              FunctionTemplate->getSourceRange().getEnd(),
1553                              Builder,
1554                              CTAK_Deduced)) {
1555      Info.Param = makeTemplateParameter(
1556                         const_cast<NamedDecl *>(TemplateParams->getParam(I)));
1557      // FIXME: These template arguments are temporary. Free them!
1558      Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
1559                                                  Builder.size()));
1560      return TDK_SubstitutionFailure;
1561    }
1562
1563    // If we get here, we successfully used the default template argument.
1564  }
1565
1566  // Form the template argument list from the deduced template arguments.
1567  TemplateArgumentList *DeducedArgumentList
1568    = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
1569  Info.reset(DeducedArgumentList);
1570
1571  // Substitute the deduced template arguments into the function template
1572  // declaration to produce the function template specialization.
1573  DeclContext *Owner = FunctionTemplate->getDeclContext();
1574  if (FunctionTemplate->getFriendObjectKind())
1575    Owner = FunctionTemplate->getLexicalDeclContext();
1576  Specialization = cast_or_null<FunctionDecl>(
1577                      SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
1578                         MultiLevelTemplateArgumentList(*DeducedArgumentList)));
1579  if (!Specialization)
1580    return TDK_SubstitutionFailure;
1581
1582  assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
1583         FunctionTemplate->getCanonicalDecl());
1584
1585  // If the template argument list is owned by the function template
1586  // specialization, release it.
1587  if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
1588      !Trap.hasErrorOccurred())
1589    Info.take();
1590
1591  // There may have been an error that did not prevent us from constructing a
1592  // declaration. Mark the declaration invalid and return with a substitution
1593  // failure.
1594  if (Trap.hasErrorOccurred()) {
1595    Specialization->setInvalidDecl(true);
1596    return TDK_SubstitutionFailure;
1597  }
1598
1599  // If we suppressed any diagnostics while performing template argument
1600  // deduction, and if we haven't already instantiated this declaration,
1601  // keep track of these diagnostics. They'll be emitted if this specialization
1602  // is actually used.
1603  if (Info.diag_begin() != Info.diag_end()) {
1604    llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
1605      Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
1606    if (Pos == SuppressedDiagnostics.end())
1607        SuppressedDiagnostics[Specialization->getCanonicalDecl()]
1608          .append(Info.diag_begin(), Info.diag_end());
1609  }
1610
1611  return TDK_Success;
1612}
1613
1614/// Gets the type of a function for template-argument-deducton
1615/// purposes when it's considered as part of an overload set.
1616static QualType GetTypeOfFunction(ASTContext &Context,
1617                                  const OverloadExpr::FindResult &R,
1618                                  FunctionDecl *Fn) {
1619  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
1620    if (Method->isInstance()) {
1621      // An instance method that's referenced in a form that doesn't
1622      // look like a member pointer is just invalid.
1623      if (!R.HasFormOfMemberPointer) return QualType();
1624
1625      return Context.getMemberPointerType(Fn->getType(),
1626               Context.getTypeDeclType(Method->getParent()).getTypePtr());
1627    }
1628
1629  if (!R.IsAddressOfOperand) return Fn->getType();
1630  return Context.getPointerType(Fn->getType());
1631}
1632
1633/// Apply the deduction rules for overload sets.
1634///
1635/// \return the null type if this argument should be treated as an
1636/// undeduced context
1637static QualType
1638ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
1639                            Expr *Arg, QualType ParamType,
1640                            bool ParamWasReference) {
1641
1642  OverloadExpr::FindResult R = OverloadExpr::find(Arg);
1643
1644  OverloadExpr *Ovl = R.Expression;
1645
1646  // C++0x [temp.deduct.call]p4
1647  unsigned TDF = 0;
1648  if (ParamWasReference)
1649    TDF |= TDF_ParamWithReferenceType;
1650  if (R.IsAddressOfOperand)
1651    TDF |= TDF_IgnoreQualifiers;
1652
1653  // If there were explicit template arguments, we can only find
1654  // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
1655  // unambiguously name a full specialization.
1656  if (Ovl->hasExplicitTemplateArgs()) {
1657    // But we can still look for an explicit specialization.
1658    if (FunctionDecl *ExplicitSpec
1659          = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
1660      return GetTypeOfFunction(S.Context, R, ExplicitSpec);
1661    return QualType();
1662  }
1663
1664  // C++0x [temp.deduct.call]p6:
1665  //   When P is a function type, pointer to function type, or pointer
1666  //   to member function type:
1667
1668  if (!ParamType->isFunctionType() &&
1669      !ParamType->isFunctionPointerType() &&
1670      !ParamType->isMemberFunctionPointerType())
1671    return QualType();
1672
1673  QualType Match;
1674  for (UnresolvedSetIterator I = Ovl->decls_begin(),
1675         E = Ovl->decls_end(); I != E; ++I) {
1676    NamedDecl *D = (*I)->getUnderlyingDecl();
1677
1678    //   - If the argument is an overload set containing one or more
1679    //     function templates, the parameter is treated as a
1680    //     non-deduced context.
1681    if (isa<FunctionTemplateDecl>(D))
1682      return QualType();
1683
1684    FunctionDecl *Fn = cast<FunctionDecl>(D);
1685    QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
1686    if (ArgType.isNull()) continue;
1687
1688    // Function-to-pointer conversion.
1689    if (!ParamWasReference && ParamType->isPointerType() &&
1690        ArgType->isFunctionType())
1691      ArgType = S.Context.getPointerType(ArgType);
1692
1693    //   - If the argument is an overload set (not containing function
1694    //     templates), trial argument deduction is attempted using each
1695    //     of the members of the set. If deduction succeeds for only one
1696    //     of the overload set members, that member is used as the
1697    //     argument value for the deduction. If deduction succeeds for
1698    //     more than one member of the overload set the parameter is
1699    //     treated as a non-deduced context.
1700
1701    // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
1702    //   Type deduction is done independently for each P/A pair, and
1703    //   the deduced template argument values are then combined.
1704    // So we do not reject deductions which were made elsewhere.
1705    llvm::SmallVector<DeducedTemplateArgument, 8>
1706      Deduced(TemplateParams->size());
1707    TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
1708    Sema::TemplateDeductionResult Result
1709      = DeduceTemplateArguments(S, TemplateParams,
1710                                ParamType, ArgType,
1711                                Info, Deduced, TDF);
1712    if (Result) continue;
1713    if (!Match.isNull()) return QualType();
1714    Match = ArgType;
1715  }
1716
1717  return Match;
1718}
1719
1720/// \brief Perform template argument deduction from a function call
1721/// (C++ [temp.deduct.call]).
1722///
1723/// \param FunctionTemplate the function template for which we are performing
1724/// template argument deduction.
1725///
1726/// \param ExplicitTemplateArguments the explicit template arguments provided
1727/// for this call.
1728///
1729/// \param Args the function call arguments
1730///
1731/// \param NumArgs the number of arguments in Args
1732///
1733/// \param Name the name of the function being called. This is only significant
1734/// when the function template is a conversion function template, in which
1735/// case this routine will also perform template argument deduction based on
1736/// the function to which
1737///
1738/// \param Specialization if template argument deduction was successful,
1739/// this will be set to the function template specialization produced by
1740/// template argument deduction.
1741///
1742/// \param Info the argument will be updated to provide additional information
1743/// about template argument deduction.
1744///
1745/// \returns the result of template argument deduction.
1746Sema::TemplateDeductionResult
1747Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
1748                          const TemplateArgumentListInfo *ExplicitTemplateArgs,
1749                              Expr **Args, unsigned NumArgs,
1750                              FunctionDecl *&Specialization,
1751                              TemplateDeductionInfo &Info) {
1752  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1753
1754  // C++ [temp.deduct.call]p1:
1755  //   Template argument deduction is done by comparing each function template
1756  //   parameter type (call it P) with the type of the corresponding argument
1757  //   of the call (call it A) as described below.
1758  unsigned CheckArgs = NumArgs;
1759  if (NumArgs < Function->getMinRequiredArguments())
1760    return TDK_TooFewArguments;
1761  else if (NumArgs > Function->getNumParams()) {
1762    const FunctionProtoType *Proto
1763      = Function->getType()->getAs<FunctionProtoType>();
1764    if (!Proto->isVariadic())
1765      return TDK_TooManyArguments;
1766
1767    CheckArgs = Function->getNumParams();
1768  }
1769
1770  // The types of the parameters from which we will perform template argument
1771  // deduction.
1772  LocalInstantiationScope InstScope(*this);
1773  TemplateParameterList *TemplateParams
1774    = FunctionTemplate->getTemplateParameters();
1775  llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
1776  llvm::SmallVector<QualType, 4> ParamTypes;
1777  unsigned NumExplicitlySpecified = 0;
1778  if (ExplicitTemplateArgs) {
1779    TemplateDeductionResult Result =
1780      SubstituteExplicitTemplateArguments(FunctionTemplate,
1781                                          *ExplicitTemplateArgs,
1782                                          Deduced,
1783                                          ParamTypes,
1784                                          0,
1785                                          Info);
1786    if (Result)
1787      return Result;
1788
1789    NumExplicitlySpecified = Deduced.size();
1790  } else {
1791    // Just fill in the parameter types from the function declaration.
1792    for (unsigned I = 0; I != CheckArgs; ++I)
1793      ParamTypes.push_back(Function->getParamDecl(I)->getType());
1794  }
1795
1796  // Deduce template arguments from the function parameters.
1797  Deduced.resize(TemplateParams->size());
1798  for (unsigned I = 0; I != CheckArgs; ++I) {
1799    QualType ParamType = ParamTypes[I];
1800    QualType ArgType = Args[I]->getType();
1801
1802    // C++0x [temp.deduct.call]p3:
1803    //   If P is a cv-qualified type, the top level cv-qualifiers of P’s type
1804    //   are ignored for type deduction.
1805    if (ParamType.getCVRQualifiers())
1806      ParamType = ParamType.getLocalUnqualifiedType();
1807    const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
1808    if (ParamRefType) {
1809      //   [...] If P is a reference type, the type referred to by P is used
1810      //   for type deduction.
1811      ParamType = ParamRefType->getPointeeType();
1812    }
1813
1814    // Overload sets usually make this parameter an undeduced
1815    // context, but there are sometimes special circumstances.
1816    if (ArgType == Context.OverloadTy) {
1817      ArgType = ResolveOverloadForDeduction(*this, TemplateParams,
1818                                            Args[I], ParamType,
1819                                            ParamRefType != 0);
1820      if (ArgType.isNull())
1821        continue;
1822    }
1823
1824    if (ParamRefType) {
1825      // C++0x [temp.deduct.call]p3:
1826      //   [...] If P is of the form T&&, where T is a template parameter, and
1827      //   the argument is an lvalue, the type A& is used in place of A for
1828      //   type deduction.
1829      if (ParamRefType->isRValueReferenceType() &&
1830          ParamRefType->getAs<TemplateTypeParmType>() &&
1831          Args[I]->isLValue())
1832        ArgType = Context.getLValueReferenceType(ArgType);
1833    } else {
1834      // C++ [temp.deduct.call]p2:
1835      //   If P is not a reference type:
1836      //   - If A is an array type, the pointer type produced by the
1837      //     array-to-pointer standard conversion (4.2) is used in place of
1838      //     A for type deduction; otherwise,
1839      if (ArgType->isArrayType())
1840        ArgType = Context.getArrayDecayedType(ArgType);
1841      //   - If A is a function type, the pointer type produced by the
1842      //     function-to-pointer standard conversion (4.3) is used in place
1843      //     of A for type deduction; otherwise,
1844      else if (ArgType->isFunctionType())
1845        ArgType = Context.getPointerType(ArgType);
1846      else {
1847        // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
1848        //   type are ignored for type deduction.
1849        QualType CanonArgType = Context.getCanonicalType(ArgType);
1850        if (ArgType.getCVRQualifiers())
1851          ArgType = ArgType.getUnqualifiedType();
1852      }
1853    }
1854
1855    // C++0x [temp.deduct.call]p4:
1856    //   In general, the deduction process attempts to find template argument
1857    //   values that will make the deduced A identical to A (after the type A
1858    //   is transformed as described above). [...]
1859    unsigned TDF = TDF_SkipNonDependent;
1860
1861    //     - If the original P is a reference type, the deduced A (i.e., the
1862    //       type referred to by the reference) can be more cv-qualified than
1863    //       the transformed A.
1864    if (ParamRefType)
1865      TDF |= TDF_ParamWithReferenceType;
1866    //     - The transformed A can be another pointer or pointer to member
1867    //       type that can be converted to the deduced A via a qualification
1868    //       conversion (4.4).
1869    if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
1870        ArgType->isObjCObjectPointerType())
1871      TDF |= TDF_IgnoreQualifiers;
1872    //     - If P is a class and P has the form simple-template-id, then the
1873    //       transformed A can be a derived class of the deduced A. Likewise,
1874    //       if P is a pointer to a class of the form simple-template-id, the
1875    //       transformed A can be a pointer to a derived class pointed to by
1876    //       the deduced A.
1877    if (isSimpleTemplateIdType(ParamType) ||
1878        (isa<PointerType>(ParamType) &&
1879         isSimpleTemplateIdType(
1880                              ParamType->getAs<PointerType>()->getPointeeType())))
1881      TDF |= TDF_DerivedClass;
1882
1883    if (TemplateDeductionResult Result
1884        = ::DeduceTemplateArguments(*this, TemplateParams,
1885                                    ParamType, ArgType, Info, Deduced,
1886                                    TDF))
1887      return Result;
1888
1889    // FIXME: we need to check that the deduced A is the same as A,
1890    // modulo the various allowed differences.
1891  }
1892
1893  return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
1894                                         NumExplicitlySpecified,
1895                                         Specialization, Info);
1896}
1897
1898/// \brief Deduce template arguments when taking the address of a function
1899/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
1900/// a template.
1901///
1902/// \param FunctionTemplate the function template for which we are performing
1903/// template argument deduction.
1904///
1905/// \param ExplicitTemplateArguments the explicitly-specified template
1906/// arguments.
1907///
1908/// \param ArgFunctionType the function type that will be used as the
1909/// "argument" type (A) when performing template argument deduction from the
1910/// function template's function type. This type may be NULL, if there is no
1911/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
1912///
1913/// \param Specialization if template argument deduction was successful,
1914/// this will be set to the function template specialization produced by
1915/// template argument deduction.
1916///
1917/// \param Info the argument will be updated to provide additional information
1918/// about template argument deduction.
1919///
1920/// \returns the result of template argument deduction.
1921Sema::TemplateDeductionResult
1922Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
1923                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
1924                              QualType ArgFunctionType,
1925                              FunctionDecl *&Specialization,
1926                              TemplateDeductionInfo &Info) {
1927  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1928  TemplateParameterList *TemplateParams
1929    = FunctionTemplate->getTemplateParameters();
1930  QualType FunctionType = Function->getType();
1931
1932  // Substitute any explicit template arguments.
1933  LocalInstantiationScope InstScope(*this);
1934  llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
1935  unsigned NumExplicitlySpecified = 0;
1936  llvm::SmallVector<QualType, 4> ParamTypes;
1937  if (ExplicitTemplateArgs) {
1938    if (TemplateDeductionResult Result
1939          = SubstituteExplicitTemplateArguments(FunctionTemplate,
1940                                                *ExplicitTemplateArgs,
1941                                                Deduced, ParamTypes,
1942                                                &FunctionType, Info))
1943      return Result;
1944
1945    NumExplicitlySpecified = Deduced.size();
1946  }
1947
1948  // Template argument deduction for function templates in a SFINAE context.
1949  // Trap any errors that might occur.
1950  SFINAETrap Trap(*this);
1951
1952  Deduced.resize(TemplateParams->size());
1953
1954  if (!ArgFunctionType.isNull()) {
1955    // Deduce template arguments from the function type.
1956    if (TemplateDeductionResult Result
1957          = ::DeduceTemplateArguments(*this, TemplateParams,
1958                                      FunctionType, ArgFunctionType, Info,
1959                                      Deduced, 0))
1960      return Result;
1961  }
1962
1963  if (TemplateDeductionResult Result
1964        = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
1965                                          NumExplicitlySpecified,
1966                                          Specialization, Info))
1967    return Result;
1968
1969  // If the requested function type does not match the actual type of the
1970  // specialization, template argument deduction fails.
1971  if (!ArgFunctionType.isNull() &&
1972      !Context.hasSameType(ArgFunctionType, Specialization->getType()))
1973    return TDK_NonDeducedMismatch;
1974
1975  return TDK_Success;
1976}
1977
1978/// \brief Deduce template arguments for a templated conversion
1979/// function (C++ [temp.deduct.conv]) and, if successful, produce a
1980/// conversion function template specialization.
1981Sema::TemplateDeductionResult
1982Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
1983                              QualType ToType,
1984                              CXXConversionDecl *&Specialization,
1985                              TemplateDeductionInfo &Info) {
1986  CXXConversionDecl *Conv
1987    = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
1988  QualType FromType = Conv->getConversionType();
1989
1990  // Canonicalize the types for deduction.
1991  QualType P = Context.getCanonicalType(FromType);
1992  QualType A = Context.getCanonicalType(ToType);
1993
1994  // C++0x [temp.deduct.conv]p3:
1995  //   If P is a reference type, the type referred to by P is used for
1996  //   type deduction.
1997  if (const ReferenceType *PRef = P->getAs<ReferenceType>())
1998    P = PRef->getPointeeType();
1999
2000  // C++0x [temp.deduct.conv]p3:
2001  //   If A is a reference type, the type referred to by A is used
2002  //   for type deduction.
2003  if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2004    A = ARef->getPointeeType();
2005  // C++ [temp.deduct.conv]p2:
2006  //
2007  //   If A is not a reference type:
2008  else {
2009    assert(!A->isReferenceType() && "Reference types were handled above");
2010
2011    //   - If P is an array type, the pointer type produced by the
2012    //     array-to-pointer standard conversion (4.2) is used in place
2013    //     of P for type deduction; otherwise,
2014    if (P->isArrayType())
2015      P = Context.getArrayDecayedType(P);
2016    //   - If P is a function type, the pointer type produced by the
2017    //     function-to-pointer standard conversion (4.3) is used in
2018    //     place of P for type deduction; otherwise,
2019    else if (P->isFunctionType())
2020      P = Context.getPointerType(P);
2021    //   - If P is a cv-qualified type, the top level cv-qualifiers of
2022    //     P’s type are ignored for type deduction.
2023    else
2024      P = P.getUnqualifiedType();
2025
2026    // C++0x [temp.deduct.conv]p3:
2027    //   If A is a cv-qualified type, the top level cv-qualifiers of A’s
2028    //   type are ignored for type deduction.
2029    A = A.getUnqualifiedType();
2030  }
2031
2032  // Template argument deduction for function templates in a SFINAE context.
2033  // Trap any errors that might occur.
2034  SFINAETrap Trap(*this);
2035
2036  // C++ [temp.deduct.conv]p1:
2037  //   Template argument deduction is done by comparing the return
2038  //   type of the template conversion function (call it P) with the
2039  //   type that is required as the result of the conversion (call it
2040  //   A) as described in 14.8.2.4.
2041  TemplateParameterList *TemplateParams
2042    = FunctionTemplate->getTemplateParameters();
2043  llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2044  Deduced.resize(TemplateParams->size());
2045
2046  // C++0x [temp.deduct.conv]p4:
2047  //   In general, the deduction process attempts to find template
2048  //   argument values that will make the deduced A identical to
2049  //   A. However, there are two cases that allow a difference:
2050  unsigned TDF = 0;
2051  //     - If the original A is a reference type, A can be more
2052  //       cv-qualified than the deduced A (i.e., the type referred to
2053  //       by the reference)
2054  if (ToType->isReferenceType())
2055    TDF |= TDF_ParamWithReferenceType;
2056  //     - The deduced A can be another pointer or pointer to member
2057  //       type that can be converted to A via a qualification
2058  //       conversion.
2059  //
2060  // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2061  // both P and A are pointers or member pointers. In this case, we
2062  // just ignore cv-qualifiers completely).
2063  if ((P->isPointerType() && A->isPointerType()) ||
2064      (P->isMemberPointerType() && P->isMemberPointerType()))
2065    TDF |= TDF_IgnoreQualifiers;
2066  if (TemplateDeductionResult Result
2067        = ::DeduceTemplateArguments(*this, TemplateParams,
2068                                    P, A, Info, Deduced, TDF))
2069    return Result;
2070
2071  // FIXME: we need to check that the deduced A is the same as A,
2072  // modulo the various allowed differences.
2073
2074  // Finish template argument deduction.
2075  LocalInstantiationScope InstScope(*this);
2076  FunctionDecl *Spec = 0;
2077  TemplateDeductionResult Result
2078    = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2079                                      Info);
2080  Specialization = cast_or_null<CXXConversionDecl>(Spec);
2081  return Result;
2082}
2083
2084/// \brief Deduce template arguments for a function template when there is
2085/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2086///
2087/// \param FunctionTemplate the function template for which we are performing
2088/// template argument deduction.
2089///
2090/// \param ExplicitTemplateArguments the explicitly-specified template
2091/// arguments.
2092///
2093/// \param Specialization if template argument deduction was successful,
2094/// this will be set to the function template specialization produced by
2095/// template argument deduction.
2096///
2097/// \param Info the argument will be updated to provide additional information
2098/// about template argument deduction.
2099///
2100/// \returns the result of template argument deduction.
2101Sema::TemplateDeductionResult
2102Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2103                           const TemplateArgumentListInfo *ExplicitTemplateArgs,
2104                              FunctionDecl *&Specialization,
2105                              TemplateDeductionInfo &Info) {
2106  return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2107                                 QualType(), Specialization, Info);
2108}
2109
2110/// \brief Stores the result of comparing the qualifiers of two types.
2111enum DeductionQualifierComparison {
2112  NeitherMoreQualified = 0,
2113  ParamMoreQualified,
2114  ArgMoreQualified
2115};
2116
2117/// \brief Deduce the template arguments during partial ordering by comparing
2118/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2119///
2120/// \param S the semantic analysis object within which we are deducing
2121///
2122/// \param TemplateParams the template parameters that we are deducing
2123///
2124/// \param ParamIn the parameter type
2125///
2126/// \param ArgIn the argument type
2127///
2128/// \param Info information about the template argument deduction itself
2129///
2130/// \param Deduced the deduced template arguments
2131///
2132/// \returns the result of template argument deduction so far. Note that a
2133/// "success" result means that template argument deduction has not yet failed,
2134/// but it may still fail, later, for other reasons.
2135static Sema::TemplateDeductionResult
2136DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
2137                                        TemplateParameterList *TemplateParams,
2138                                             QualType ParamIn, QualType ArgIn,
2139                                             TemplateDeductionInfo &Info,
2140                      llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2141   llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2142  CanQualType Param = S.Context.getCanonicalType(ParamIn);
2143  CanQualType Arg = S.Context.getCanonicalType(ArgIn);
2144
2145  // C++0x [temp.deduct.partial]p5:
2146  //   Before the partial ordering is done, certain transformations are
2147  //   performed on the types used for partial ordering:
2148  //     - If P is a reference type, P is replaced by the type referred to.
2149  CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
2150  if (!ParamRef.isNull())
2151    Param = ParamRef->getPointeeType();
2152
2153  //     - If A is a reference type, A is replaced by the type referred to.
2154  CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
2155  if (!ArgRef.isNull())
2156    Arg = ArgRef->getPointeeType();
2157
2158  if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
2159    // C++0x [temp.deduct.partial]p6:
2160    //   If both P and A were reference types (before being replaced with the
2161    //   type referred to above), determine which of the two types (if any) is
2162    //   more cv-qualified than the other; otherwise the types are considered to
2163    //   be equally cv-qualified for partial ordering purposes. The result of this
2164    //   determination will be used below.
2165    //
2166    // We save this information for later, using it only when deduction
2167    // succeeds in both directions.
2168    DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2169    if (Param.isMoreQualifiedThan(Arg))
2170      QualifierResult = ParamMoreQualified;
2171    else if (Arg.isMoreQualifiedThan(Param))
2172      QualifierResult = ArgMoreQualified;
2173    QualifierComparisons->push_back(QualifierResult);
2174  }
2175
2176  // C++0x [temp.deduct.partial]p7:
2177  //   Remove any top-level cv-qualifiers:
2178  //     - If P is a cv-qualified type, P is replaced by the cv-unqualified
2179  //       version of P.
2180  Param = Param.getUnqualifiedType();
2181  //     - If A is a cv-qualified type, A is replaced by the cv-unqualified
2182  //       version of A.
2183  Arg = Arg.getUnqualifiedType();
2184
2185  // C++0x [temp.deduct.partial]p8:
2186  //   Using the resulting types P and A the deduction is then done as
2187  //   described in 14.9.2.5. If deduction succeeds for a given type, the type
2188  //   from the argument template is considered to be at least as specialized
2189  //   as the type from the parameter template.
2190  return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
2191                                 Deduced, TDF_None);
2192}
2193
2194static void
2195MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2196                           bool OnlyDeduced,
2197                           unsigned Level,
2198                           llvm::SmallVectorImpl<bool> &Deduced);
2199
2200/// \brief If this is a non-static member function,
2201static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2202                                                CXXMethodDecl *Method,
2203                                 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2204  if (Method->isStatic())
2205    return;
2206
2207  // C++ [over.match.funcs]p4:
2208  //
2209  //   For non-static member functions, the type of the implicit
2210  //   object parameter is
2211  //     — "lvalue reference to cv X" for functions declared without a
2212  //       ref-qualifier or with the & ref-qualifier
2213  //     - "rvalue reference to cv X" for functions declared with the
2214  //       && ref-qualifier
2215  //
2216  // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2217  QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2218  ArgTy = Context.getQualifiedType(ArgTy,
2219                        Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2220  ArgTy = Context.getLValueReferenceType(ArgTy);
2221  ArgTypes.push_back(ArgTy);
2222}
2223
2224/// \brief Determine whether the function template \p FT1 is at least as
2225/// specialized as \p FT2.
2226static bool isAtLeastAsSpecializedAs(Sema &S,
2227                                     SourceLocation Loc,
2228                                     FunctionTemplateDecl *FT1,
2229                                     FunctionTemplateDecl *FT2,
2230                                     TemplatePartialOrderingContext TPOC,
2231    llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2232  FunctionDecl *FD1 = FT1->getTemplatedDecl();
2233  FunctionDecl *FD2 = FT2->getTemplatedDecl();
2234  const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2235  const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2236
2237  assert(Proto1 && Proto2 && "Function templates must have prototypes");
2238  TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
2239  llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2240  Deduced.resize(TemplateParams->size());
2241
2242  // C++0x [temp.deduct.partial]p3:
2243  //   The types used to determine the ordering depend on the context in which
2244  //   the partial ordering is done:
2245  TemplateDeductionInfo Info(S.Context, Loc);
2246  CXXMethodDecl *Method1 = 0;
2247  CXXMethodDecl *Method2 = 0;
2248  bool IsNonStatic2 = false;
2249  bool IsNonStatic1 = false;
2250  unsigned Skip2 = 0;
2251  switch (TPOC) {
2252  case TPOC_Call: {
2253    //   - In the context of a function call, the function parameter types are
2254    //     used.
2255    Method1 = dyn_cast<CXXMethodDecl>(FD1);
2256    Method2 = dyn_cast<CXXMethodDecl>(FD2);
2257    IsNonStatic1 = Method1 && !Method1->isStatic();
2258    IsNonStatic2 = Method2 && !Method2->isStatic();
2259
2260    // C++0x [temp.func.order]p3:
2261    //   [...] If only one of the function templates is a non-static
2262    //   member, that function template is considered to have a new
2263    //   first parameter inserted in its function parameter list. The
2264    //   new parameter is of type "reference to cv A," where cv are
2265    //   the cv-qualifiers of the function template (if any) and A is
2266    //   the class of which the function template is a member.
2267    //
2268    // C++98/03 doesn't have this provision, so instead we drop the
2269    // first argument of the free function or static member, which
2270    // seems to match existing practice.
2271    llvm::SmallVector<QualType, 4> Args1;
2272    unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2273      IsNonStatic2 && !IsNonStatic1;
2274    if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
2275      MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2276    Args1.insert(Args1.end(),
2277                 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
2278
2279    llvm::SmallVector<QualType, 4> Args2;
2280    Skip2 = !S.getLangOptions().CPlusPlus0x &&
2281      IsNonStatic1 && !IsNonStatic2;
2282    if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
2283      MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2284    Args2.insert(Args2.end(),
2285                 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
2286
2287    unsigned NumParams = std::min(Args1.size(), Args2.size());
2288    for (unsigned I = 0; I != NumParams; ++I)
2289      if (DeduceTemplateArgumentsDuringPartialOrdering(S,
2290                                                       TemplateParams,
2291                                                       Args2[I],
2292                                                       Args1[I],
2293                                                       Info,
2294                                                       Deduced,
2295                                                       QualifierComparisons))
2296        return false;
2297
2298    break;
2299  }
2300
2301  case TPOC_Conversion:
2302    //   - In the context of a call to a conversion operator, the return types
2303    //     of the conversion function templates are used.
2304    if (DeduceTemplateArgumentsDuringPartialOrdering(S,
2305                                                     TemplateParams,
2306                                                     Proto2->getResultType(),
2307                                                     Proto1->getResultType(),
2308                                                     Info,
2309                                                     Deduced,
2310                                                     QualifierComparisons))
2311      return false;
2312    break;
2313
2314  case TPOC_Other:
2315    //   - In other contexts (14.6.6.2) the function template’s function type
2316    //     is used.
2317    if (DeduceTemplateArgumentsDuringPartialOrdering(S,
2318                                                     TemplateParams,
2319                                                     FD2->getType(),
2320                                                     FD1->getType(),
2321                                                     Info,
2322                                                     Deduced,
2323                                                     QualifierComparisons))
2324      return false;
2325    break;
2326  }
2327
2328  // C++0x [temp.deduct.partial]p11:
2329  //   In most cases, all template parameters must have values in order for
2330  //   deduction to succeed, but for partial ordering purposes a template
2331  //   parameter may remain without a value provided it is not used in the
2332  //   types being used for partial ordering. [ Note: a template parameter used
2333  //   in a non-deduced context is considered used. -end note]
2334  unsigned ArgIdx = 0, NumArgs = Deduced.size();
2335  for (; ArgIdx != NumArgs; ++ArgIdx)
2336    if (Deduced[ArgIdx].isNull())
2337      break;
2338
2339  if (ArgIdx == NumArgs) {
2340    // All template arguments were deduced. FT1 is at least as specialized
2341    // as FT2.
2342    return true;
2343  }
2344
2345  // Figure out which template parameters were used.
2346  llvm::SmallVector<bool, 4> UsedParameters;
2347  UsedParameters.resize(TemplateParams->size());
2348  switch (TPOC) {
2349  case TPOC_Call: {
2350    unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
2351    if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
2352      ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
2353                                   TemplateParams->getDepth(), UsedParameters);
2354    for (unsigned I = Skip2; I < NumParams; ++I)
2355      ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
2356                                   TemplateParams->getDepth(),
2357                                   UsedParameters);
2358    break;
2359  }
2360
2361  case TPOC_Conversion:
2362    ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
2363                                 TemplateParams->getDepth(),
2364                                 UsedParameters);
2365    break;
2366
2367  case TPOC_Other:
2368    ::MarkUsedTemplateParameters(S, FD2->getType(), false,
2369                                 TemplateParams->getDepth(),
2370                                 UsedParameters);
2371    break;
2372  }
2373
2374  for (; ArgIdx != NumArgs; ++ArgIdx)
2375    // If this argument had no value deduced but was used in one of the types
2376    // used for partial ordering, then deduction fails.
2377    if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
2378      return false;
2379
2380  return true;
2381}
2382
2383
2384/// \brief Returns the more specialized function template according
2385/// to the rules of function template partial ordering (C++ [temp.func.order]).
2386///
2387/// \param FT1 the first function template
2388///
2389/// \param FT2 the second function template
2390///
2391/// \param TPOC the context in which we are performing partial ordering of
2392/// function templates.
2393///
2394/// \returns the more specialized function template. If neither
2395/// template is more specialized, returns NULL.
2396FunctionTemplateDecl *
2397Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
2398                                 FunctionTemplateDecl *FT2,
2399                                 SourceLocation Loc,
2400                                 TemplatePartialOrderingContext TPOC) {
2401  llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
2402  bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
2403  bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
2404                                          &QualifierComparisons);
2405
2406  if (Better1 != Better2) // We have a clear winner
2407    return Better1? FT1 : FT2;
2408
2409  if (!Better1 && !Better2) // Neither is better than the other
2410    return 0;
2411
2412
2413  // C++0x [temp.deduct.partial]p10:
2414  //   If for each type being considered a given template is at least as
2415  //   specialized for all types and more specialized for some set of types and
2416  //   the other template is not more specialized for any types or is not at
2417  //   least as specialized for any types, then the given template is more
2418  //   specialized than the other template. Otherwise, neither template is more
2419  //   specialized than the other.
2420  Better1 = false;
2421  Better2 = false;
2422  for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
2423    // C++0x [temp.deduct.partial]p9:
2424    //   If, for a given type, deduction succeeds in both directions (i.e., the
2425    //   types are identical after the transformations above) and if the type
2426    //   from the argument template is more cv-qualified than the type from the
2427    //   parameter template (as described above) that type is considered to be
2428    //   more specialized than the other. If neither type is more cv-qualified
2429    //   than the other then neither type is more specialized than the other.
2430    switch (QualifierComparisons[I]) {
2431      case NeitherMoreQualified:
2432        break;
2433
2434      case ParamMoreQualified:
2435        Better1 = true;
2436        if (Better2)
2437          return 0;
2438        break;
2439
2440      case ArgMoreQualified:
2441        Better2 = true;
2442        if (Better1)
2443          return 0;
2444        break;
2445    }
2446  }
2447
2448  assert(!(Better1 && Better2) && "Should have broken out in the loop above");
2449  if (Better1)
2450    return FT1;
2451  else if (Better2)
2452    return FT2;
2453  else
2454    return 0;
2455}
2456
2457/// \brief Determine if the two templates are equivalent.
2458static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
2459  if (T1 == T2)
2460    return true;
2461
2462  if (!T1 || !T2)
2463    return false;
2464
2465  return T1->getCanonicalDecl() == T2->getCanonicalDecl();
2466}
2467
2468/// \brief Retrieve the most specialized of the given function template
2469/// specializations.
2470///
2471/// \param SpecBegin the start iterator of the function template
2472/// specializations that we will be comparing.
2473///
2474/// \param SpecEnd the end iterator of the function template
2475/// specializations, paired with \p SpecBegin.
2476///
2477/// \param TPOC the partial ordering context to use to compare the function
2478/// template specializations.
2479///
2480/// \param Loc the location where the ambiguity or no-specializations
2481/// diagnostic should occur.
2482///
2483/// \param NoneDiag partial diagnostic used to diagnose cases where there are
2484/// no matching candidates.
2485///
2486/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
2487/// occurs.
2488///
2489/// \param CandidateDiag partial diagnostic used for each function template
2490/// specialization that is a candidate in the ambiguous ordering. One parameter
2491/// in this diagnostic should be unbound, which will correspond to the string
2492/// describing the template arguments for the function template specialization.
2493///
2494/// \param Index if non-NULL and the result of this function is non-nULL,
2495/// receives the index corresponding to the resulting function template
2496/// specialization.
2497///
2498/// \returns the most specialized function template specialization, if
2499/// found. Otherwise, returns SpecEnd.
2500///
2501/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
2502/// template argument deduction.
2503UnresolvedSetIterator
2504Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
2505                         UnresolvedSetIterator SpecEnd,
2506                         TemplatePartialOrderingContext TPOC,
2507                         SourceLocation Loc,
2508                         const PartialDiagnostic &NoneDiag,
2509                         const PartialDiagnostic &AmbigDiag,
2510                         const PartialDiagnostic &CandidateDiag) {
2511  if (SpecBegin == SpecEnd) {
2512    Diag(Loc, NoneDiag);
2513    return SpecEnd;
2514  }
2515
2516  if (SpecBegin + 1 == SpecEnd)
2517    return SpecBegin;
2518
2519  // Find the function template that is better than all of the templates it
2520  // has been compared to.
2521  UnresolvedSetIterator Best = SpecBegin;
2522  FunctionTemplateDecl *BestTemplate
2523    = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
2524  assert(BestTemplate && "Not a function template specialization?");
2525  for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
2526    FunctionTemplateDecl *Challenger
2527      = cast<FunctionDecl>(*I)->getPrimaryTemplate();
2528    assert(Challenger && "Not a function template specialization?");
2529    if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
2530                                                  Loc, TPOC),
2531                       Challenger)) {
2532      Best = I;
2533      BestTemplate = Challenger;
2534    }
2535  }
2536
2537  // Make sure that the "best" function template is more specialized than all
2538  // of the others.
2539  bool Ambiguous = false;
2540  for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
2541    FunctionTemplateDecl *Challenger
2542      = cast<FunctionDecl>(*I)->getPrimaryTemplate();
2543    if (I != Best &&
2544        !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
2545                                                   Loc, TPOC),
2546                        BestTemplate)) {
2547      Ambiguous = true;
2548      break;
2549    }
2550  }
2551
2552  if (!Ambiguous) {
2553    // We found an answer. Return it.
2554    return Best;
2555  }
2556
2557  // Diagnose the ambiguity.
2558  Diag(Loc, AmbigDiag);
2559
2560  // FIXME: Can we order the candidates in some sane way?
2561  for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
2562    Diag((*I)->getLocation(), CandidateDiag)
2563      << getTemplateArgumentBindingsText(
2564        cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
2565                    *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
2566
2567  return SpecEnd;
2568}
2569
2570/// \brief Returns the more specialized class template partial specialization
2571/// according to the rules of partial ordering of class template partial
2572/// specializations (C++ [temp.class.order]).
2573///
2574/// \param PS1 the first class template partial specialization
2575///
2576/// \param PS2 the second class template partial specialization
2577///
2578/// \returns the more specialized class template partial specialization. If
2579/// neither partial specialization is more specialized, returns NULL.
2580ClassTemplatePartialSpecializationDecl *
2581Sema::getMoreSpecializedPartialSpecialization(
2582                                  ClassTemplatePartialSpecializationDecl *PS1,
2583                                  ClassTemplatePartialSpecializationDecl *PS2,
2584                                              SourceLocation Loc) {
2585  // C++ [temp.class.order]p1:
2586  //   For two class template partial specializations, the first is at least as
2587  //   specialized as the second if, given the following rewrite to two
2588  //   function templates, the first function template is at least as
2589  //   specialized as the second according to the ordering rules for function
2590  //   templates (14.6.6.2):
2591  //     - the first function template has the same template parameters as the
2592  //       first partial specialization and has a single function parameter
2593  //       whose type is a class template specialization with the template
2594  //       arguments of the first partial specialization, and
2595  //     - the second function template has the same template parameters as the
2596  //       second partial specialization and has a single function parameter
2597  //       whose type is a class template specialization with the template
2598  //       arguments of the second partial specialization.
2599  //
2600  // Rather than synthesize function templates, we merely perform the
2601  // equivalent partial ordering by performing deduction directly on
2602  // the template arguments of the class template partial
2603  // specializations. This computation is slightly simpler than the
2604  // general problem of function template partial ordering, because
2605  // class template partial specializations are more constrained. We
2606  // know that every template parameter is deducible from the class
2607  // template partial specialization's template arguments, for
2608  // example.
2609  llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2610  TemplateDeductionInfo Info(Context, Loc);
2611
2612  QualType PT1 = PS1->getInjectedSpecializationType();
2613  QualType PT2 = PS2->getInjectedSpecializationType();
2614
2615  // Determine whether PS1 is at least as specialized as PS2
2616  Deduced.resize(PS2->getTemplateParameters()->size());
2617  bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
2618                                                  PS2->getTemplateParameters(),
2619                                                               PT2,
2620                                                               PT1,
2621                                                               Info,
2622                                                               Deduced,
2623                                                               0);
2624  if (Better1) {
2625    InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
2626                               Deduced.data(), Deduced.size(), Info);
2627    Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
2628                                                 PS1->getTemplateArgs(),
2629                                                 Deduced, Info);
2630  }
2631
2632  // Determine whether PS2 is at least as specialized as PS1
2633  Deduced.clear();
2634  Deduced.resize(PS1->getTemplateParameters()->size());
2635  bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
2636                                                  PS1->getTemplateParameters(),
2637                                                               PT1,
2638                                                               PT2,
2639                                                               Info,
2640                                                               Deduced,
2641                                                               0);
2642  if (Better2) {
2643    InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
2644                               Deduced.data(), Deduced.size(), Info);
2645    Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
2646                                                 PS2->getTemplateArgs(),
2647                                                 Deduced, Info);
2648  }
2649
2650  if (Better1 == Better2)
2651    return 0;
2652
2653  return Better1? PS1 : PS2;
2654}
2655
2656static void
2657MarkUsedTemplateParameters(Sema &SemaRef,
2658                           const TemplateArgument &TemplateArg,
2659                           bool OnlyDeduced,
2660                           unsigned Depth,
2661                           llvm::SmallVectorImpl<bool> &Used);
2662
2663/// \brief Mark the template parameters that are used by the given
2664/// expression.
2665static void
2666MarkUsedTemplateParameters(Sema &SemaRef,
2667                           const Expr *E,
2668                           bool OnlyDeduced,
2669                           unsigned Depth,
2670                           llvm::SmallVectorImpl<bool> &Used) {
2671  // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
2672  // find other occurrences of template parameters.
2673  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
2674  if (!DRE)
2675    return;
2676
2677  const NonTypeTemplateParmDecl *NTTP
2678    = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2679  if (!NTTP)
2680    return;
2681
2682  if (NTTP->getDepth() == Depth)
2683    Used[NTTP->getIndex()] = true;
2684}
2685
2686/// \brief Mark the template parameters that are used by the given
2687/// nested name specifier.
2688static void
2689MarkUsedTemplateParameters(Sema &SemaRef,
2690                           NestedNameSpecifier *NNS,
2691                           bool OnlyDeduced,
2692                           unsigned Depth,
2693                           llvm::SmallVectorImpl<bool> &Used) {
2694  if (!NNS)
2695    return;
2696
2697  MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
2698                             Used);
2699  MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
2700                             OnlyDeduced, Depth, Used);
2701}
2702
2703/// \brief Mark the template parameters that are used by the given
2704/// template name.
2705static void
2706MarkUsedTemplateParameters(Sema &SemaRef,
2707                           TemplateName Name,
2708                           bool OnlyDeduced,
2709                           unsigned Depth,
2710                           llvm::SmallVectorImpl<bool> &Used) {
2711  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2712    if (TemplateTemplateParmDecl *TTP
2713          = dyn_cast<TemplateTemplateParmDecl>(Template)) {
2714      if (TTP->getDepth() == Depth)
2715        Used[TTP->getIndex()] = true;
2716    }
2717    return;
2718  }
2719
2720  if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
2721    MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
2722                               Depth, Used);
2723  if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
2724    MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
2725                               Depth, Used);
2726}
2727
2728/// \brief Mark the template parameters that are used by the given
2729/// type.
2730static void
2731MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2732                           bool OnlyDeduced,
2733                           unsigned Depth,
2734                           llvm::SmallVectorImpl<bool> &Used) {
2735  if (T.isNull())
2736    return;
2737
2738  // Non-dependent types have nothing deducible
2739  if (!T->isDependentType())
2740    return;
2741
2742  T = SemaRef.Context.getCanonicalType(T);
2743  switch (T->getTypeClass()) {
2744  case Type::Pointer:
2745    MarkUsedTemplateParameters(SemaRef,
2746                               cast<PointerType>(T)->getPointeeType(),
2747                               OnlyDeduced,
2748                               Depth,
2749                               Used);
2750    break;
2751
2752  case Type::BlockPointer:
2753    MarkUsedTemplateParameters(SemaRef,
2754                               cast<BlockPointerType>(T)->getPointeeType(),
2755                               OnlyDeduced,
2756                               Depth,
2757                               Used);
2758    break;
2759
2760  case Type::LValueReference:
2761  case Type::RValueReference:
2762    MarkUsedTemplateParameters(SemaRef,
2763                               cast<ReferenceType>(T)->getPointeeType(),
2764                               OnlyDeduced,
2765                               Depth,
2766                               Used);
2767    break;
2768
2769  case Type::MemberPointer: {
2770    const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
2771    MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
2772                               Depth, Used);
2773    MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
2774                               OnlyDeduced, Depth, Used);
2775    break;
2776  }
2777
2778  case Type::DependentSizedArray:
2779    MarkUsedTemplateParameters(SemaRef,
2780                               cast<DependentSizedArrayType>(T)->getSizeExpr(),
2781                               OnlyDeduced, Depth, Used);
2782    // Fall through to check the element type
2783
2784  case Type::ConstantArray:
2785  case Type::IncompleteArray:
2786    MarkUsedTemplateParameters(SemaRef,
2787                               cast<ArrayType>(T)->getElementType(),
2788                               OnlyDeduced, Depth, Used);
2789    break;
2790
2791  case Type::Vector:
2792  case Type::ExtVector:
2793    MarkUsedTemplateParameters(SemaRef,
2794                               cast<VectorType>(T)->getElementType(),
2795                               OnlyDeduced, Depth, Used);
2796    break;
2797
2798  case Type::DependentSizedExtVector: {
2799    const DependentSizedExtVectorType *VecType
2800      = cast<DependentSizedExtVectorType>(T);
2801    MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
2802                               Depth, Used);
2803    MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
2804                               Depth, Used);
2805    break;
2806  }
2807
2808  case Type::FunctionProto: {
2809    const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2810    MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
2811                               Depth, Used);
2812    for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
2813      MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
2814                                 Depth, Used);
2815    break;
2816  }
2817
2818  case Type::TemplateTypeParm: {
2819    const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
2820    if (TTP->getDepth() == Depth)
2821      Used[TTP->getIndex()] = true;
2822    break;
2823  }
2824
2825  case Type::InjectedClassName:
2826    T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
2827    // fall through
2828
2829  case Type::TemplateSpecialization: {
2830    const TemplateSpecializationType *Spec
2831      = cast<TemplateSpecializationType>(T);
2832    MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
2833                               Depth, Used);
2834    for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
2835      MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
2836                                 Used);
2837    break;
2838  }
2839
2840  case Type::Complex:
2841    if (!OnlyDeduced)
2842      MarkUsedTemplateParameters(SemaRef,
2843                                 cast<ComplexType>(T)->getElementType(),
2844                                 OnlyDeduced, Depth, Used);
2845    break;
2846
2847  case Type::DependentName:
2848    if (!OnlyDeduced)
2849      MarkUsedTemplateParameters(SemaRef,
2850                                 cast<DependentNameType>(T)->getQualifier(),
2851                                 OnlyDeduced, Depth, Used);
2852    break;
2853
2854  case Type::DependentTemplateSpecialization: {
2855    const DependentTemplateSpecializationType *Spec
2856      = cast<DependentTemplateSpecializationType>(T);
2857    if (!OnlyDeduced)
2858      MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
2859                                 OnlyDeduced, Depth, Used);
2860    for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
2861      MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
2862                                 Used);
2863    break;
2864  }
2865
2866  case Type::TypeOf:
2867    if (!OnlyDeduced)
2868      MarkUsedTemplateParameters(SemaRef,
2869                                 cast<TypeOfType>(T)->getUnderlyingType(),
2870                                 OnlyDeduced, Depth, Used);
2871    break;
2872
2873  case Type::TypeOfExpr:
2874    if (!OnlyDeduced)
2875      MarkUsedTemplateParameters(SemaRef,
2876                                 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
2877                                 OnlyDeduced, Depth, Used);
2878    break;
2879
2880  case Type::Decltype:
2881    if (!OnlyDeduced)
2882      MarkUsedTemplateParameters(SemaRef,
2883                                 cast<DecltypeType>(T)->getUnderlyingExpr(),
2884                                 OnlyDeduced, Depth, Used);
2885    break;
2886
2887  case Type::PackExpansion:
2888    MarkUsedTemplateParameters(SemaRef,
2889                               cast<PackExpansionType>(T)->getPattern(),
2890                               OnlyDeduced, Depth, Used);
2891    break;
2892
2893  // None of these types have any template parameters in them.
2894  case Type::Builtin:
2895  case Type::VariableArray:
2896  case Type::FunctionNoProto:
2897  case Type::Record:
2898  case Type::Enum:
2899  case Type::ObjCInterface:
2900  case Type::ObjCObject:
2901  case Type::ObjCObjectPointer:
2902  case Type::UnresolvedUsing:
2903#define TYPE(Class, Base)
2904#define ABSTRACT_TYPE(Class, Base)
2905#define DEPENDENT_TYPE(Class, Base)
2906#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2907#include "clang/AST/TypeNodes.def"
2908    break;
2909  }
2910}
2911
2912/// \brief Mark the template parameters that are used by this
2913/// template argument.
2914static void
2915MarkUsedTemplateParameters(Sema &SemaRef,
2916                           const TemplateArgument &TemplateArg,
2917                           bool OnlyDeduced,
2918                           unsigned Depth,
2919                           llvm::SmallVectorImpl<bool> &Used) {
2920  switch (TemplateArg.getKind()) {
2921  case TemplateArgument::Null:
2922  case TemplateArgument::Integral:
2923    case TemplateArgument::Declaration:
2924    break;
2925
2926  case TemplateArgument::Type:
2927    MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
2928                               Depth, Used);
2929    break;
2930
2931  case TemplateArgument::Template:
2932    MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsTemplate(),
2933                               OnlyDeduced, Depth, Used);
2934    break;
2935
2936  case TemplateArgument::Expression:
2937    MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
2938                               Depth, Used);
2939    break;
2940
2941  case TemplateArgument::Pack:
2942    for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
2943                                      PEnd = TemplateArg.pack_end();
2944         P != PEnd; ++P)
2945      MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
2946    break;
2947  }
2948}
2949
2950/// \brief Mark the template parameters can be deduced by the given
2951/// template argument list.
2952///
2953/// \param TemplateArgs the template argument list from which template
2954/// parameters will be deduced.
2955///
2956/// \param Deduced a bit vector whose elements will be set to \c true
2957/// to indicate when the corresponding template parameter will be
2958/// deduced.
2959void
2960Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
2961                                 bool OnlyDeduced, unsigned Depth,
2962                                 llvm::SmallVectorImpl<bool> &Used) {
2963  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2964    ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
2965                                 Depth, Used);
2966}
2967
2968/// \brief Marks all of the template parameters that will be deduced by a
2969/// call to the given function template.
2970void
2971Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
2972                                    llvm::SmallVectorImpl<bool> &Deduced) {
2973  TemplateParameterList *TemplateParams
2974    = FunctionTemplate->getTemplateParameters();
2975  Deduced.clear();
2976  Deduced.resize(TemplateParams->size());
2977
2978  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2979  for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
2980    ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
2981                                 true, TemplateParams->getDepth(), Deduced);
2982}
2983