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