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