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