blob: bf4533d6998caf4757d7a87894086141bfe154c4 [file] [log] [blame]
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===/
12
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Sema.h"
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/DeclSpec.h"
John McCall7cd088e2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000016#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000017#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000019#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/StmtVisitor.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
Benjamin Kramer013b3662012-01-30 16:17:39 +000023#include "llvm/ADT/SmallBitVector.h"
Richard Smith34b41d92011-02-20 03:19:35 +000024#include "TreeTransform.h"
Douglas Gregor8a514912009-09-14 18:39:43 +000025#include <algorithm>
Douglas Gregor508f1c82009-06-26 23:10:12 +000026
27namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000028 using namespace sema;
29
Douglas Gregor508f1c82009-06-26 23:10:12 +000030 /// \brief Various flags that control template argument deduction.
31 ///
32 /// These flags can be bitwise-OR'd together.
33 enum TemplateDeductionFlags {
34 /// \brief No template argument deduction flags, which indicates the
35 /// strictest results for template argument deduction (as used for, e.g.,
36 /// matching class template partial specializations).
37 TDF_None = 0,
38 /// \brief Within template argument deduction from a function call, we are
39 /// matching with a parameter type for which the original parameter was
40 /// a reference.
41 TDF_ParamWithReferenceType = 0x1,
42 /// \brief Within template argument deduction from a function call, we
43 /// are matching in a case where we ignore cv-qualifiers.
44 TDF_IgnoreQualifiers = 0x02,
45 /// \brief Within template argument deduction from a function call,
46 /// we are matching in a case where we can perform template argument
Douglas Gregor41128772009-06-26 23:27:24 +000047 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor12820292009-09-14 20:00:47 +000048 TDF_DerivedClass = 0x04,
49 /// \brief Allow non-dependent types to differ, e.g., when performing
50 /// template argument deduction from a function call where conversions
51 /// may apply.
Douglas Gregor73b3cf62011-01-25 17:19:08 +000052 TDF_SkipNonDependent = 0x08,
53 /// \brief Whether we are performing template argument deduction for
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000054 /// parameters and arguments in a top-level template argument
Douglas Gregor73b3cf62011-01-25 17:19:08 +000055 TDF_TopLevelParameterTypeList = 0x10
Douglas Gregor508f1c82009-06-26 23:10:12 +000056 };
57}
58
Douglas Gregor0b9247f2009-06-04 00:03:07 +000059using namespace clang;
60
Douglas Gregor9d0e4412010-03-26 05:50:28 +000061/// \brief Compare two APSInts, extending and switching the sign as
62/// necessary to compare their values regardless of underlying type.
63static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
64 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000065 X = X.extend(Y.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000066 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000067 Y = Y.extend(X.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000068
69 // If there is a signedness mismatch, correct it.
70 if (X.isSigned() != Y.isSigned()) {
71 // If the signed value is negative, then the values cannot be the same.
72 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
73 return false;
74
75 Y.setIsSigned(true);
76 X.setIsSigned(true);
77 }
78
79 return X == Y;
80}
81
Douglas Gregorf67875d2009-06-12 18:26:56 +000082static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +000083DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +000084 TemplateParameterList *TemplateParams,
85 const TemplateArgument &Param,
Douglas Gregor77d6bb92011-01-11 22:21:24 +000086 TemplateArgument Arg,
John McCall2a7fb272010-08-25 05:32:35 +000087 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +000088 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregord708c722009-06-09 16:35:58 +000089
Douglas Gregorb939a192011-01-21 17:29:42 +000090/// \brief Whether template argument deduction for two reference parameters
91/// resulted in the argument type, parameter type, or neither type being more
92/// qualified than the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000093enum DeductionQualifierComparison {
94 NeitherMoreQualified = 0,
95 ParamMoreQualified,
96 ArgMoreQualified
Douglas Gregor5c7bf422011-01-11 17:34:58 +000097};
98
Douglas Gregorb939a192011-01-21 17:29:42 +000099/// \brief Stores the result of comparing two reference parameters while
100/// performing template argument deduction for partial ordering of function
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000101/// templates.
Douglas Gregorb939a192011-01-21 17:29:42 +0000102struct RefParamPartialOrderingComparison {
103 /// \brief Whether the parameter type is an rvalue reference type.
104 bool ParamIsRvalueRef;
105 /// \brief Whether the argument type is an rvalue reference type.
106 bool ArgIsRvalueRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000107
Douglas Gregorb939a192011-01-21 17:29:42 +0000108 /// \brief Whether the parameter or argument (or neither) is more qualified.
109 DeductionQualifierComparison Qualifiers;
110};
111
112
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000113
Douglas Gregor20a55e22010-12-22 18:17:10 +0000114static Sema::TemplateDeductionResult
Sebastian Redlbb95e512012-01-17 22:49:52 +0000115DeduceTemplateArgumentsByTypeMatch(Sema &S,
116 TemplateParameterList *TemplateParams,
117 QualType Param,
118 QualType Arg,
119 TemplateDeductionInfo &Info,
120 SmallVectorImpl<DeducedTemplateArgument> &
121 Deduced,
122 unsigned TDF,
123 bool PartialOrdering = false,
124 SmallVectorImpl<RefParamPartialOrderingComparison> *
Douglas Gregorb939a192011-01-21 17:29:42 +0000125 RefParamComparisons = 0);
Douglas Gregor603cfb42011-01-05 23:12:31 +0000126
127static Sema::TemplateDeductionResult
128DeduceTemplateArguments(Sema &S,
129 TemplateParameterList *TemplateParams,
Douglas Gregor20a55e22010-12-22 18:17:10 +0000130 const TemplateArgument *Params, unsigned NumParams,
131 const TemplateArgument *Args, unsigned NumArgs,
132 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000133 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor0972c862010-12-22 18:55:49 +0000134 bool NumberOfArgumentsMustMatch = true);
Douglas Gregor20a55e22010-12-22 18:17:10 +0000135
Douglas Gregor199d9912009-06-05 00:53:49 +0000136/// \brief If the given expression is of a form that permits the deduction
137/// of a non-type template parameter, return the declaration of that
138/// non-type template parameter.
139static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
Richard Smith5a343d72012-07-08 04:37:51 +0000140 // If we are within an alias template, the expression may have undergone
141 // any number of parameter substitutions already.
142 while (1) {
143 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
144 E = IC->getSubExpr();
145 else if (SubstNonTypeTemplateParmExpr *Subst =
146 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
147 E = Subst->getReplacement();
148 else
149 break;
150 }
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Douglas Gregor199d9912009-06-05 00:53:49 +0000152 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
153 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Douglas Gregor199d9912009-06-05 00:53:49 +0000155 return 0;
156}
157
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000158/// \brief Determine whether two declaration pointers refer to the same
159/// declaration.
160static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000161 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
162 X = NX->getUnderlyingDecl();
163 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
164 Y = NY->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000165
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000166 return X->getCanonicalDecl() == Y->getCanonicalDecl();
167}
168
169/// \brief Verify that the given, deduced template arguments are compatible.
170///
171/// \returns The deduced template argument, or a NULL template argument if
172/// the deduced template arguments were incompatible.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000173static DeducedTemplateArgument
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000174checkDeducedTemplateArguments(ASTContext &Context,
175 const DeducedTemplateArgument &X,
176 const DeducedTemplateArgument &Y) {
177 // We have no deduction for one or both of the arguments; they're compatible.
178 if (X.isNull())
179 return Y;
180 if (Y.isNull())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000181 return X;
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000182
183 switch (X.getKind()) {
184 case TemplateArgument::Null:
185 llvm_unreachable("Non-deduced template arguments handled above");
186
187 case TemplateArgument::Type:
188 // If two template type arguments have the same type, they're compatible.
189 if (Y.getKind() == TemplateArgument::Type &&
190 Context.hasSameType(X.getAsType(), Y.getAsType()))
191 return X;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000192
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000193 return DeducedTemplateArgument();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000194
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000195 case TemplateArgument::Integral:
196 // If we deduced a constant in one case and either a dependent expression or
197 // declaration in another case, keep the integral constant.
198 // If both are integral constants with the same value, keep that value.
199 if (Y.getKind() == TemplateArgument::Expression ||
200 Y.getKind() == TemplateArgument::Declaration ||
201 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer85524372012-06-07 15:09:51 +0000202 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000203 return DeducedTemplateArgument(X,
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000204 X.wasDeducedFromArrayBound() &&
205 Y.wasDeducedFromArrayBound());
206
207 // All other combinations are incompatible.
208 return DeducedTemplateArgument();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000209
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000210 case TemplateArgument::Template:
211 if (Y.getKind() == TemplateArgument::Template &&
212 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
213 return X;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000214
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000215 // All other combinations are incompatible.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000216 return DeducedTemplateArgument();
Douglas Gregora7fc9012011-01-05 18:58:31 +0000217
218 case TemplateArgument::TemplateExpansion:
219 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000220 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregora7fc9012011-01-05 18:58:31 +0000221 Y.getAsTemplateOrTemplatePattern()))
222 return X;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000223
Douglas Gregora7fc9012011-01-05 18:58:31 +0000224 // All other combinations are incompatible.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000225 return DeducedTemplateArgument();
Douglas Gregora7fc9012011-01-05 18:58:31 +0000226
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000227 case TemplateArgument::Expression:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000228 // If we deduced a dependent expression in one case and either an integral
229 // constant or a declaration in another case, keep the integral constant
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000230 // or declaration.
231 if (Y.getKind() == TemplateArgument::Integral ||
232 Y.getKind() == TemplateArgument::Declaration)
233 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
234 Y.wasDeducedFromArrayBound());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000235
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000236 if (Y.getKind() == TemplateArgument::Expression) {
237 // Compare the expressions for equality
238 llvm::FoldingSetNodeID ID1, ID2;
239 X.getAsExpr()->Profile(ID1, Context, true);
240 Y.getAsExpr()->Profile(ID2, Context, true);
241 if (ID1 == ID2)
242 return X;
243 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000244
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000245 // All other combinations are incompatible.
246 return DeducedTemplateArgument();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000247
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000248 case TemplateArgument::Declaration:
249 // If we deduced a declaration and a dependent expression, keep the
250 // declaration.
251 if (Y.getKind() == TemplateArgument::Expression)
252 return X;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000253
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000254 // If we deduced a declaration and an integral constant, keep the
255 // integral constant.
256 if (Y.getKind() == TemplateArgument::Integral)
257 return Y;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000258
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000259 // If we deduced two declarations, make sure they they refer to the
260 // same declaration.
261 if (Y.getKind() == TemplateArgument::Declaration &&
Eli Friedmand7a6b162012-09-26 02:36:12 +0000262 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()) &&
263 X.isDeclForReferenceParam() == Y.isDeclForReferenceParam())
264 return X;
265
266 // All other combinations are incompatible.
267 return DeducedTemplateArgument();
268
269 case TemplateArgument::NullPtr:
270 // If we deduced a null pointer and a dependent expression, keep the
271 // null pointer.
272 if (Y.getKind() == TemplateArgument::Expression)
273 return X;
274
275 // If we deduced a null pointer and an integral constant, keep the
276 // integral constant.
277 if (Y.getKind() == TemplateArgument::Integral)
278 return Y;
279
280 // If we deduced two null pointers, make sure they have the same type.
281 if (Y.getKind() == TemplateArgument::NullPtr &&
282 Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000283 return X;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000284
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000285 // All other combinations are incompatible.
286 return DeducedTemplateArgument();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000287
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000288 case TemplateArgument::Pack:
289 if (Y.getKind() != TemplateArgument::Pack ||
290 X.pack_size() != Y.pack_size())
291 return DeducedTemplateArgument();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000292
293 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000294 XAEnd = X.pack_end(),
295 YA = Y.pack_begin();
296 XA != XAEnd; ++XA, ++YA) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000297 if (checkDeducedTemplateArguments(Context,
298 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
Douglas Gregor135ffa72011-01-05 21:00:53 +0000299 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
300 .isNull())
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000301 return DeducedTemplateArgument();
302 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000303
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000304 return X;
305 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000306
David Blaikie30263482012-01-20 21:50:17 +0000307 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000308}
309
Mike Stump1eb44332009-09-09 15:08:12 +0000310/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000311/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000312static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000313DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump1eb44332009-09-09 15:08:12 +0000314 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000315 llvm::APSInt Value, QualType ValueType,
Douglas Gregor02024a92010-03-28 02:42:43 +0000316 bool DeducedFromArrayBound,
John McCall2a7fb272010-08-25 05:32:35 +0000317 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000318 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000319 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000320 "Cannot deduce non-type template argument with depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Benjamin Kramer85524372012-06-07 15:09:51 +0000322 DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType,
323 DeducedFromArrayBound);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000324 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000325 Deduced[NTTP->getIndex()],
326 NewDeduced);
327 if (Result.isNull()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000328 Info.Param = NTTP;
329 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000330 Info.SecondArg = NewDeduced;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000331 return Sema::TDK_Inconsistent;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000332 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000333
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000334 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000335 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000336}
337
Mike Stump1eb44332009-09-09 15:08:12 +0000338/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000339/// from the given type- or value-dependent expression.
340///
341/// \returns true if deduction succeeded, false otherwise.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000342static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000343DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000344 NonTypeTemplateParmDecl *NTTP,
345 Expr *Value,
John McCall2a7fb272010-08-25 05:32:35 +0000346 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000347 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000348 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000349 "Cannot deduce non-type template argument with depth > 0");
350 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
351 "Expression template argument must be type- or value-dependent.");
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000353 DeducedTemplateArgument NewDeduced(Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000354 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
355 Deduced[NTTP->getIndex()],
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000356 NewDeduced);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000357
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000358 if (Result.isNull()) {
359 Info.Param = NTTP;
360 Info.FirstArg = Deduced[NTTP->getIndex()];
361 Info.SecondArg = NewDeduced;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000362 return Sema::TDK_Inconsistent;
Douglas Gregor199d9912009-06-05 00:53:49 +0000363 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000364
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000365 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000366 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000367}
368
Douglas Gregor15755cb2009-11-13 23:45:44 +0000369/// \brief Deduce the value of the given non-type template parameter
370/// from the given declaration.
371///
372/// \returns true if deduction succeeded, false otherwise.
373static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000374DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor15755cb2009-11-13 23:45:44 +0000375 NonTypeTemplateParmDecl *NTTP,
Eli Friedmand7a6b162012-09-26 02:36:12 +0000376 ValueDecl *D,
John McCall2a7fb272010-08-25 05:32:35 +0000377 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000378 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor15755cb2009-11-13 23:45:44 +0000379 assert(NTTP->getDepth() == 0 &&
380 "Cannot deduce non-type template argument with depth > 0");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000381
Eli Friedmand7a6b162012-09-26 02:36:12 +0000382 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : 0;
383 TemplateArgument New(D, NTTP->getType()->isReferenceType());
384 DeducedTemplateArgument NewDeduced(New);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000385 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000386 Deduced[NTTP->getIndex()],
387 NewDeduced);
388 if (Result.isNull()) {
389 Info.Param = NTTP;
390 Info.FirstArg = Deduced[NTTP->getIndex()];
391 Info.SecondArg = NewDeduced;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000392 return Sema::TDK_Inconsistent;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000393 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000394
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000395 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000396 return Sema::TDK_Success;
397}
398
Douglas Gregorf67875d2009-06-12 18:26:56 +0000399static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000400DeduceTemplateArguments(Sema &S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000401 TemplateParameterList *TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000402 TemplateName Param,
403 TemplateName Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000404 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000405 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000406 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000407 if (!ParamDecl) {
408 // The parameter type is dependent and is not a template template parameter,
409 // so there is nothing that we can deduce.
410 return Sema::TDK_Success;
411 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000412
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000413 if (TemplateTemplateParmDecl *TempParam
414 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000415 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000416 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000417 Deduced[TempParam->getIndex()],
418 NewDeduced);
419 if (Result.isNull()) {
420 Info.Param = TempParam;
421 Info.FirstArg = Deduced[TempParam->getIndex()];
422 Info.SecondArg = NewDeduced;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000423 return Sema::TDK_Inconsistent;
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000424 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000425
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000426 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000427 return Sema::TDK_Success;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000428 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000429
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000430 // Verify that the two template names are equivalent.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000431 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000432 return Sema::TDK_Success;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000433
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000434 // Mismatch of non-dependent template parameter to argument.
435 Info.FirstArg = TemplateArgument(Param);
436 Info.SecondArg = TemplateArgument(Arg);
437 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord708c722009-06-09 16:35:58 +0000438}
439
Mike Stump1eb44332009-09-09 15:08:12 +0000440/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000441/// type (which is a template-id) with the template argument type.
442///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000443/// \param S the Sema
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000444///
445/// \param TemplateParams the template parameters that we are deducing
446///
447/// \param Param the parameter type
448///
449/// \param Arg the argument type
450///
451/// \param Info information about the template argument deduction itself
452///
453/// \param Deduced the deduced template arguments
454///
455/// \returns the result of template argument deduction so far. Note that a
456/// "success" result means that template argument deduction has not yet failed,
457/// but it may still fail, later, for other reasons.
458static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000459DeduceTemplateArguments(Sema &S,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000460 TemplateParameterList *TemplateParams,
461 const TemplateSpecializationType *Param,
462 QualType Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000463 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000464 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCall467b27b2009-10-22 20:10:53 +0000465 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000467 // Check whether the template argument is a dependent template-id.
Mike Stump1eb44332009-09-09 15:08:12 +0000468 if (const TemplateSpecializationType *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000469 = dyn_cast<TemplateSpecializationType>(Arg)) {
470 // Perform template argument deduction for the template name.
471 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000472 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000473 Param->getTemplateName(),
474 SpecArg->getTemplateName(),
475 Info, Deduced))
476 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000479 // Perform template argument deduction on each template
Douglas Gregor0972c862010-12-22 18:55:49 +0000480 // argument. Ignore any missing/extra arguments, since they could be
481 // filled in by default arguments.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000482 return DeduceTemplateArguments(S, TemplateParams,
483 Param->getArgs(), Param->getNumArgs(),
Douglas Gregor0972c862010-12-22 18:55:49 +0000484 SpecArg->getArgs(), SpecArg->getNumArgs(),
485 Info, Deduced,
486 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000487 }
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000489 // If the argument type is a class template specialization, we
490 // perform template argument deduction using its template
491 // arguments.
492 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
493 if (!RecordArg)
494 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000495
496 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000497 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
498 if (!SpecArg)
499 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000501 // Perform template argument deduction for the template name.
502 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000503 = DeduceTemplateArguments(S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000504 TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000505 Param->getTemplateName(),
506 TemplateName(SpecArg->getSpecializedTemplate()),
507 Info, Deduced))
508 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Douglas Gregor20a55e22010-12-22 18:17:10 +0000510 // Perform template argument deduction for the template arguments.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000511 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor20a55e22010-12-22 18:17:10 +0000512 Param->getArgs(), Param->getNumArgs(),
513 SpecArg->getTemplateArgs().data(),
514 SpecArg->getTemplateArgs().size(),
515 Info, Deduced);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000516}
517
John McCallcd05e812010-08-28 22:14:41 +0000518/// \brief Determines whether the given type is an opaque type that
519/// might be more qualified when instantiated.
520static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
521 switch (T->getTypeClass()) {
522 case Type::TypeOfExpr:
523 case Type::TypeOf:
524 case Type::DependentName:
525 case Type::Decltype:
526 case Type::UnresolvedUsing:
John McCall62c28c82011-01-18 07:41:22 +0000527 case Type::TemplateTypeParm:
John McCallcd05e812010-08-28 22:14:41 +0000528 return true;
529
530 case Type::ConstantArray:
531 case Type::IncompleteArray:
532 case Type::VariableArray:
533 case Type::DependentSizedArray:
534 return IsPossiblyOpaquelyQualifiedType(
535 cast<ArrayType>(T)->getElementType());
536
537 default:
538 return false;
539 }
540}
541
Douglas Gregord3731192011-01-10 07:32:04 +0000542/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000543static std::pair<unsigned, unsigned>
Douglas Gregord3731192011-01-10 07:32:04 +0000544getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor603cfb42011-01-05 23:12:31 +0000545 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
546 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000547
Douglas Gregor603cfb42011-01-05 23:12:31 +0000548 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
549 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000550
Douglas Gregor603cfb42011-01-05 23:12:31 +0000551 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
552 return std::make_pair(TTP->getDepth(), TTP->getIndex());
553}
554
Douglas Gregord3731192011-01-10 07:32:04 +0000555/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000556static std::pair<unsigned, unsigned>
Douglas Gregord3731192011-01-10 07:32:04 +0000557getDepthAndIndex(UnexpandedParameterPack UPP) {
558 if (const TemplateTypeParmType *TTP
559 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
560 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000561
Douglas Gregord3731192011-01-10 07:32:04 +0000562 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
563}
564
Douglas Gregor603cfb42011-01-05 23:12:31 +0000565/// \brief Helper function to build a TemplateParameter when we don't
566/// know its type statically.
567static TemplateParameter makeTemplateParameter(Decl *D) {
568 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
569 return TemplateParameter(TTP);
570 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
571 return TemplateParameter(NTTP);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000572
Douglas Gregor603cfb42011-01-05 23:12:31 +0000573 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
574}
575
Douglas Gregor54293852011-01-10 17:35:05 +0000576/// \brief Prepare to perform template argument deduction for all of the
577/// arguments in a set of argument packs.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000578static void PrepareArgumentPackDeduction(Sema &S,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000579 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Bill Wendling4fe5be02012-02-22 09:38:11 +0000580 ArrayRef<unsigned> PackIndices,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000581 SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
582 SmallVectorImpl<
583 SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks) {
Douglas Gregor54293852011-01-10 17:35:05 +0000584 // Save the deduced template arguments for each parameter pack expanded
585 // by this pack expansion, then clear out the deduction.
586 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
587 // Save the previously-deduced argument pack, then clear it out so that we
588 // can deduce a new argument pack.
589 SavedPacks[I] = Deduced[PackIndices[I]];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000590 Deduced[PackIndices[I]] = TemplateArgument();
591
Richard Smitha8eaf002012-08-23 06:16:52 +0000592 if (!S.CurrentInstantiationScope)
593 continue;
594
Richard Smith6964b3f2012-09-07 02:06:42 +0000595 // If the template argument pack was explicitly specified, add that to
Douglas Gregor54293852011-01-10 17:35:05 +0000596 // the set of deduced arguments.
597 const TemplateArgument *ExplicitArgs;
598 unsigned NumExplicitArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000599 if (NamedDecl *PartiallySubstitutedPack
Douglas Gregor54293852011-01-10 17:35:05 +0000600 = S.CurrentInstantiationScope->getPartiallySubstitutedPack(
601 &ExplicitArgs,
602 &NumExplicitArgs)) {
603 if (getDepthAndIndex(PartiallySubstitutedPack).second == PackIndices[I])
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000604 NewlyDeducedPacks[I].append(ExplicitArgs,
Douglas Gregor54293852011-01-10 17:35:05 +0000605 ExplicitArgs + NumExplicitArgs);
606 }
607 }
608}
609
Douglas Gregor0216f812011-01-10 17:53:52 +0000610/// \brief Finish template argument deduction for a set of argument packs,
611/// producing the argument packs and checking for consistency with prior
612/// deductions.
613static Sema::TemplateDeductionResult
614FinishArgumentPackDeduction(Sema &S,
615 TemplateParameterList *TemplateParams,
616 bool HasAnyArguments,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000617 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Bill Wendling341785e2012-02-22 09:51:33 +0000618 ArrayRef<unsigned> PackIndices,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000619 SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
620 SmallVectorImpl<
621 SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks,
Douglas Gregor0216f812011-01-10 17:53:52 +0000622 TemplateDeductionInfo &Info) {
623 // Build argument packs for each of the parameter packs expanded by this
624 // pack expansion.
625 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
626 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
627 // We were not able to deduce anything for this parameter pack,
628 // so just restore the saved argument pack.
629 Deduced[PackIndices[I]] = SavedPacks[I];
630 continue;
631 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000632
Douglas Gregor0216f812011-01-10 17:53:52 +0000633 DeducedTemplateArgument NewPack;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000634
Douglas Gregor0216f812011-01-10 17:53:52 +0000635 if (NewlyDeducedPacks[I].empty()) {
636 // If we deduced an empty argument pack, create it now.
Eli Friedmand7a6b162012-09-26 02:36:12 +0000637 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
Douglas Gregor0216f812011-01-10 17:53:52 +0000638 } else {
639 TemplateArgument *ArgumentPack
Douglas Gregor203e6a32011-01-11 23:09:57 +0000640 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
Douglas Gregor0216f812011-01-10 17:53:52 +0000641 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
642 ArgumentPack);
643 NewPack
Douglas Gregor203e6a32011-01-11 23:09:57 +0000644 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
645 NewlyDeducedPacks[I].size()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000646 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
Douglas Gregor0216f812011-01-10 17:53:52 +0000647 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000648
Douglas Gregor0216f812011-01-10 17:53:52 +0000649 DeducedTemplateArgument Result
650 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
651 if (Result.isNull()) {
652 Info.Param
653 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
654 Info.FirstArg = SavedPacks[I];
655 Info.SecondArg = NewPack;
656 return Sema::TDK_Inconsistent;
657 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000658
Douglas Gregor0216f812011-01-10 17:53:52 +0000659 Deduced[PackIndices[I]] = Result;
660 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000661
Douglas Gregor0216f812011-01-10 17:53:52 +0000662 return Sema::TDK_Success;
663}
664
Douglas Gregor603cfb42011-01-05 23:12:31 +0000665/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000666/// types to the list of argument types, as in the parameter-type-lists of
667/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor603cfb42011-01-05 23:12:31 +0000668///
669/// \param S The semantic analysis object within which we are deducing
670///
671/// \param TemplateParams The template parameters that we are deducing
672///
673/// \param Params The list of parameter types
674///
675/// \param NumParams The number of types in \c Params
676///
677/// \param Args The list of argument types
678///
679/// \param NumArgs The number of types in \c Args
680///
681/// \param Info information about the template argument deduction itself
682///
683/// \param Deduced the deduced template arguments
684///
685/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
686/// how template argument deduction is performed.
687///
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000688/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000689/// deduction for during partial ordering for a call
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000690/// (C++0x [temp.deduct.partial]).
691///
Douglas Gregorb939a192011-01-21 17:29:42 +0000692/// \param RefParamComparisons If we're performing template argument deduction
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000693/// in the context of partial ordering, the set of qualifier comparisons.
694///
Douglas Gregor603cfb42011-01-05 23:12:31 +0000695/// \returns the result of template argument deduction so far. Note that a
696/// "success" result means that template argument deduction has not yet failed,
697/// but it may still fail, later, for other reasons.
698static Sema::TemplateDeductionResult
699DeduceTemplateArguments(Sema &S,
700 TemplateParameterList *TemplateParams,
701 const QualType *Params, unsigned NumParams,
702 const QualType *Args, unsigned NumArgs,
703 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000704 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000705 unsigned TDF,
706 bool PartialOrdering = false,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000707 SmallVectorImpl<RefParamPartialOrderingComparison> *
Douglas Gregorb939a192011-01-21 17:29:42 +0000708 RefParamComparisons = 0) {
Douglas Gregor0bbacf82011-01-05 23:23:17 +0000709 // Fast-path check to see if we have too many/too few arguments.
710 if (NumParams != NumArgs &&
711 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
712 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000713 return Sema::TDK_NonDeducedMismatch;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000714
Douglas Gregor603cfb42011-01-05 23:12:31 +0000715 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000716 // Similarly, if P has a form that contains (T), then each parameter type
717 // Pi of the respective parameter-type- list of P is compared with the
718 // corresponding parameter type Ai of the corresponding parameter-type-list
719 // of A. [...]
Douglas Gregor603cfb42011-01-05 23:12:31 +0000720 unsigned ArgIdx = 0, ParamIdx = 0;
721 for (; ParamIdx != NumParams; ++ParamIdx) {
722 // Check argument types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000723 const PackExpansionType *Expansion
Douglas Gregor603cfb42011-01-05 23:12:31 +0000724 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
725 if (!Expansion) {
726 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000727
Douglas Gregor603cfb42011-01-05 23:12:31 +0000728 // Make sure we have an argument.
729 if (ArgIdx >= NumArgs)
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000730 return Sema::TDK_NonDeducedMismatch;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000731
Douglas Gregor77d6bb92011-01-11 22:21:24 +0000732 if (isa<PackExpansionType>(Args[ArgIdx])) {
733 // C++0x [temp.deduct.type]p22:
734 // If the original function parameter associated with A is a function
735 // parameter pack and the function parameter associated with P is not
736 // a function parameter pack, then template argument deduction fails.
737 return Sema::TDK_NonDeducedMismatch;
738 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000739
Douglas Gregor603cfb42011-01-05 23:12:31 +0000740 if (Sema::TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +0000741 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
742 Params[ParamIdx], Args[ArgIdx],
743 Info, Deduced, TDF,
744 PartialOrdering,
745 RefParamComparisons))
Douglas Gregor603cfb42011-01-05 23:12:31 +0000746 return Result;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000747
Douglas Gregor603cfb42011-01-05 23:12:31 +0000748 ++ArgIdx;
749 continue;
750 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000751
Douglas Gregor7d5c0c12011-01-11 01:52:23 +0000752 // C++0x [temp.deduct.type]p5:
753 // The non-deduced contexts are:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000754 // - A function parameter pack that does not occur at the end of the
Douglas Gregor7d5c0c12011-01-11 01:52:23 +0000755 // parameter-declaration-clause.
756 if (ParamIdx + 1 < NumParams)
757 return Sema::TDK_Success;
758
Douglas Gregor603cfb42011-01-05 23:12:31 +0000759 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000760 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor603cfb42011-01-05 23:12:31 +0000761 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000762 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor603cfb42011-01-05 23:12:31 +0000763 // comparison deduces template arguments for subsequent positions in the
764 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000765
Douglas Gregor603cfb42011-01-05 23:12:31 +0000766 // Compute the set of template parameter indices that correspond to
767 // parameter packs expanded by the pack expansion.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000768 SmallVector<unsigned, 2> PackIndices;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000769 QualType Pattern = Expansion->getPattern();
770 {
Benjamin Kramer013b3662012-01-30 16:17:39 +0000771 llvm::SmallBitVector SawIndices(TemplateParams->size());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000772 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000773 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
774 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
775 unsigned Depth, Index;
776 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
777 if (Depth == 0 && !SawIndices[Index]) {
778 SawIndices[Index] = true;
779 PackIndices.push_back(Index);
780 }
781 }
782 }
783 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
784
Douglas Gregord3731192011-01-10 07:32:04 +0000785 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000786 // expanded by this pack expansion (the outer index) and for each
Douglas Gregord3731192011-01-10 07:32:04 +0000787 // template argument (the inner SmallVectors).
Chris Lattner5f9e2722011-07-23 10:55:15 +0000788 SmallVector<SmallVector<DeducedTemplateArgument, 4>, 2>
Douglas Gregord3731192011-01-10 07:32:04 +0000789 NewlyDeducedPacks(PackIndices.size());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000790 SmallVector<DeducedTemplateArgument, 2>
Douglas Gregor54293852011-01-10 17:35:05 +0000791 SavedPacks(PackIndices.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000792 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
Douglas Gregor54293852011-01-10 17:35:05 +0000793 NewlyDeducedPacks);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000794
Douglas Gregor603cfb42011-01-05 23:12:31 +0000795 bool HasAnyArguments = false;
796 for (; ArgIdx < NumArgs; ++ArgIdx) {
797 HasAnyArguments = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000798
Douglas Gregor603cfb42011-01-05 23:12:31 +0000799 // Deduce template arguments from the pattern.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000800 if (Sema::TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +0000801 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
802 Args[ArgIdx], Info, Deduced,
803 TDF, PartialOrdering,
804 RefParamComparisons))
Douglas Gregor603cfb42011-01-05 23:12:31 +0000805 return Result;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000806
Douglas Gregor603cfb42011-01-05 23:12:31 +0000807 // Capture the deduced template arguments for each parameter pack expanded
808 // by this pack expansion, add them to the list of arguments we've deduced
809 // for that pack, then clear out the deduced argument.
810 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
811 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
812 if (!DeducedArg.isNull()) {
813 NewlyDeducedPacks[I].push_back(DeducedArg);
814 DeducedArg = DeducedTemplateArgument();
815 }
816 }
817 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000818
Douglas Gregor603cfb42011-01-05 23:12:31 +0000819 // Build argument packs for each of the parameter packs expanded by this
820 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +0000821 if (Sema::TemplateDeductionResult Result
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000822 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
Douglas Gregor0216f812011-01-10 17:53:52 +0000823 Deduced, PackIndices, SavedPacks,
824 NewlyDeducedPacks, Info))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000825 return Result;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000826 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000827
Douglas Gregor603cfb42011-01-05 23:12:31 +0000828 // Make sure we don't have any extra arguments.
829 if (ArgIdx < NumArgs)
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000830 return Sema::TDK_NonDeducedMismatch;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000831
Douglas Gregor603cfb42011-01-05 23:12:31 +0000832 return Sema::TDK_Success;
833}
834
Douglas Gregor61d0b6b2011-04-28 00:56:09 +0000835/// \brief Determine whether the parameter has qualifiers that are either
836/// inconsistent with or a superset of the argument's qualifiers.
837static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
838 QualType ArgType) {
839 Qualifiers ParamQs = ParamType.getQualifiers();
840 Qualifiers ArgQs = ArgType.getQualifiers();
841
842 if (ParamQs == ArgQs)
843 return false;
844
845 // Mismatched (but not missing) Objective-C GC attributes.
846 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
847 ParamQs.hasObjCGCAttr())
848 return true;
849
850 // Mismatched (but not missing) address spaces.
851 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
852 ParamQs.hasAddressSpace())
853 return true;
854
John McCallf85e1932011-06-15 23:02:42 +0000855 // Mismatched (but not missing) Objective-C lifetime qualifiers.
856 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
857 ParamQs.hasObjCLifetime())
858 return true;
859
Douglas Gregor61d0b6b2011-04-28 00:56:09 +0000860 // CVR qualifier superset.
861 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
862 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
863 == ParamQs.getCVRQualifiers());
864}
865
Douglas Gregor500d3312009-06-26 18:27:22 +0000866/// \brief Deduce the template arguments by comparing the parameter type and
867/// the argument type (C++ [temp.deduct.type]).
868///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000869/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000870///
871/// \param TemplateParams the template parameters that we are deducing
872///
873/// \param ParamIn the parameter type
874///
875/// \param ArgIn the argument type
876///
877/// \param Info information about the template argument deduction itself
878///
879/// \param Deduced the deduced template arguments
880///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000881/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000882/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000883///
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000884/// \param PartialOrdering Whether we're performing template argument deduction
885/// in the context of partial ordering (C++0x [temp.deduct.partial]).
886///
Douglas Gregorb939a192011-01-21 17:29:42 +0000887/// \param RefParamComparisons If we're performing template argument deduction
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000888/// in the context of partial ordering, the set of qualifier comparisons.
889///
Douglas Gregor500d3312009-06-26 18:27:22 +0000890/// \returns the result of template argument deduction so far. Note that a
891/// "success" result means that template argument deduction has not yet failed,
892/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000893static Sema::TemplateDeductionResult
Sebastian Redlbb95e512012-01-17 22:49:52 +0000894DeduceTemplateArgumentsByTypeMatch(Sema &S,
895 TemplateParameterList *TemplateParams,
896 QualType ParamIn, QualType ArgIn,
897 TemplateDeductionInfo &Info,
898 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
899 unsigned TDF,
900 bool PartialOrdering,
901 SmallVectorImpl<RefParamPartialOrderingComparison> *
902 RefParamComparisons) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000903 // We only want to look at the canonical types, since typedefs and
904 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000905 QualType Param = S.Context.getCanonicalType(ParamIn);
906 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000907
Douglas Gregor77d6bb92011-01-11 22:21:24 +0000908 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000909 // This isn't explicitly called out
Douglas Gregor77d6bb92011-01-11 22:21:24 +0000910 if (const PackExpansionType *ArgExpansion
911 = dyn_cast<PackExpansionType>(Arg))
912 Arg = ArgExpansion->getPattern();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000913
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000914 if (PartialOrdering) {
915 // C++0x [temp.deduct.partial]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000916 // Before the partial ordering is done, certain transformations are
917 // performed on the types used for partial ordering:
918 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000919 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
920 if (ParamRef)
921 Param = ParamRef->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000922
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000923 // - If A is a reference type, A is replaced by the type referred to.
924 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
925 if (ArgRef)
926 Arg = ArgRef->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000927
Douglas Gregorb939a192011-01-21 17:29:42 +0000928 if (RefParamComparisons && ParamRef && ArgRef) {
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000929 // C++0x [temp.deduct.partial]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000930 // If both P and A were reference types (before being replaced with the
931 // type referred to above), determine which of the two types (if any) is
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000932 // more cv-qualified than the other; otherwise the types are considered
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000933 // to be equally cv-qualified for partial ordering purposes. The result
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000934 // of this determination will be used below.
935 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000936 // We save this information for later, using it only when deduction
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000937 // succeeds in both directions.
Douglas Gregorb939a192011-01-21 17:29:42 +0000938 RefParamPartialOrderingComparison Comparison;
939 Comparison.ParamIsRvalueRef = ParamRef->getAs<RValueReferenceType>();
940 Comparison.ArgIsRvalueRef = ArgRef->getAs<RValueReferenceType>();
941 Comparison.Qualifiers = NeitherMoreQualified;
Douglas Gregor769d0cc2011-04-30 17:07:52 +0000942
943 Qualifiers ParamQuals = Param.getQualifiers();
944 Qualifiers ArgQuals = Arg.getQualifiers();
945 if (ParamQuals.isStrictSupersetOf(ArgQuals))
Douglas Gregorb939a192011-01-21 17:29:42 +0000946 Comparison.Qualifiers = ParamMoreQualified;
Douglas Gregor769d0cc2011-04-30 17:07:52 +0000947 else if (ArgQuals.isStrictSupersetOf(ParamQuals))
Douglas Gregorb939a192011-01-21 17:29:42 +0000948 Comparison.Qualifiers = ArgMoreQualified;
949 RefParamComparisons->push_back(Comparison);
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000950 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000951
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000952 // C++0x [temp.deduct.partial]p7:
953 // Remove any top-level cv-qualifiers:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000954 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000955 // version of P.
956 Param = Param.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000957 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000958 // version of A.
959 Arg = Arg.getUnqualifiedType();
960 } else {
961 // C++0x [temp.deduct.call]p4 bullet 1:
962 // - If the original P is a reference type, the deduced A (i.e., the type
963 // referred to by the reference) can be more cv-qualified than the
964 // transformed A.
965 if (TDF & TDF_ParamWithReferenceType) {
966 Qualifiers Quals;
967 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
968 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall62c28c82011-01-18 07:41:22 +0000969 Arg.getCVRQualifiers());
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000970 Param = S.Context.getQualifiedType(UnqualParam, Quals);
971 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000972
Douglas Gregor73b3cf62011-01-25 17:19:08 +0000973 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
974 // C++0x [temp.deduct.type]p10:
975 // If P and A are function types that originated from deduction when
976 // taking the address of a function template (14.8.2.2) or when deducing
977 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000978 // Ai are parameters of the top-level parameter-type-list of P and A,
979 // respectively, Pi is adjusted if it is an rvalue reference to a
980 // cv-unqualified template parameter and Ai is an lvalue reference, in
981 // which case the type of Pi is changed to be the template parameter
Douglas Gregor73b3cf62011-01-25 17:19:08 +0000982 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
983 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi00995302011-01-27 07:09:49 +0000984 // deduced as X&. - end note ]
Douglas Gregor73b3cf62011-01-25 17:19:08 +0000985 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000986
Douglas Gregor73b3cf62011-01-25 17:19:08 +0000987 if (const RValueReferenceType *ParamRef
988 = Param->getAs<RValueReferenceType>()) {
989 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
990 !ParamRef->getPointeeType().getQualifiers())
991 if (Arg->isLValueReferenceType())
992 Param = ParamRef->getPointeeType();
993 }
994 }
Douglas Gregor500d3312009-06-26 18:27:22 +0000995 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000996
Douglas Gregor199d9912009-06-05 00:53:49 +0000997 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000998 // A template type argument T, a template template argument TT or a
999 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +00001000 // the following forms:
1001 //
1002 // T
1003 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +00001004 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +00001005 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregoraf1308232011-09-22 15:57:07 +00001006 // Just skip any attempts to deduce from a placeholder type.
1007 if (Arg->isPlaceholderType())
1008 return Sema::TDK_Success;
1009
Douglas Gregorf67875d2009-06-12 18:26:56 +00001010 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +00001011 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Douglas Gregor9e9fae42009-07-22 20:02:25 +00001013 // If the argument type is an array type, move the qualifiers up to the
1014 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregorf290e0d2009-07-22 21:30:48 +00001015 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +00001016 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001017 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +00001018 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001019 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +00001020 RecanonicalizeArg = true;
1021 }
1022 }
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001024 // The argument type can not be less qualified than the parameter
1025 // type.
Douglas Gregor61d0b6b2011-04-28 00:56:09 +00001026 if (!(TDF & TDF_IgnoreQualifiers) &&
1027 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +00001028 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +00001029 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +00001030 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +00001031 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +00001032 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001033
1034 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001035 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +00001036 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +00001037
Douglas Gregor61d0b6b2011-04-28 00:56:09 +00001038 // Remove any qualifiers on the parameter from the deduced type.
1039 // We checked the qualifiers for consistency above.
1040 Qualifiers DeducedQs = DeducedType.getQualifiers();
1041 Qualifiers ParamQs = Param.getQualifiers();
1042 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1043 if (ParamQs.hasObjCGCAttr())
1044 DeducedQs.removeObjCGCAttr();
1045 if (ParamQs.hasAddressSpace())
1046 DeducedQs.removeAddressSpace();
John McCallf85e1932011-06-15 23:02:42 +00001047 if (ParamQs.hasObjCLifetime())
1048 DeducedQs.removeObjCLifetime();
Douglas Gregore559ca12011-06-17 22:11:49 +00001049
1050 // Objective-C ARC:
Douglas Gregorda8b2492011-07-26 14:53:44 +00001051 // If template deduction would produce a lifetime qualifier on a type
1052 // that is not a lifetime type, template argument deduction fails.
1053 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1054 !DeducedType->isDependentType()) {
1055 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1056 Info.FirstArg = TemplateArgument(Param);
1057 Info.SecondArg = TemplateArgument(Arg);
1058 return Sema::TDK_Underqualified;
1059 }
1060
1061 // Objective-C ARC:
Douglas Gregore559ca12011-06-17 22:11:49 +00001062 // If template deduction would produce an argument type with lifetime type
1063 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikie4e4d0842012-03-11 07:00:24 +00001064 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore559ca12011-06-17 22:11:49 +00001065 DeducedType->isObjCLifetimeType() &&
1066 !DeducedQs.hasObjCLifetime())
1067 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1068
Douglas Gregor61d0b6b2011-04-28 00:56:09 +00001069 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1070 DeducedQs);
1071
Douglas Gregorf290e0d2009-07-22 21:30:48 +00001072 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001073 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +00001074
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001075 DeducedTemplateArgument NewDeduced(DeducedType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001076 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001077 Deduced[Index],
1078 NewDeduced);
1079 if (Result.isNull()) {
1080 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1081 Info.FirstArg = Deduced[Index];
1082 Info.SecondArg = NewDeduced;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001083 return Sema::TDK_Inconsistent;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001084 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001085
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001086 Deduced[Index] = Result;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001087 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001088 }
1089
Douglas Gregorf67875d2009-06-12 18:26:56 +00001090 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +00001091 Info.FirstArg = TemplateArgument(ParamIn);
1092 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +00001093
Douglas Gregor0bc15d92011-01-14 05:11:40 +00001094 // If the parameter is an already-substituted template parameter
1095 // pack, do nothing: we don't know which of its arguments to look
1096 // at, so we have to wait until all of the parameter packs in this
1097 // expansion have arguments.
1098 if (isa<SubstTemplateTypeParmPackType>(Param))
1099 return Sema::TDK_Success;
1100
Douglas Gregor508f1c82009-06-26 23:10:12 +00001101 // Check the cv-qualifiers on the parameter and argument types.
1102 if (!(TDF & TDF_IgnoreQualifiers)) {
1103 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor61d0b6b2011-04-28 00:56:09 +00001104 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregor508f1c82009-06-26 23:10:12 +00001105 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +00001106 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +00001107 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +00001108 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +00001109 }
Douglas Gregorfc55a822012-03-11 03:29:50 +00001110
1111 // If the parameter type is not dependent, there is nothing to deduce.
1112 if (!Param->isDependentType()) {
1113 if (!(TDF & TDF_SkipNonDependent) && Param != Arg)
1114 return Sema::TDK_NonDeducedMismatch;
1115
1116 return Sema::TDK_Success;
1117 }
1118 } else if (!Param->isDependentType() &&
1119 Param.getUnqualifiedType() == Arg.getUnqualifiedType()) {
1120 return Sema::TDK_Success;
Douglas Gregor508f1c82009-06-26 23:10:12 +00001121 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001122
Douglas Gregord560d502009-06-04 00:21:18 +00001123 switch (Param->getTypeClass()) {
Douglas Gregor4ac01402011-06-15 16:02:29 +00001124 // Non-canonical types cannot appear here.
1125#define NON_CANONICAL_TYPE(Class, Base) \
1126 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1127#define TYPE(Class, Base)
1128#include "clang/AST/TypeNodes.def"
1129
1130 case Type::TemplateTypeParm:
1131 case Type::SubstTemplateTypeParmPack:
1132 llvm_unreachable("Type nodes handled above");
Douglas Gregorfc55a822012-03-11 03:29:50 +00001133
1134 // These types cannot be dependent, so simply check whether the types are
1135 // the same.
Douglas Gregor199d9912009-06-05 00:53:49 +00001136 case Type::Builtin:
Douglas Gregor4ac01402011-06-15 16:02:29 +00001137 case Type::VariableArray:
1138 case Type::Vector:
1139 case Type::FunctionNoProto:
1140 case Type::Record:
1141 case Type::Enum:
1142 case Type::ObjCObject:
1143 case Type::ObjCInterface:
Douglas Gregorfc55a822012-03-11 03:29:50 +00001144 case Type::ObjCObjectPointer: {
1145 if (TDF & TDF_SkipNonDependent)
1146 return Sema::TDK_Success;
1147
1148 if (TDF & TDF_IgnoreQualifiers) {
1149 Param = Param.getUnqualifiedType();
1150 Arg = Arg.getUnqualifiedType();
1151 }
1152
1153 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1154 }
1155
Douglas Gregor4ac01402011-06-15 16:02:29 +00001156 // _Complex T [placeholder extension]
1157 case Type::Complex:
1158 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Sebastian Redlbb95e512012-01-17 22:49:52 +00001159 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor4ac01402011-06-15 16:02:29 +00001160 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlbb95e512012-01-17 22:49:52 +00001161 ComplexArg->getElementType(),
1162 Info, Deduced, TDF);
Douglas Gregor4ac01402011-06-15 16:02:29 +00001163
1164 return Sema::TDK_NonDeducedMismatch;
Eli Friedmanb001de72011-10-06 23:00:33 +00001165
1166 // _Atomic T [extension]
1167 case Type::Atomic:
1168 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlbb95e512012-01-17 22:49:52 +00001169 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedmanb001de72011-10-06 23:00:33 +00001170 cast<AtomicType>(Param)->getValueType(),
1171 AtomicArg->getValueType(),
1172 Info, Deduced, TDF);
1173
1174 return Sema::TDK_NonDeducedMismatch;
1175
Douglas Gregor199d9912009-06-05 00:53:49 +00001176 // T *
Douglas Gregord560d502009-06-04 00:21:18 +00001177 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +00001178 QualType PointeeType;
1179 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1180 PointeeType = PointerArg->getPointeeType();
1181 } else if (const ObjCObjectPointerType *PointerArg
1182 = Arg->getAs<ObjCObjectPointerType>()) {
1183 PointeeType = PointerArg->getPointeeType();
1184 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +00001185 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +00001186 }
Mike Stump1eb44332009-09-09 15:08:12 +00001187
Douglas Gregor41128772009-06-26 23:27:24 +00001188 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlbb95e512012-01-17 22:49:52 +00001189 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1190 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +00001191 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +00001192 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +00001193 }
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Douglas Gregor199d9912009-06-05 00:53:49 +00001195 // T &
Douglas Gregord560d502009-06-04 00:21:18 +00001196 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +00001197 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +00001198 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001199 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Sebastian Redlbb95e512012-01-17 22:49:52 +00001201 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +00001202 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlbb95e512012-01-17 22:49:52 +00001203 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +00001204 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001205
Douglas Gregor199d9912009-06-05 00:53:49 +00001206 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +00001207 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +00001208 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +00001209 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001210 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Sebastian Redlbb95e512012-01-17 22:49:52 +00001212 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1213 cast<RValueReferenceType>(Param)->getPointeeType(),
1214 ReferenceArg->getPointeeType(),
1215 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +00001216 }
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Douglas Gregor199d9912009-06-05 00:53:49 +00001218 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001219 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +00001220 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001221 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001222 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001223 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001224
John McCalle4f26e52010-08-19 00:20:19 +00001225 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlbb95e512012-01-17 22:49:52 +00001226 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1227 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1228 IncompleteArrayArg->getElementType(),
1229 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001230 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001231
1232 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001233 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +00001234 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001235 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001236 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001237 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001238
1239 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001240 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001241 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001242 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001243
John McCalle4f26e52010-08-19 00:20:19 +00001244 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlbb95e512012-01-17 22:49:52 +00001245 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1246 ConstantArrayParm->getElementType(),
1247 ConstantArrayArg->getElementType(),
1248 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001249 }
1250
Douglas Gregor199d9912009-06-05 00:53:49 +00001251 // type [i]
1252 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001253 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +00001254 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001255 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001256
John McCalle4f26e52010-08-19 00:20:19 +00001257 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1258
Douglas Gregor199d9912009-06-05 00:53:49 +00001259 // Check the element type of the arrays
1260 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001261 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +00001262 if (Sema::TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +00001263 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1264 DependentArrayParm->getElementType(),
1265 ArrayArg->getElementType(),
1266 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001267 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Douglas Gregor199d9912009-06-05 00:53:49 +00001269 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +00001270 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001271 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1272 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001273 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +00001274
1275 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +00001276 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00001277 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +00001278 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +00001279 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +00001280 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1281 llvm::APSInt Size(ConstantArrayArg->getSize());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001282 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001283 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001284 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001285 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +00001286 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001287 if (const DependentSizedArrayType *DependentArrayArg
1288 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor34c2f8c2010-12-22 23:15:38 +00001289 if (DependentArrayArg->getSizeExpr())
1290 return DeduceNonTypeTemplateArgument(S, NTTP,
1291 DependentArrayArg->getSizeExpr(),
1292 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Douglas Gregor199d9912009-06-05 00:53:49 +00001294 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +00001295 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001296 }
Mike Stump1eb44332009-09-09 15:08:12 +00001297
1298 // type(*)(T)
1299 // T(*)()
1300 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +00001301 case Type::FunctionProto: {
Douglas Gregor73b3cf62011-01-25 17:19:08 +00001302 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump1eb44332009-09-09 15:08:12 +00001303 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +00001304 dyn_cast<FunctionProtoType>(Arg);
1305 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001306 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001307
1308 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +00001309 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001310
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001311 if (FunctionProtoParam->getTypeQuals()
Douglas Gregore3c7a7c2011-01-26 16:50:54 +00001312 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001313 FunctionProtoParam->getRefQualifier()
Douglas Gregore3c7a7c2011-01-26 16:50:54 +00001314 != FunctionProtoArg->getRefQualifier() ||
1315 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001316 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001317
Anders Carlssona27fad52009-06-08 15:19:08 +00001318 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001319 if (Sema::TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +00001320 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1321 FunctionProtoParam->getResultType(),
1322 FunctionProtoArg->getResultType(),
1323 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001324 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Douglas Gregor603cfb42011-01-05 23:12:31 +00001326 return DeduceTemplateArguments(S, TemplateParams,
1327 FunctionProtoParam->arg_type_begin(),
1328 FunctionProtoParam->getNumArgs(),
1329 FunctionProtoArg->arg_type_begin(),
1330 FunctionProtoArg->getNumArgs(),
Douglas Gregor73b3cf62011-01-25 17:19:08 +00001331 Info, Deduced, SubTDF);
Anders Carlssona27fad52009-06-08 15:19:08 +00001332 }
Mike Stump1eb44332009-09-09 15:08:12 +00001333
John McCall3cb0ebd2010-03-10 03:28:59 +00001334 case Type::InjectedClassName: {
1335 // Treat a template's injected-class-name as if the template
1336 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +00001337 Param = cast<InjectedClassNameType>(Param)
1338 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00001339 assert(isa<TemplateSpecializationType>(Param) &&
1340 "injected class name is not a template specialization type");
1341 // fall through
1342 }
1343
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001344 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +00001345 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001346 // TT<T>
1347 // TT<i>
1348 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +00001349 case Type::TemplateSpecialization: {
1350 const TemplateSpecializationType *SpecParam
1351 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001353 // Try to deduce template arguments from the template-id.
1354 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001355 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001356 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Douglas Gregor4a5c15f2009-09-30 22:13:51 +00001358 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001359 // C++ [temp.deduct.call]p3b3:
1360 // If P is a class, and P has the form template-id, then A can be a
1361 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +00001362 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001363 // class pointed to by the deduced A.
1364 //
1365 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +00001366 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001367 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001368 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1369 // We cannot inspect base classes as part of deduction when the type
1370 // is incomplete, so either instantiate any templates necessary to
1371 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +00001372 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001373 return Result;
1374
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001375 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +00001376 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001377 // ToVisit is our stack of records that we still need to visit.
1378 llvm::SmallPtrSet<const RecordType *, 8> Visited;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001379 SmallVector<const RecordType *, 8> ToVisit;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001380 ToVisit.push_back(RecordT);
1381 bool Successful = false;
Benjamin Kramer74fe6612012-01-20 16:39:18 +00001382 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1383 Deduced.end());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001384 while (!ToVisit.empty()) {
1385 // Retrieve the next class in the inheritance hierarchy.
1386 const RecordType *NextT = ToVisit.back();
1387 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001389 // If we have already seen this type, skip it.
1390 if (!Visited.insert(NextT))
1391 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001393 // If this is a base class, try to perform template argument
1394 // deduction from it.
1395 if (NextT != RecordT) {
Richard Trieu910515b2012-11-07 21:17:13 +00001396 TemplateDeductionInfo BaseInfo(Info.getLocation());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001397 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001398 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Richard Trieu910515b2012-11-07 21:17:13 +00001399 QualType(NextT, 0), BaseInfo,
1400 Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001401
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001402 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +00001403 // note that we had some success. Otherwise, ignore any deductions
1404 // from this base class.
1405 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001406 Successful = true;
Benjamin Kramer74fe6612012-01-20 16:39:18 +00001407 DeducedOrig.clear();
1408 DeducedOrig.append(Deduced.begin(), Deduced.end());
Richard Trieu910515b2012-11-07 21:17:13 +00001409 Info.Param = BaseInfo.Param;
1410 Info.FirstArg = BaseInfo.FirstArg;
1411 Info.SecondArg = BaseInfo.SecondArg;
Douglas Gregor053105d2010-11-02 00:02:34 +00001412 }
1413 else
1414 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001415 }
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001417 // Visit base classes
1418 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1419 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
1420 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +00001421 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001422 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001423 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +00001424 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001425 }
1426 }
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001428 if (Successful)
1429 return Sema::TDK_Success;
1430 }
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001432 }
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001434 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +00001435 }
1436
Douglas Gregor637a4092009-06-10 23:47:09 +00001437 // T type::*
1438 // T T::*
1439 // T (type::*)()
1440 // type (T::*)()
1441 // type (type::*)(T)
1442 // type (T::*)(T)
1443 // T (type::*)(T)
1444 // T (T::*)()
1445 // T (T::*)(T)
1446 case Type::MemberPointer: {
1447 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1448 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1449 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001450 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +00001451
Douglas Gregorf67875d2009-06-12 18:26:56 +00001452 if (Sema::TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +00001453 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1454 MemPtrParam->getPointeeType(),
1455 MemPtrArg->getPointeeType(),
1456 Info, Deduced,
1457 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001458 return Result;
1459
Sebastian Redlbb95e512012-01-17 22:49:52 +00001460 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1461 QualType(MemPtrParam->getClass(), 0),
1462 QualType(MemPtrArg->getClass(), 0),
Douglas Gregorfc55a822012-03-11 03:29:50 +00001463 Info, Deduced,
1464 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637a4092009-06-10 23:47:09 +00001465 }
1466
Anders Carlsson9a917e42009-06-12 22:56:54 +00001467 // (clang extension)
1468 //
Mike Stump1eb44332009-09-09 15:08:12 +00001469 // type(^)(T)
1470 // T(^)()
1471 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +00001472 case Type::BlockPointer: {
1473 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1474 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00001475
Anders Carlsson859ba502009-06-12 16:23:10 +00001476 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001477 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Sebastian Redlbb95e512012-01-17 22:49:52 +00001479 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1480 BlockPtrParam->getPointeeType(),
1481 BlockPtrArg->getPointeeType(),
1482 Info, Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +00001483 }
1484
Douglas Gregor4ac01402011-06-15 16:02:29 +00001485 // (clang extension)
1486 //
1487 // T __attribute__(((ext_vector_type(<integral constant>))))
1488 case Type::ExtVector: {
1489 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1490 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1491 // Make sure that the vectors have the same number of elements.
1492 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1493 return Sema::TDK_NonDeducedMismatch;
1494
1495 // Perform deduction on the element types.
Sebastian Redlbb95e512012-01-17 22:49:52 +00001496 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1497 VectorParam->getElementType(),
1498 VectorArg->getElementType(),
1499 Info, Deduced, TDF);
Douglas Gregor4ac01402011-06-15 16:02:29 +00001500 }
1501
1502 if (const DependentSizedExtVectorType *VectorArg
1503 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1504 // We can't check the number of elements, since the argument has a
1505 // dependent number of elements. This can only occur during partial
1506 // ordering.
1507
1508 // Perform deduction on the element types.
Sebastian Redlbb95e512012-01-17 22:49:52 +00001509 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1510 VectorParam->getElementType(),
1511 VectorArg->getElementType(),
1512 Info, Deduced, TDF);
Douglas Gregor4ac01402011-06-15 16:02:29 +00001513 }
1514
1515 return Sema::TDK_NonDeducedMismatch;
1516 }
1517
1518 // (clang extension)
1519 //
1520 // T __attribute__(((ext_vector_type(N))))
1521 case Type::DependentSizedExtVector: {
1522 const DependentSizedExtVectorType *VectorParam
1523 = cast<DependentSizedExtVectorType>(Param);
1524
1525 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1526 // Perform deduction on the element types.
1527 if (Sema::TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +00001528 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1529 VectorParam->getElementType(),
1530 VectorArg->getElementType(),
1531 Info, Deduced, TDF))
Douglas Gregor4ac01402011-06-15 16:02:29 +00001532 return Result;
1533
1534 // Perform deduction on the vector size, if we can.
1535 NonTypeTemplateParmDecl *NTTP
1536 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1537 if (!NTTP)
1538 return Sema::TDK_Success;
1539
1540 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1541 ArgSize = VectorArg->getNumElements();
1542 return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy,
1543 false, Info, Deduced);
1544 }
1545
1546 if (const DependentSizedExtVectorType *VectorArg
1547 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1548 // Perform deduction on the element types.
1549 if (Sema::TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +00001550 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1551 VectorParam->getElementType(),
1552 VectorArg->getElementType(),
1553 Info, Deduced, TDF))
Douglas Gregor4ac01402011-06-15 16:02:29 +00001554 return Result;
1555
1556 // Perform deduction on the vector size, if we can.
1557 NonTypeTemplateParmDecl *NTTP
1558 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1559 if (!NTTP)
1560 return Sema::TDK_Success;
1561
1562 return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(),
1563 Info, Deduced);
1564 }
1565
1566 return Sema::TDK_NonDeducedMismatch;
1567 }
1568
Douglas Gregor637a4092009-06-10 23:47:09 +00001569 case Type::TypeOfExpr:
1570 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +00001571 case Type::DependentName:
Douglas Gregor4ac01402011-06-15 16:02:29 +00001572 case Type::UnresolvedUsing:
1573 case Type::Decltype:
1574 case Type::UnaryTransform:
1575 case Type::Auto:
1576 case Type::DependentTemplateSpecialization:
1577 case Type::PackExpansion:
Douglas Gregor637a4092009-06-10 23:47:09 +00001578 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +00001579 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001580 }
1581
David Blaikie30263482012-01-20 21:50:17 +00001582 llvm_unreachable("Invalid Type Class!");
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001583}
1584
Douglas Gregorf67875d2009-06-12 18:26:56 +00001585static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001586DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001587 TemplateParameterList *TemplateParams,
1588 const TemplateArgument &Param,
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001589 TemplateArgument Arg,
John McCall2a7fb272010-08-25 05:32:35 +00001590 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001591 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001592 // If the template argument is a pack expansion, perform template argument
1593 // deduction against the pattern of that expansion. This only occurs during
1594 // partial ordering.
1595 if (Arg.isPackExpansion())
1596 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001597
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001598 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +00001599 case TemplateArgument::Null:
David Blaikieb219cfc2011-09-23 05:06:16 +00001600 llvm_unreachable("Null template argument in parameter list");
Mike Stump1eb44332009-09-09 15:08:12 +00001601
1602 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +00001603 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlbb95e512012-01-17 22:49:52 +00001604 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1605 Param.getAsType(),
1606 Arg.getAsType(),
1607 Info, Deduced, 0);
Douglas Gregor788cd062009-11-11 01:00:40 +00001608 Info.FirstArg = Param;
1609 Info.SecondArg = Arg;
1610 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001611
Douglas Gregor788cd062009-11-11 01:00:40 +00001612 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001613 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001614 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +00001615 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001616 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +00001617 Info.FirstArg = Param;
1618 Info.SecondArg = Arg;
1619 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001620
1621 case TemplateArgument::TemplateExpansion:
1622 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001623
Douglas Gregor199d9912009-06-05 00:53:49 +00001624 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +00001625 if (Arg.getKind() == TemplateArgument::Declaration &&
Eli Friedmand7a6b162012-09-26 02:36:12 +00001626 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()) &&
1627 Param.isDeclForReferenceParam() == Arg.isDeclForReferenceParam())
1628 return Sema::TDK_Success;
1629
1630 Info.FirstArg = Param;
1631 Info.SecondArg = Arg;
1632 return Sema::TDK_NonDeducedMismatch;
1633
1634 case TemplateArgument::NullPtr:
1635 if (Arg.getKind() == TemplateArgument::NullPtr &&
1636 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor788cd062009-11-11 01:00:40 +00001637 return Sema::TDK_Success;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001638
Douglas Gregorf67875d2009-06-12 18:26:56 +00001639 Info.FirstArg = Param;
1640 Info.SecondArg = Arg;
1641 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Douglas Gregor199d9912009-06-05 00:53:49 +00001643 case TemplateArgument::Integral:
1644 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer85524372012-06-07 15:09:51 +00001645 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001646 return Sema::TDK_Success;
1647
1648 Info.FirstArg = Param;
1649 Info.SecondArg = Arg;
1650 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001651 }
Douglas Gregorf67875d2009-06-12 18:26:56 +00001652
1653 if (Arg.getKind() == TemplateArgument::Expression) {
1654 Info.FirstArg = Param;
1655 Info.SecondArg = Arg;
1656 return Sema::TDK_NonDeducedMismatch;
1657 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001658
Douglas Gregorf67875d2009-06-12 18:26:56 +00001659 Info.FirstArg = Param;
1660 Info.SecondArg = Arg;
1661 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Douglas Gregor199d9912009-06-05 00:53:49 +00001663 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +00001664 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001665 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1666 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001667 return DeduceNonTypeTemplateArgument(S, NTTP,
Benjamin Kramer85524372012-06-07 15:09:51 +00001668 Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001669 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001670 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001671 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +00001672 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001673 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001674 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +00001675 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001676 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +00001677 Info, Deduced);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001678
Douglas Gregorf67875d2009-06-12 18:26:56 +00001679 Info.FirstArg = Param;
1680 Info.SecondArg = Arg;
1681 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001682 }
Mike Stump1eb44332009-09-09 15:08:12 +00001683
Douglas Gregor199d9912009-06-05 00:53:49 +00001684 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001685 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001686 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001687 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001688 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001689 }
Mike Stump1eb44332009-09-09 15:08:12 +00001690
David Blaikie30263482012-01-20 21:50:17 +00001691 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001692}
1693
Douglas Gregor20a55e22010-12-22 18:17:10 +00001694/// \brief Determine whether there is a template argument to be used for
1695/// deduction.
1696///
1697/// This routine "expands" argument packs in-place, overriding its input
1698/// parameters so that \c Args[ArgIdx] will be the available template argument.
1699///
1700/// \returns true if there is another template argument (which will be at
1701/// \c Args[ArgIdx]), false otherwise.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001702static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
Douglas Gregor20a55e22010-12-22 18:17:10 +00001703 unsigned &ArgIdx,
1704 unsigned &NumArgs) {
1705 if (ArgIdx == NumArgs)
1706 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001707
Douglas Gregor20a55e22010-12-22 18:17:10 +00001708 const TemplateArgument &Arg = Args[ArgIdx];
1709 if (Arg.getKind() != TemplateArgument::Pack)
1710 return true;
1711
1712 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1713 Args = Arg.pack_begin();
1714 NumArgs = Arg.pack_size();
1715 ArgIdx = 0;
1716 return ArgIdx < NumArgs;
1717}
1718
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001719/// \brief Determine whether the given set of template arguments has a pack
1720/// expansion that is not the last template argument.
1721static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1722 unsigned NumArgs) {
1723 unsigned ArgIdx = 0;
1724 while (ArgIdx < NumArgs) {
1725 const TemplateArgument &Arg = Args[ArgIdx];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001726
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001727 // Unwrap argument packs.
1728 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1729 Args = Arg.pack_begin();
1730 NumArgs = Arg.pack_size();
1731 ArgIdx = 0;
1732 continue;
1733 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001734
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001735 ++ArgIdx;
1736 if (ArgIdx == NumArgs)
1737 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001738
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001739 if (Arg.isPackExpansion())
1740 return true;
1741 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001742
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001743 return false;
1744}
1745
Douglas Gregor20a55e22010-12-22 18:17:10 +00001746static Sema::TemplateDeductionResult
1747DeduceTemplateArguments(Sema &S,
1748 TemplateParameterList *TemplateParams,
1749 const TemplateArgument *Params, unsigned NumParams,
1750 const TemplateArgument *Args, unsigned NumArgs,
1751 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001752 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor0972c862010-12-22 18:55:49 +00001753 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001754 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001755 // If the template argument list of P contains a pack expansion that is not
1756 // the last template argument, the entire template argument list is a
Douglas Gregore02e2622010-12-22 21:19:48 +00001757 // non-deduced context.
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001758 if (hasPackExpansionBeforeEnd(Params, NumParams))
1759 return Sema::TDK_Success;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001760
Douglas Gregore02e2622010-12-22 21:19:48 +00001761 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001762 // If P has a form that contains <T> or <i>, then each argument Pi of the
1763 // respective template argument list P is compared with the corresponding
Douglas Gregore02e2622010-12-22 21:19:48 +00001764 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001765 unsigned ArgIdx = 0, ParamIdx = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001766 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
Douglas Gregor20a55e22010-12-22 18:17:10 +00001767 ++ParamIdx) {
1768 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001769 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001770
Douglas Gregor20a55e22010-12-22 18:17:10 +00001771 // Check whether we have enough arguments.
1772 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor3cae5c92011-01-10 20:53:55 +00001773 return NumberOfArgumentsMustMatch? Sema::TDK_NonDeducedMismatch
Douglas Gregor0972c862010-12-22 18:55:49 +00001774 : Sema::TDK_Success;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001775
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001776 if (Args[ArgIdx].isPackExpansion()) {
1777 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1778 // but applied to pack expansions that are template arguments.
1779 return Sema::TDK_NonDeducedMismatch;
1780 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001781
Douglas Gregore02e2622010-12-22 21:19:48 +00001782 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001783 if (Sema::TemplateDeductionResult Result
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001784 = DeduceTemplateArguments(S, TemplateParams,
1785 Params[ParamIdx], Args[ArgIdx],
1786 Info, Deduced))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001787 return Result;
1788
Douglas Gregor20a55e22010-12-22 18:17:10 +00001789 // Move to the next argument.
1790 ++ArgIdx;
1791 continue;
1792 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001793
Douglas Gregore02e2622010-12-22 21:19:48 +00001794 // The parameter is a pack expansion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001795
Douglas Gregore02e2622010-12-22 21:19:48 +00001796 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001797 // If Pi is a pack expansion, then the pattern of Pi is compared with
1798 // each remaining argument in the template argument list of A. Each
1799 // comparison deduces template arguments for subsequent positions in the
Douglas Gregore02e2622010-12-22 21:19:48 +00001800 // template parameter packs expanded by Pi.
1801 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001802
Douglas Gregore02e2622010-12-22 21:19:48 +00001803 // Compute the set of template parameter indices that correspond to
1804 // parameter packs expanded by the pack expansion.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001805 SmallVector<unsigned, 2> PackIndices;
Douglas Gregore02e2622010-12-22 21:19:48 +00001806 {
Benjamin Kramer013b3662012-01-30 16:17:39 +00001807 llvm::SmallBitVector SawIndices(TemplateParams->size());
Chris Lattner5f9e2722011-07-23 10:55:15 +00001808 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregore02e2622010-12-22 21:19:48 +00001809 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1810 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1811 unsigned Depth, Index;
1812 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1813 if (Depth == 0 && !SawIndices[Index]) {
1814 SawIndices[Index] = true;
1815 PackIndices.push_back(Index);
1816 }
1817 }
1818 }
1819 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001820
Douglas Gregore02e2622010-12-22 21:19:48 +00001821 // FIXME: If there are no remaining arguments, we can bail out early
1822 // and set any deduced parameter packs to an empty argument pack.
1823 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001824
Douglas Gregore02e2622010-12-22 21:19:48 +00001825 // Save the deduced template arguments for each parameter pack expanded
1826 // by this pack expansion, then clear out the deduction.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001827 SmallVector<DeducedTemplateArgument, 2>
Douglas Gregore02e2622010-12-22 21:19:48 +00001828 SavedPacks(PackIndices.size());
Chris Lattner5f9e2722011-07-23 10:55:15 +00001829 SmallVector<SmallVector<DeducedTemplateArgument, 4>, 2>
Douglas Gregor54293852011-01-10 17:35:05 +00001830 NewlyDeducedPacks(PackIndices.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001831 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
Douglas Gregor54293852011-01-10 17:35:05 +00001832 NewlyDeducedPacks);
Douglas Gregore02e2622010-12-22 21:19:48 +00001833
1834 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001835 // expanded by this pack expansion (the outer index) and for each
Douglas Gregore02e2622010-12-22 21:19:48 +00001836 // template argument (the inner SmallVectors).
Douglas Gregore02e2622010-12-22 21:19:48 +00001837 bool HasAnyArguments = false;
1838 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1839 HasAnyArguments = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001840
Douglas Gregore02e2622010-12-22 21:19:48 +00001841 // Deduce template arguments from the pattern.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001842 if (Sema::TemplateDeductionResult Result
Douglas Gregore02e2622010-12-22 21:19:48 +00001843 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1844 Info, Deduced))
1845 return Result;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001846
Douglas Gregore02e2622010-12-22 21:19:48 +00001847 // Capture the deduced template arguments for each parameter pack expanded
1848 // by this pack expansion, add them to the list of arguments we've deduced
1849 // for that pack, then clear out the deduced argument.
1850 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1851 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1852 if (!DeducedArg.isNull()) {
1853 NewlyDeducedPacks[I].push_back(DeducedArg);
1854 DeducedArg = DeducedTemplateArgument();
1855 }
1856 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001857
Douglas Gregore02e2622010-12-22 21:19:48 +00001858 ++ArgIdx;
1859 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001860
Douglas Gregore02e2622010-12-22 21:19:48 +00001861 // Build argument packs for each of the parameter packs expanded by this
1862 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +00001863 if (Sema::TemplateDeductionResult Result
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001864 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
Douglas Gregor0216f812011-01-10 17:53:52 +00001865 Deduced, PackIndices, SavedPacks,
1866 NewlyDeducedPacks, Info))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001867 return Result;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001868 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001869
Douglas Gregor20a55e22010-12-22 18:17:10 +00001870 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001871 if (NumberOfArgumentsMustMatch &&
1872 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor3cae5c92011-01-10 20:53:55 +00001873 return Sema::TDK_NonDeducedMismatch;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001874
Douglas Gregor20a55e22010-12-22 18:17:10 +00001875 return Sema::TDK_Success;
1876}
1877
Mike Stump1eb44332009-09-09 15:08:12 +00001878static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001879DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001880 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001881 const TemplateArgumentList &ParamList,
1882 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001883 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001884 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001885 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor20a55e22010-12-22 18:17:10 +00001886 ParamList.data(), ParamList.size(),
1887 ArgList.data(), ArgList.size(),
1888 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001889}
1890
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001891/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001892static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001893 const TemplateArgument &X,
1894 const TemplateArgument &Y) {
1895 if (X.getKind() != Y.getKind())
1896 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001897
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001898 switch (X.getKind()) {
1899 case TemplateArgument::Null:
David Blaikieb219cfc2011-09-23 05:06:16 +00001900 llvm_unreachable("Comparing NULL template argument");
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001902 case TemplateArgument::Type:
1903 return Context.getCanonicalType(X.getAsType()) ==
1904 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001906 case TemplateArgument::Declaration:
Eli Friedmand7a6b162012-09-26 02:36:12 +00001907 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl()) &&
1908 X.isDeclForReferenceParam() == Y.isDeclForReferenceParam();
1909
1910 case TemplateArgument::NullPtr:
1911 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump1eb44332009-09-09 15:08:12 +00001912
Douglas Gregor788cd062009-11-11 01:00:40 +00001913 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001914 case TemplateArgument::TemplateExpansion:
1915 return Context.getCanonicalTemplateName(
1916 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1917 Context.getCanonicalTemplateName(
1918 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001919
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001920 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00001921 return X.getAsIntegral() == Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001922
Douglas Gregor788cd062009-11-11 01:00:40 +00001923 case TemplateArgument::Expression: {
1924 llvm::FoldingSetNodeID XID, YID;
1925 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001926 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001927 return XID == YID;
1928 }
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001930 case TemplateArgument::Pack:
1931 if (X.pack_size() != Y.pack_size())
1932 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001933
1934 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1935 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001936 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001937 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001938 if (!isSameTemplateArg(Context, *XP, *YP))
1939 return false;
1940
1941 return true;
1942 }
1943
David Blaikie30263482012-01-20 21:50:17 +00001944 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001945}
1946
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001947/// \brief Allocate a TemplateArgumentLoc where all locations have
1948/// been initialized to the given location.
1949///
1950/// \param S The semantic analysis object.
1951///
James Dennett1dfbd922012-06-14 21:40:34 +00001952/// \param Arg The template argument we are producing template argument
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001953/// location information for.
1954///
1955/// \param NTTPType For a declaration template argument, the type of
1956/// the non-type template parameter that corresponds to this template
1957/// argument.
1958///
1959/// \param Loc The source location to use for the resulting template
1960/// argument.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001961static TemplateArgumentLoc
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001962getTrivialTemplateArgumentLoc(Sema &S,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001963 const TemplateArgument &Arg,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001964 QualType NTTPType,
1965 SourceLocation Loc) {
1966 switch (Arg.getKind()) {
1967 case TemplateArgument::Null:
1968 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001969
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001970 case TemplateArgument::Type:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001971 return TemplateArgumentLoc(Arg,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001972 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001973
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001974 case TemplateArgument::Declaration: {
1975 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001976 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Douglas Gregord2008e22012-04-06 22:40:38 +00001977 .takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001978 return TemplateArgumentLoc(TemplateArgument(E), E);
1979 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001980
Eli Friedmand7a6b162012-09-26 02:36:12 +00001981 case TemplateArgument::NullPtr: {
1982 Expr *E
1983 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
1984 .takeAs<Expr>();
1985 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
1986 E);
1987 }
1988
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001989 case TemplateArgument::Integral: {
1990 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001991 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001992 return TemplateArgumentLoc(TemplateArgument(E), E);
1993 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001994
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001995 case TemplateArgument::Template:
1996 case TemplateArgument::TemplateExpansion: {
1997 NestedNameSpecifierLocBuilder Builder;
1998 TemplateName Template = Arg.getAsTemplate();
1999 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2000 Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc);
2001 else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2002 Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc);
2003
2004 if (Arg.getKind() == TemplateArgument::Template)
2005 return TemplateArgumentLoc(Arg,
2006 Builder.getWithLocInContext(S.Context),
2007 Loc);
2008
2009
2010 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context),
2011 Loc, Loc);
2012 }
Douglas Gregora7fc9012011-01-05 18:58:31 +00002013
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002014 case TemplateArgument::Expression:
2015 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002016
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002017 case TemplateArgument::Pack:
2018 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2019 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002020
David Blaikie30263482012-01-20 21:50:17 +00002021 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002022}
2023
2024
2025/// \brief Convert the given deduced template argument and add it to the set of
2026/// fully-converted template arguments.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002027static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002028 DeducedTemplateArgument Arg,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002029 NamedDecl *Template,
2030 QualType NTTPType,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002031 unsigned ArgumentPackIndex,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002032 TemplateDeductionInfo &Info,
2033 bool InFunctionTemplate,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002034 SmallVectorImpl<TemplateArgument> &Output) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002035 if (Arg.getKind() == TemplateArgument::Pack) {
2036 // This is a template argument pack, so check each of its arguments against
2037 // the template parameter.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002038 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002039 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
Douglas Gregor135ffa72011-01-05 21:00:53 +00002040 PAEnd = Arg.pack_end();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002041 PA != PAEnd; ++PA) {
Douglas Gregord53e16a2011-01-05 20:52:18 +00002042 // When converting the deduced template argument, append it to the
2043 // general output list. We need to do this so that the template argument
2044 // checking logic has all of the prior template arguments available.
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002045 DeducedTemplateArgument InnerArg(*PA);
2046 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002047 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002048 NTTPType, PackedArgsBuilder.size(),
2049 Info, InFunctionTemplate, Output))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002050 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002051
Douglas Gregord53e16a2011-01-05 20:52:18 +00002052 // Move the converted template argument into our argument pack.
2053 PackedArgsBuilder.push_back(Output.back());
2054 Output.pop_back();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002055 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002056
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002057 // Create the resulting argument pack.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002058 Output.push_back(TemplateArgument::CreatePackCopy(S.Context,
Douglas Gregor203e6a32011-01-11 23:09:57 +00002059 PackedArgsBuilder.data(),
2060 PackedArgsBuilder.size()));
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002061 return false;
2062 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002063
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002064 // Convert the deduced template argument into a template
2065 // argument that we can check, almost as if the user had written
2066 // the template argument explicitly.
2067 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
2068 Info.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002069
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002070 // Check the template argument, converting it as necessary.
2071 return S.CheckTemplateArgument(Param, ArgLoc,
2072 Template,
2073 Template->getLocation(),
2074 Template->getSourceRange().getEnd(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002075 ArgumentPackIndex,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002076 Output,
2077 InFunctionTemplate
2078 ? (Arg.wasDeducedFromArrayBound()
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002079 ? Sema::CTAK_DeducedFromArrayBound
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002080 : Sema::CTAK_Deduced)
2081 : Sema::CTAK_Specified);
2082}
2083
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002084/// Complete template argument deduction for a class template partial
2085/// specialization.
2086static Sema::TemplateDeductionResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002087FinishTemplateArgumentDeduction(Sema &S,
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002088 ClassTemplatePartialSpecializationDecl *Partial,
2089 const TemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002090 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00002091 TemplateDeductionInfo &Info) {
Eli Friedman59a839c2012-02-08 03:07:05 +00002092 // Unevaluated SFINAE context.
2093 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002094 Sema::SFINAETrap Trap(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002095
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002096 Sema::ContextRAII SavedContext(S, Partial);
2097
2098 // C++ [temp.deduct.type]p2:
2099 // [...] or if any template argument remains neither deduced nor
2100 // explicitly specified, template argument deduction fails.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002101 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor033a3ca2011-01-04 22:23:38 +00002102 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2103 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002104 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002105 if (Deduced[I].isNull()) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002106 Info.Param = makeTemplateParameter(Param);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002107 return Sema::TDK_Incomplete;
2108 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002109
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002110 // We have deduced this argument, so it still needs to be
2111 // checked and converted.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002112
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002113 // First, for a non-type template parameter type that is
2114 // initialized by a declaration, we need the type of the
2115 // corresponding non-type template parameter.
2116 QualType NTTPType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002117 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord53e16a2011-01-05 20:52:18 +00002118 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002119 NTTPType = NTTP->getType();
Douglas Gregord53e16a2011-01-05 20:52:18 +00002120 if (NTTPType->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002121 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregord53e16a2011-01-05 20:52:18 +00002122 Builder.data(), Builder.size());
2123 NTTPType = S.SubstType(NTTPType,
2124 MultiLevelTemplateArgumentList(TemplateArgs),
2125 NTTP->getLocation(),
2126 NTTP->getDeclName());
2127 if (NTTPType.isNull()) {
2128 Info.Param = makeTemplateParameter(Param);
2129 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002130 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
2131 Builder.data(),
Douglas Gregord53e16a2011-01-05 20:52:18 +00002132 Builder.size()));
2133 return Sema::TDK_SubstitutionFailure;
2134 }
2135 }
2136 }
2137
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002138 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002139 Partial, NTTPType, 0, Info, false,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002140 Builder)) {
2141 Info.Param = makeTemplateParameter(Param);
2142 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002143 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2144 Builder.size()));
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002145 return Sema::TDK_SubstitutionFailure;
2146 }
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002147 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002148
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002149 // Form the template argument list from the deduced template arguments.
2150 TemplateArgumentList *DeducedArgumentList
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002151 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
Douglas Gregor910f8002010-11-07 23:05:16 +00002152 Builder.size());
2153
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002154 Info.reset(DeducedArgumentList);
2155
2156 // Substitute the deduced template arguments into the template
2157 // arguments of the class template partial specialization, and
2158 // verify that the instantiated template arguments are both valid
2159 // and are equivalent to the template arguments originally provided
2160 // to the class template.
John McCall2a7fb272010-08-25 05:32:35 +00002161 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002162 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
2163 const TemplateArgumentLoc *PartialTemplateArgs
2164 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002165
2166 // Note that we don't provide the langle and rangle locations.
2167 TemplateArgumentListInfo InstArgs;
2168
Douglas Gregore02e2622010-12-22 21:19:48 +00002169 if (S.Subst(PartialTemplateArgs,
2170 Partial->getNumTemplateArgsAsWritten(),
2171 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2172 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2173 if (ParamIdx >= Partial->getTemplateParameters()->size())
2174 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2175
2176 Decl *Param
2177 = const_cast<NamedDecl *>(
2178 Partial->getTemplateParameters()->getParam(ParamIdx));
2179 Info.Param = makeTemplateParameter(Param);
2180 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2181 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002182 }
2183
Chris Lattner5f9e2722011-07-23 10:55:15 +00002184 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002185 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002186 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002187 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002188
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002189 TemplateParameterList *TemplateParams
2190 = ClassTemplate->getTemplateParameters();
2191 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor910f8002010-11-07 23:05:16 +00002192 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002193 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00002194 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002195 Info.FirstArg = TemplateArgs[I];
2196 Info.SecondArg = InstArg;
2197 return Sema::TDK_NonDeducedMismatch;
2198 }
2199 }
2200
2201 if (Trap.hasErrorOccurred())
2202 return Sema::TDK_SubstitutionFailure;
2203
2204 return Sema::TDK_Success;
2205}
2206
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002207/// \brief Perform template argument deduction to determine whether
2208/// the given template arguments match the given class template
2209/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00002210Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00002211Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00002212 const TemplateArgumentList &TemplateArgs,
2213 TemplateDeductionInfo &Info) {
Douglas Gregorae19fbb2012-09-13 21:01:57 +00002214 if (Partial->isInvalidDecl())
2215 return TDK_Invalid;
2216
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002217 // C++ [temp.class.spec.match]p2:
2218 // A partial specialization matches a given actual template
2219 // argument list if the template arguments of the partial
2220 // specialization can be deduced from the actual template argument
2221 // list (14.8.2).
Eli Friedman59a839c2012-02-08 03:07:05 +00002222
2223 // Unevaluated SFINAE context.
2224 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregorbb260412009-06-14 08:02:22 +00002225 SFINAETrap Trap(*this);
Eli Friedman59a839c2012-02-08 03:07:05 +00002226
Chris Lattner5f9e2722011-07-23 10:55:15 +00002227 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00002228 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00002229 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002230 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00002231 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00002232 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00002233 TemplateArgs, Info, Deduced))
2234 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00002235
Richard Smith7e54fb52012-07-16 01:09:10 +00002236 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Douglas Gregor637a4092009-06-10 23:47:09 +00002237 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Richard Smith7e54fb52012-07-16 01:09:10 +00002238 DeducedArgs, Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00002239 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00002240 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00002241
Douglas Gregorbb260412009-06-14 08:02:22 +00002242 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002243 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002244
2245 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002246 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00002247}
Douglas Gregor031a5882009-06-13 00:26:55 +00002248
Douglas Gregor41128772009-06-26 23:27:24 +00002249/// \brief Determine whether the given type T is a simple-template-id type.
2250static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00002251 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00002252 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00002253 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002254
Douglas Gregor41128772009-06-26 23:27:24 +00002255 return false;
2256}
Douglas Gregor83314aa2009-07-08 20:55:45 +00002257
2258/// \brief Substitute the explicitly-provided template arguments into the
2259/// given function template according to C++ [temp.arg.explicit].
2260///
2261/// \param FunctionTemplate the function template into which the explicit
2262/// template arguments will be substituted.
2263///
James Dennett1dfbd922012-06-14 21:40:34 +00002264/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002265/// arguments.
2266///
Mike Stump1eb44332009-09-09 15:08:12 +00002267/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00002268/// with the converted and checked explicit template arguments.
2269///
Mike Stump1eb44332009-09-09 15:08:12 +00002270/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00002271/// parameters.
2272///
2273/// \param FunctionType if non-NULL, the result type of the function template
2274/// will also be instantiated and the pointed-to value will be updated with
2275/// the instantiated function type.
2276///
2277/// \param Info if substitution fails for any reason, this object will be
2278/// populated with more information about the failure.
2279///
2280/// \returns TDK_Success if substitution was successful, or some failure
2281/// condition.
2282Sema::TemplateDeductionResult
2283Sema::SubstituteExplicitTemplateArguments(
2284 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor67714232011-03-03 02:41:12 +00002285 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002286 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2287 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002288 QualType *FunctionType,
2289 TemplateDeductionInfo &Info) {
2290 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2291 TemplateParameterList *TemplateParams
2292 = FunctionTemplate->getTemplateParameters();
2293
John McCalld5532b62009-11-23 01:53:49 +00002294 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002295 // No arguments to substitute; just copy over the parameter types and
2296 // fill in the function type.
2297 for (FunctionDecl::param_iterator P = Function->param_begin(),
2298 PEnd = Function->param_end();
2299 P != PEnd;
2300 ++P)
2301 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00002302
Douglas Gregor83314aa2009-07-08 20:55:45 +00002303 if (FunctionType)
2304 *FunctionType = Function->getType();
2305 return TDK_Success;
2306 }
Mike Stump1eb44332009-09-09 15:08:12 +00002307
Eli Friedman59a839c2012-02-08 03:07:05 +00002308 // Unevaluated SFINAE context.
2309 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +00002310 SFINAETrap Trap(*this);
2311
Douglas Gregor83314aa2009-07-08 20:55:45 +00002312 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002313 // Template arguments that are present shall be specified in the
2314 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00002315 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00002316 // there are corresponding template-parameters.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002317 SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00002318
2319 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00002320 // explicitly-specified template arguments against this function template,
2321 // and then substitute them into the function parameter types.
Richard Smith7e54fb52012-07-16 01:09:10 +00002322 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002323 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Richard Smith7e54fb52012-07-16 01:09:10 +00002324 FunctionTemplate, DeducedArgs,
Douglas Gregor9b623632010-10-12 23:32:35 +00002325 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2326 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00002327 if (Inst)
2328 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00002329
Douglas Gregor83314aa2009-07-08 20:55:45 +00002330 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002331 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00002332 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002333 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00002334 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00002335 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00002336 if (Index >= TemplateParams->size())
2337 Index = TemplateParams->size() - 1;
2338 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002339 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00002340 }
Mike Stump1eb44332009-09-09 15:08:12 +00002341
Douglas Gregor83314aa2009-07-08 20:55:45 +00002342 // Form the template argument list from the explicitly-specified
2343 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00002344 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002345 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00002346 Info.reset(ExplicitArgumentList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002347
John McCalldf41f182010-10-12 19:40:14 +00002348 // Template argument deduction and the final substitution should be
2349 // done in the context of the templated declaration. Explicit
2350 // argument substitution, on the other hand, needs to happen in the
2351 // calling context.
2352 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2353
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002354 // If we deduced template arguments for a template parameter pack,
Douglas Gregord3731192011-01-10 07:32:04 +00002355 // note that the template argument pack is partially substituted and record
2356 // the explicit template arguments. They'll be used as part of deduction
2357 // for this template parameter pack.
Douglas Gregord3731192011-01-10 07:32:04 +00002358 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2359 const TemplateArgument &Arg = Builder[I];
2360 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregord3731192011-01-10 07:32:04 +00002361 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002362 TemplateParams->getParam(I),
Douglas Gregord3731192011-01-10 07:32:04 +00002363 Arg.pack_begin(),
2364 Arg.pack_size());
2365 break;
2366 }
2367 }
2368
Richard Smitheefb3d52012-02-10 09:58:53 +00002369 const FunctionProtoType *Proto
2370 = Function->getType()->getAs<FunctionProtoType>();
2371 assert(Proto && "Function template does not have a prototype?");
2372
Douglas Gregor83314aa2009-07-08 20:55:45 +00002373 // Instantiate the types of each of the function parameters given the
Richard Smitheefb3d52012-02-10 09:58:53 +00002374 // explicitly-specified template arguments. If the function has a trailing
2375 // return type, substitute it after the arguments to ensure we substitute
2376 // in lexical order.
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002377 if (Proto->hasTrailingReturn()) {
2378 if (SubstParmTypes(Function->getLocation(),
2379 Function->param_begin(), Function->getNumParams(),
2380 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2381 ParamTypes))
2382 return TDK_SubstitutionFailure;
2383 }
2384
Richard Smitheefb3d52012-02-10 09:58:53 +00002385 // Instantiate the return type.
2386 // FIXME: exception-specifications?
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002387 QualType ResultType;
2388 {
2389 // C++11 [expr.prim.general]p3:
2390 // If a declaration declares a member function or member function
2391 // template of a class X, the expression this is a prvalue of type
2392 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2393 // and the end of the function-definition, member-declarator, or
2394 // declarator.
2395 unsigned ThisTypeQuals = 0;
2396 CXXRecordDecl *ThisContext = 0;
2397 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2398 ThisContext = Method->getParent();
2399 ThisTypeQuals = Method->getTypeQualifiers();
2400 }
2401
2402 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
2403 getLangOpts().CPlusPlus0x);
2404
2405 ResultType = SubstType(Proto->getResultType(),
2406 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2407 Function->getTypeSpecStartLoc(),
2408 Function->getDeclName());
2409 if (ResultType.isNull() || Trap.hasErrorOccurred())
2410 return TDK_SubstitutionFailure;
2411 }
2412
Richard Smitheefb3d52012-02-10 09:58:53 +00002413 // Instantiate the types of each of the function parameters given the
2414 // explicitly-specified template arguments if we didn't do so earlier.
2415 if (!Proto->hasTrailingReturn() &&
2416 SubstParmTypes(Function->getLocation(),
2417 Function->param_begin(), Function->getNumParams(),
2418 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2419 ParamTypes))
2420 return TDK_SubstitutionFailure;
2421
Douglas Gregor83314aa2009-07-08 20:55:45 +00002422 if (FunctionType) {
Mike Stump1eb44332009-09-09 15:08:12 +00002423 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002424 ParamTypes.data(), ParamTypes.size(),
2425 Proto->isVariadic(),
Richard Smitheefb3d52012-02-10 09:58:53 +00002426 Proto->hasTrailingReturn(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00002427 Proto->getTypeQuals(),
Douglas Gregorc938c162011-01-26 05:01:58 +00002428 Proto->getRefQualifier(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00002429 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00002430 Function->getDeclName(),
2431 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00002432 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2433 return TDK_SubstitutionFailure;
2434 }
Mike Stump1eb44332009-09-09 15:08:12 +00002435
Douglas Gregor83314aa2009-07-08 20:55:45 +00002436 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002437 // Trailing template arguments that can be deduced (14.8.2) may be
2438 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00002439 // template arguments can be deduced, they may all be omitted; in this
2440 // case, the empty template argument list <> itself may also be omitted.
2441 //
Douglas Gregord3731192011-01-10 07:32:04 +00002442 // Take all of the explicitly-specified arguments and put them into
2443 // the set of deduced template arguments. Explicitly-specified
2444 // parameter packs, however, will be set to NULL since the deduction
2445 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002446 Deduced.reserve(TemplateParams->size());
Douglas Gregord3731192011-01-10 07:32:04 +00002447 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2448 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2449 if (Arg.getKind() == TemplateArgument::Pack)
2450 Deduced.push_back(DeducedTemplateArgument());
2451 else
2452 Deduced.push_back(Arg);
2453 }
Mike Stump1eb44332009-09-09 15:08:12 +00002454
Douglas Gregor83314aa2009-07-08 20:55:45 +00002455 return TDK_Success;
2456}
2457
Douglas Gregorb7edc4f2011-06-17 05:18:17 +00002458/// \brief Check whether the deduced argument type for a call to a function
2459/// template matches the actual argument type per C++ [temp.deduct.call]p4.
2460static bool
2461CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
2462 QualType DeducedA) {
2463 ASTContext &Context = S.Context;
2464
2465 QualType A = OriginalArg.OriginalArgType;
2466 QualType OriginalParamType = OriginalArg.OriginalParamType;
2467
2468 // Check for type equality (top-level cv-qualifiers are ignored).
2469 if (Context.hasSameUnqualifiedType(A, DeducedA))
2470 return false;
2471
2472 // Strip off references on the argument types; they aren't needed for
2473 // the following checks.
2474 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2475 DeducedA = DeducedARef->getPointeeType();
2476 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2477 A = ARef->getPointeeType();
2478
2479 // C++ [temp.deduct.call]p4:
2480 // [...] However, there are three cases that allow a difference:
2481 // - If the original P is a reference type, the deduced A (i.e., the
2482 // type referred to by the reference) can be more cv-qualified than
2483 // the transformed A.
2484 if (const ReferenceType *OriginalParamRef
2485 = OriginalParamType->getAs<ReferenceType>()) {
2486 // We don't want to keep the reference around any more.
2487 OriginalParamType = OriginalParamRef->getPointeeType();
2488
2489 Qualifiers AQuals = A.getQualifiers();
2490 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregorb2513022012-07-18 00:14:59 +00002491
2492 // Under Objective-C++ ARC, the deduced type may have implicitly been
2493 // given strong lifetime. If so, update the original qualifiers to
2494 // include this strong lifetime.
2495 if (S.getLangOpts().ObjCAutoRefCount &&
2496 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2497 AQuals.getObjCLifetime() == Qualifiers::OCL_None) {
2498 AQuals.setObjCLifetime(Qualifiers::OCL_Strong);
2499 }
2500
Douglas Gregorb7edc4f2011-06-17 05:18:17 +00002501 if (AQuals == DeducedAQuals) {
2502 // Qualifiers match; there's nothing to do.
2503 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorc99f0ec2011-06-17 14:36:00 +00002504 return true;
Douglas Gregorb7edc4f2011-06-17 05:18:17 +00002505 } else {
2506 // Qualifiers are compatible, so have the argument type adopt the
2507 // deduced argument type's qualifiers as if we had performed the
2508 // qualification conversion.
2509 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2510 }
2511 }
2512
2513 // - The transformed A can be another pointer or pointer to member
2514 // type that can be converted to the deduced A via a qualification
2515 // conversion.
Chandler Carruth18e04612011-06-18 01:19:03 +00002516 //
2517 // Also allow conversions which merely strip [[noreturn]] from function types
2518 // (recursively) as an extension.
2519 // FIXME: Currently, this doesn't place nicely with qualfication conversions.
Douglas Gregorb7edc4f2011-06-17 05:18:17 +00002520 bool ObjCLifetimeConversion = false;
Chandler Carruth18e04612011-06-18 01:19:03 +00002521 QualType ResultTy;
Douglas Gregorb7edc4f2011-06-17 05:18:17 +00002522 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth18e04612011-06-18 01:19:03 +00002523 (S.IsQualificationConversion(A, DeducedA, false,
2524 ObjCLifetimeConversion) ||
2525 S.IsNoReturnConversion(A, DeducedA, ResultTy)))
Douglas Gregorb7edc4f2011-06-17 05:18:17 +00002526 return false;
2527
2528
2529 // - If P is a class and P has the form simple-template-id, then the
2530 // transformed A can be a derived class of the deduced A. [...]
2531 // [...] Likewise, if P is a pointer to a class of the form
2532 // simple-template-id, the transformed A can be a pointer to a
2533 // derived class pointed to by the deduced A.
2534 if (const PointerType *OriginalParamPtr
2535 = OriginalParamType->getAs<PointerType>()) {
2536 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2537 if (const PointerType *APtr = A->getAs<PointerType>()) {
2538 if (A->getPointeeType()->isRecordType()) {
2539 OriginalParamType = OriginalParamPtr->getPointeeType();
2540 DeducedA = DeducedAPtr->getPointeeType();
2541 A = APtr->getPointeeType();
2542 }
2543 }
2544 }
2545 }
2546
2547 if (Context.hasSameUnqualifiedType(A, DeducedA))
2548 return false;
2549
2550 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
2551 S.IsDerivedFrom(A, DeducedA))
2552 return false;
2553
2554 return true;
2555}
2556
Mike Stump1eb44332009-09-09 15:08:12 +00002557/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002558/// checking the deduced template arguments for completeness and forming
2559/// the function template specialization.
Douglas Gregordbfb3712011-06-16 16:50:48 +00002560///
2561/// \param OriginalCallArgs If non-NULL, the original call arguments against
2562/// which the deduced argument types should be compared.
Mike Stump1eb44332009-09-09 15:08:12 +00002563Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00002564Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002565 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002566 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002567 FunctionDecl *&Specialization,
Douglas Gregordbfb3712011-06-16 16:50:48 +00002568 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002569 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002570 TemplateParameterList *TemplateParams
2571 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00002572
Eli Friedman59a839c2012-02-08 03:07:05 +00002573 // Unevaluated SFINAE context.
2574 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +00002575 SFINAETrap Trap(*this);
2576
Douglas Gregor83314aa2009-07-08 20:55:45 +00002577 // Enter a new template instantiation context while we instantiate the
2578 // actual function declaration.
Richard Smith7e54fb52012-07-16 01:09:10 +00002579 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002580 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Richard Smith7e54fb52012-07-16 01:09:10 +00002581 FunctionTemplate, DeducedArgs,
Douglas Gregor9b623632010-10-12 23:32:35 +00002582 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2583 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00002584 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00002585 return TDK_InstantiationDepth;
2586
John McCall96db3102010-04-29 01:18:58 +00002587 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00002588
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002589 // C++ [temp.deduct.type]p2:
2590 // [...] or if any template argument remains neither deduced nor
2591 // explicitly specified, template argument deduction fails.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002592 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002593 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2594 NamedDecl *Param = TemplateParams->getParam(I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002595
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002596 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002597 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00002598 // We have already fully type-checked and converted this
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002599 // argument, because it was explicitly-specified. Just record the
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002600 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00002601 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00002602 continue;
2603 }
2604
2605 // We have deduced this argument, so it still needs to be
2606 // checked and converted.
2607
2608 // First, for a non-type template parameter type that is
2609 // initialized by a declaration, we need the type of the
2610 // corresponding non-type template parameter.
2611 QualType NTTPType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002612 if (NonTypeTemplateParmDecl *NTTP
2613 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002614 NTTPType = NTTP->getType();
2615 if (NTTPType->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002616 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002617 Builder.data(), Builder.size());
2618 NTTPType = SubstType(NTTPType,
2619 MultiLevelTemplateArgumentList(TemplateArgs),
2620 NTTP->getLocation(),
2621 NTTP->getDeclName());
2622 if (NTTPType.isNull()) {
2623 Info.Param = makeTemplateParameter(Param);
2624 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002625 Info.reset(TemplateArgumentList::CreateCopy(Context,
2626 Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002627 Builder.size()));
2628 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00002629 }
2630 }
2631 }
2632
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002633 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002634 FunctionTemplate, NTTPType, 0, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002635 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002636 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00002637 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002638 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2639 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00002640 return TDK_SubstitutionFailure;
2641 }
2642
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002643 continue;
2644 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002645
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002646 // C++0x [temp.arg.explicit]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002647 // A trailing template parameter pack (14.5.3) not otherwise deduced will
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002648 // be deduced to an empty sequence of template arguments.
2649 // FIXME: Where did the word "trailing" come from?
2650 if (Param->isTemplateParameterPack()) {
Douglas Gregord3731192011-01-10 07:32:04 +00002651 // We may have had explicitly-specified template arguments for this
2652 // template parameter pack. If so, our empty deduction extends the
2653 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2654 const TemplateArgument *ExplicitArgs;
2655 unsigned NumExplicitArgs;
Richard Smitha8eaf002012-08-23 06:16:52 +00002656 if (CurrentInstantiationScope &&
2657 CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
Douglas Gregord3731192011-01-10 07:32:04 +00002658 &NumExplicitArgs)
2659 == Param)
2660 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002661 else
Eli Friedmand7a6b162012-09-26 02:36:12 +00002662 Builder.push_back(TemplateArgument::getEmptyPack());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002663
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002664 continue;
2665 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002666
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002667 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002668 TemplateArgumentLoc DefArg
2669 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2670 FunctionTemplate->getLocation(),
2671 FunctionTemplate->getSourceRange().getEnd(),
2672 Param,
2673 Builder);
2674
2675 // If there was no default argument, deduction is incomplete.
2676 if (DefArg.getArgument().isNull()) {
2677 Info.Param = makeTemplateParameter(
2678 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2679 return TDK_Incomplete;
2680 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002681
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002682 // Check whether we can actually use the default argument.
2683 if (CheckTemplateArgument(Param, DefArg,
2684 FunctionTemplate,
2685 FunctionTemplate->getLocation(),
2686 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002687 0, Builder,
Douglas Gregor8735b292011-06-03 02:59:40 +00002688 CTAK_Specified)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002689 Info.Param = makeTemplateParameter(
2690 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00002691 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002692 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregor910f8002010-11-07 23:05:16 +00002693 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002694 return TDK_SubstitutionFailure;
2695 }
2696
2697 // If we get here, we successfully used the default template argument.
2698 }
2699
2700 // Form the template argument list from the deduced template arguments.
2701 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002702 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002703 Info.reset(DeducedArgumentList);
2704
Mike Stump1eb44332009-09-09 15:08:12 +00002705 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002706 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00002707 DeclContext *Owner = FunctionTemplate->getDeclContext();
2708 if (FunctionTemplate->getFriendObjectKind())
2709 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002710 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00002711 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00002712 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor5fad9b82011-10-12 20:35:48 +00002713 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor83314aa2009-07-08 20:55:45 +00002714 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002715
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002716 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregorf8825742009-09-15 18:26:13 +00002717 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002718
Mike Stump1eb44332009-09-09 15:08:12 +00002719 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002720 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00002721 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2722 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00002723 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002724
Douglas Gregor5fad9b82011-10-12 20:35:48 +00002725 // There may have been an error that did not prevent us from constructing a
2726 // declaration. Mark the declaration invalid and return with a substitution
2727 // failure.
2728 if (Trap.hasErrorOccurred()) {
2729 Specialization->setInvalidDecl(true);
2730 return TDK_SubstitutionFailure;
2731 }
2732
Douglas Gregordbfb3712011-06-16 16:50:48 +00002733 if (OriginalCallArgs) {
2734 // C++ [temp.deduct.call]p4:
2735 // In general, the deduction process attempts to find template argument
2736 // values that will make the deduced A identical to A (after the type A
2737 // is transformed as described above). [...]
2738 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2739 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregordbfb3712011-06-16 16:50:48 +00002740 unsigned ParamIdx = OriginalArg.ArgIdx;
2741
2742 if (ParamIdx >= Specialization->getNumParams())
2743 continue;
2744
2745 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Douglas Gregorb7edc4f2011-06-17 05:18:17 +00002746 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA))
2747 return Sema::TDK_SubstitutionFailure;
Douglas Gregordbfb3712011-06-16 16:50:48 +00002748 }
2749 }
2750
Douglas Gregor9b623632010-10-12 23:32:35 +00002751 // If we suppressed any diagnostics while performing template argument
2752 // deduction, and if we haven't already instantiated this declaration,
2753 // keep track of these diagnostics. They'll be emitted if this specialization
2754 // is actually used.
2755 if (Info.diag_begin() != Info.diag_end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002756 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +00002757 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2758 if (Pos == SuppressedDiagnostics.end())
2759 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2760 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002761 }
Douglas Gregor9b623632010-10-12 23:32:35 +00002762
Mike Stump1eb44332009-09-09 15:08:12 +00002763 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002764}
2765
John McCall9c72c602010-08-27 09:08:28 +00002766/// Gets the type of a function for template-argument-deducton
2767/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00002768static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00002769 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00002770 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00002771 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00002772 if (Method->isInstance()) {
2773 // An instance method that's referenced in a form that doesn't
2774 // look like a member pointer is just invalid.
2775 if (!R.HasFormOfMemberPointer) return QualType();
2776
John McCalleff92132010-02-02 02:21:27 +00002777 return Context.getMemberPointerType(Fn->getType(),
2778 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00002779 }
2780
2781 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00002782 return Context.getPointerType(Fn->getType());
2783}
2784
2785/// Apply the deduction rules for overload sets.
2786///
2787/// \return the null type if this argument should be treated as an
2788/// undeduced context
2789static QualType
2790ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002791 Expr *Arg, QualType ParamType,
2792 bool ParamWasReference) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002793
John McCall9c72c602010-08-27 09:08:28 +00002794 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00002795
John McCall9c72c602010-08-27 09:08:28 +00002796 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00002797
Douglas Gregor75f21af2010-08-30 21:04:23 +00002798 // C++0x [temp.deduct.call]p4
2799 unsigned TDF = 0;
2800 if (ParamWasReference)
2801 TDF |= TDF_ParamWithReferenceType;
2802 if (R.IsAddressOfOperand)
2803 TDF |= TDF_IgnoreQualifiers;
2804
John McCalleff92132010-02-02 02:21:27 +00002805 // C++0x [temp.deduct.call]p6:
2806 // When P is a function type, pointer to function type, or pointer
2807 // to member function type:
2808
2809 if (!ParamType->isFunctionType() &&
2810 !ParamType->isFunctionPointerType() &&
Douglas Gregor860d9b72012-03-12 21:09:16 +00002811 !ParamType->isMemberFunctionPointerType()) {
2812 if (Ovl->hasExplicitTemplateArgs()) {
2813 // But we can still look for an explicit specialization.
2814 if (FunctionDecl *ExplicitSpec
2815 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
2816 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
2817 }
John McCalleff92132010-02-02 02:21:27 +00002818
Douglas Gregor860d9b72012-03-12 21:09:16 +00002819 return QualType();
2820 }
2821
2822 // Gather the explicit template arguments, if any.
2823 TemplateArgumentListInfo ExplicitTemplateArgs;
2824 if (Ovl->hasExplicitTemplateArgs())
2825 Ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
John McCalleff92132010-02-02 02:21:27 +00002826 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00002827 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2828 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00002829 NamedDecl *D = (*I)->getUnderlyingDecl();
2830
Douglas Gregor860d9b72012-03-12 21:09:16 +00002831 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
2832 // - If the argument is an overload set containing one or more
2833 // function templates, the parameter is treated as a
2834 // non-deduced context.
2835 if (!Ovl->hasExplicitTemplateArgs())
2836 return QualType();
2837
2838 // Otherwise, see if we can resolve a function type
2839 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00002840 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor860d9b72012-03-12 21:09:16 +00002841 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
2842 Specialization, Info))
2843 continue;
2844
2845 D = Specialization;
2846 }
John McCalleff92132010-02-02 02:21:27 +00002847
2848 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00002849 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2850 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00002851
Douglas Gregor75f21af2010-08-30 21:04:23 +00002852 // Function-to-pointer conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002853 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor75f21af2010-08-30 21:04:23 +00002854 ArgType->isFunctionType())
2855 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002856
John McCalleff92132010-02-02 02:21:27 +00002857 // - If the argument is an overload set (not containing function
2858 // templates), trial argument deduction is attempted using each
2859 // of the members of the set. If deduction succeeds for only one
2860 // of the overload set members, that member is used as the
2861 // argument value for the deduction. If deduction succeeds for
2862 // more than one member of the overload set the parameter is
2863 // treated as a non-deduced context.
2864
2865 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2866 // Type deduction is done independently for each P/A pair, and
2867 // the deduced template argument values are then combined.
2868 // So we do not reject deductions which were made elsewhere.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002869 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregor02024a92010-03-28 02:42:43 +00002870 Deduced(TemplateParams->size());
Craig Topper93e45992012-09-19 02:26:47 +00002871 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00002872 Sema::TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +00002873 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
2874 ArgType, Info, Deduced, TDF);
John McCalleff92132010-02-02 02:21:27 +00002875 if (Result) continue;
2876 if (!Match.isNull()) return QualType();
2877 Match = ArgType;
2878 }
2879
2880 return Match;
2881}
2882
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002883/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002884/// described in C++ [temp.deduct.call].
2885///
2886/// \returns true if the caller should not attempt to perform any template
2887/// argument deduction based on this P/A pair.
2888static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
2889 TemplateParameterList *TemplateParams,
2890 QualType &ParamType,
2891 QualType &ArgType,
2892 Expr *Arg,
2893 unsigned &TDF) {
2894 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002895 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002896 // are ignored for type deduction.
Douglas Gregora459cc22011-04-27 23:34:22 +00002897 if (ParamType.hasQualifiers())
2898 ParamType = ParamType.getUnqualifiedType();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002899 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2900 if (ParamRefType) {
Richard Smith34b41d92011-02-20 03:19:35 +00002901 QualType PointeeType = ParamRefType->getPointeeType();
2902
Douglas Gregorf15748a2011-06-03 03:35:07 +00002903 // If the argument has incomplete array type, try to complete it's type.
Douglas Gregord10099e2012-05-04 16:32:21 +00002904 if (ArgType->isIncompleteArrayType() && !S.RequireCompleteExprType(Arg, 0))
Douglas Gregorf15748a2011-06-03 03:35:07 +00002905 ArgType = Arg->getType();
2906
Douglas Gregor2ad746a2011-01-21 05:18:22 +00002907 // [C++0x] If P is an rvalue reference to a cv-unqualified
2908 // template parameter and the argument is an lvalue, the type
2909 // "lvalue reference to A" is used in place of A for type
2910 // deduction.
Richard Smith34b41d92011-02-20 03:19:35 +00002911 if (isa<RValueReferenceType>(ParamType)) {
2912 if (!PointeeType.getQualifiers() &&
2913 isa<TemplateTypeParmType>(PointeeType) &&
Douglas Gregor9625e442011-05-21 22:16:50 +00002914 Arg->Classify(S.Context).isLValue() &&
2915 Arg->getType() != S.Context.OverloadTy &&
2916 Arg->getType() != S.Context.BoundMemberTy)
Douglas Gregor2ad746a2011-01-21 05:18:22 +00002917 ArgType = S.Context.getLValueReferenceType(ArgType);
2918 }
2919
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002920 // [...] If P is a reference type, the type referred to by P is used
2921 // for type deduction.
Richard Smith34b41d92011-02-20 03:19:35 +00002922 ParamType = PointeeType;
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002923 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002924
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002925 // Overload sets usually make this parameter an undeduced
2926 // context, but there are sometimes special circumstances.
2927 if (ArgType == S.Context.OverloadTy) {
2928 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
2929 Arg, ParamType,
2930 ParamRefType != 0);
2931 if (ArgType.isNull())
2932 return true;
2933 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002934
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002935 if (ParamRefType) {
2936 // C++0x [temp.deduct.call]p3:
2937 // [...] If P is of the form T&&, where T is a template parameter, and
2938 // the argument is an lvalue, the type A& is used in place of A for
2939 // type deduction.
2940 if (ParamRefType->isRValueReferenceType() &&
2941 ParamRefType->getAs<TemplateTypeParmType>() &&
2942 Arg->isLValue())
2943 ArgType = S.Context.getLValueReferenceType(ArgType);
2944 } else {
2945 // C++ [temp.deduct.call]p2:
2946 // If P is not a reference type:
2947 // - If A is an array type, the pointer type produced by the
2948 // array-to-pointer standard conversion (4.2) is used in place of
2949 // A for type deduction; otherwise,
2950 if (ArgType->isArrayType())
2951 ArgType = S.Context.getArrayDecayedType(ArgType);
2952 // - If A is a function type, the pointer type produced by the
2953 // function-to-pointer standard conversion (4.3) is used in place
2954 // of A for type deduction; otherwise,
2955 else if (ArgType->isFunctionType())
2956 ArgType = S.Context.getPointerType(ArgType);
2957 else {
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002958 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002959 // type are ignored for type deduction.
Douglas Gregora459cc22011-04-27 23:34:22 +00002960 ArgType = ArgType.getUnqualifiedType();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002961 }
2962 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002963
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002964 // C++0x [temp.deduct.call]p4:
2965 // In general, the deduction process attempts to find template argument
2966 // values that will make the deduced A identical to A (after the type A
2967 // is transformed as described above). [...]
2968 TDF = TDF_SkipNonDependent;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002969
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002970 // - If the original P is a reference type, the deduced A (i.e., the
2971 // type referred to by the reference) can be more cv-qualified than
2972 // the transformed A.
2973 if (ParamRefType)
2974 TDF |= TDF_ParamWithReferenceType;
2975 // - The transformed A can be another pointer or pointer to member
2976 // type that can be converted to the deduced A via a qualification
2977 // conversion (4.4).
2978 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2979 ArgType->isObjCObjectPointerType())
2980 TDF |= TDF_IgnoreQualifiers;
2981 // - If P is a class and P has the form simple-template-id, then the
2982 // transformed A can be a derived class of the deduced A. Likewise,
2983 // if P is a pointer to a class of the form simple-template-id, the
2984 // transformed A can be a pointer to a derived class pointed to by
2985 // the deduced A.
2986 if (isSimpleTemplateIdType(ParamType) ||
2987 (isa<PointerType>(ParamType) &&
2988 isSimpleTemplateIdType(
2989 ParamType->getAs<PointerType>()->getPointeeType())))
2990 TDF |= TDF_DerivedClass;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002991
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002992 return false;
2993}
2994
Douglas Gregordbfb3712011-06-16 16:50:48 +00002995static bool hasDeducibleTemplateParameters(Sema &S,
2996 FunctionTemplateDecl *FunctionTemplate,
2997 QualType T);
2998
Sebastian Redl4b911e62012-03-15 21:40:51 +00002999/// \brief Perform template argument deduction by matching a parameter type
3000/// against a single expression, where the expression is an element of
3001/// an initializer list that was originally matched against the argument
3002/// type.
3003static Sema::TemplateDeductionResult
3004DeduceTemplateArgumentByListElement(Sema &S,
3005 TemplateParameterList *TemplateParams,
3006 QualType ParamType, Expr *Arg,
3007 TemplateDeductionInfo &Info,
3008 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3009 unsigned TDF) {
3010 // Handle the case where an init list contains another init list as the
3011 // element.
3012 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3013 QualType X;
3014 if (!S.isStdInitializerList(ParamType.getNonReferenceType(), &X))
3015 return Sema::TDK_Success; // Just ignore this expression.
3016
3017 // Recurse down into the init list.
3018 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3019 if (Sema::TemplateDeductionResult Result =
3020 DeduceTemplateArgumentByListElement(S, TemplateParams, X,
3021 ILE->getInit(i),
3022 Info, Deduced, TDF))
3023 return Result;
3024 }
3025 return Sema::TDK_Success;
3026 }
3027
3028 // For all other cases, just match by type.
Douglas Gregord2803892012-04-04 05:10:53 +00003029 QualType ArgType = Arg->getType();
3030 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
3031 ArgType, Arg, TDF))
3032 return Sema::TDK_FailedOverloadResolution;
Sebastian Redl4b911e62012-03-15 21:40:51 +00003033 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregord2803892012-04-04 05:10:53 +00003034 ArgType, Info, Deduced, TDF);
Sebastian Redl4b911e62012-03-15 21:40:51 +00003035}
3036
Douglas Gregore53060f2009-06-25 22:08:12 +00003037/// \brief Perform template argument deduction from a function call
3038/// (C++ [temp.deduct.call]).
3039///
3040/// \param FunctionTemplate the function template for which we are performing
3041/// template argument deduction.
3042///
James Dennett40ae6662012-06-22 08:52:37 +00003043/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregor48026d22010-01-11 18:40:55 +00003044/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003045///
Douglas Gregore53060f2009-06-25 22:08:12 +00003046/// \param Args the function call arguments
3047///
Douglas Gregor48026d22010-01-11 18:40:55 +00003048/// \param Name the name of the function being called. This is only significant
3049/// when the function template is a conversion function template, in which
3050/// case this routine will also perform template argument deduction based on
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003051/// the function to which
Douglas Gregor48026d22010-01-11 18:40:55 +00003052///
Douglas Gregore53060f2009-06-25 22:08:12 +00003053/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00003054/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00003055/// template argument deduction.
3056///
3057/// \param Info the argument will be updated to provide additional information
3058/// about template argument deduction.
3059///
3060/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00003061Sema::TemplateDeductionResult
3062Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor67714232011-03-03 02:41:12 +00003063 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003064 llvm::ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00003065 FunctionDecl *&Specialization,
3066 TemplateDeductionInfo &Info) {
Douglas Gregorae19fbb2012-09-13 21:01:57 +00003067 if (FunctionTemplate->isInvalidDecl())
3068 return TDK_Invalid;
3069
Douglas Gregore53060f2009-06-25 22:08:12 +00003070 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003071
Douglas Gregore53060f2009-06-25 22:08:12 +00003072 // C++ [temp.deduct.call]p1:
3073 // Template argument deduction is done by comparing each function template
3074 // parameter type (call it P) with the type of the corresponding argument
3075 // of the call (call it A) as described below.
Ahmed Charles13a140c2012-02-25 11:00:22 +00003076 unsigned CheckArgs = Args.size();
3077 if (Args.size() < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00003078 return TDK_TooFewArguments;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003079 else if (Args.size() > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003080 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00003081 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003082 if (Proto->isTemplateVariadic())
3083 /* Do nothing */;
3084 else if (Proto->isVariadic())
3085 CheckArgs = Function->getNumParams();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003086 else
Douglas Gregore53060f2009-06-25 22:08:12 +00003087 return TDK_TooManyArguments;
Douglas Gregore53060f2009-06-25 22:08:12 +00003088 }
Mike Stump1eb44332009-09-09 15:08:12 +00003089
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003090 // The types of the parameters from which we will perform template argument
3091 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00003092 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00003093 TemplateParameterList *TemplateParams
3094 = FunctionTemplate->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003095 SmallVector<DeducedTemplateArgument, 4> Deduced;
3096 SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00003097 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00003098 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00003099 TemplateDeductionResult Result =
3100 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00003101 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00003102 Deduced,
3103 ParamTypes,
3104 0,
3105 Info);
3106 if (Result)
3107 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00003108
3109 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003110 } else {
3111 // Just fill in the parameter types from the function declaration.
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003112 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003113 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3114 }
Mike Stump1eb44332009-09-09 15:08:12 +00003115
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003116 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00003117 Deduced.resize(TemplateParams->size());
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003118 unsigned ArgIdx = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003119 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003120 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003121 ParamIdx != NumParams; ++ParamIdx) {
Douglas Gregordbfb3712011-06-16 16:50:48 +00003122 QualType OrigParamType = ParamTypes[ParamIdx];
3123 QualType ParamType = OrigParamType;
3124
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003125 const PackExpansionType *ParamExpansion
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003126 = dyn_cast<PackExpansionType>(ParamType);
3127 if (!ParamExpansion) {
3128 // Simple case: matching a function parameter to a function argument.
3129 if (ArgIdx >= CheckArgs)
3130 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003131
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003132 Expr *Arg = Args[ArgIdx++];
3133 QualType ArgType = Arg->getType();
Douglas Gregordbfb3712011-06-16 16:50:48 +00003134
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003135 unsigned TDF = 0;
3136 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3137 ParamType, ArgType, Arg,
3138 TDF))
3139 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003140
Douglas Gregord8f5b332011-10-09 22:06:46 +00003141 // If we have nothing to deduce, we're done.
3142 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3143 continue;
3144
Sebastian Redl84760e32012-01-17 22:49:58 +00003145 // If the argument is an initializer list ...
3146 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3147 // ... then the parameter is an undeduced context, unless the parameter
3148 // type is (reference to cv) std::initializer_list<P'>, in which case
3149 // deduction is done for each element of the initializer list, and the
3150 // result is the deduced type if it's the same for all elements.
3151 QualType X;
3152 // Removing references was already done.
3153 if (!isStdInitializerList(ParamType, &X))
3154 continue;
3155
3156 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3157 if (TemplateDeductionResult Result =
Sebastian Redl4b911e62012-03-15 21:40:51 +00003158 DeduceTemplateArgumentByListElement(*this, TemplateParams, X,
3159 ILE->getInit(i),
3160 Info, Deduced, TDF))
Sebastian Redl84760e32012-01-17 22:49:58 +00003161 return Result;
3162 }
3163 // Don't track the argument type, since an initializer list has none.
3164 continue;
3165 }
3166
Douglas Gregordbfb3712011-06-16 16:50:48 +00003167 // Keep track of the argument type and corresponding parameter index,
3168 // so we can check for compatibility between the deduced A and A.
Douglas Gregord8f5b332011-10-09 22:06:46 +00003169 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
3170 ArgType));
Douglas Gregordbfb3712011-06-16 16:50:48 +00003171
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003172 if (TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +00003173 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3174 ParamType, ArgType,
3175 Info, Deduced, TDF))
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003176 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00003177
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003178 continue;
Douglas Gregor75f21af2010-08-30 21:04:23 +00003179 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003180
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003181 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003182 // For a function parameter pack that occurs at the end of the
3183 // parameter-declaration-list, the type A of each remaining argument of
3184 // the call is compared with the type P of the declarator-id of the
3185 // function parameter pack. Each comparison deduces template arguments
3186 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor7d5c0c12011-01-11 01:52:23 +00003187 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003188 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor7d5c0c12011-01-11 01:52:23 +00003189 // the parameter pack is a non-deduced context.
3190 if (ParamIdx + 1 < NumParams)
3191 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003192
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003193 QualType ParamPattern = ParamExpansion->getPattern();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003194 SmallVector<unsigned, 2> PackIndices;
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003195 {
Benjamin Kramer013b3662012-01-30 16:17:39 +00003196 llvm::SmallBitVector SawIndices(TemplateParams->size());
Chris Lattner5f9e2722011-07-23 10:55:15 +00003197 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003198 collectUnexpandedParameterPacks(ParamPattern, Unexpanded);
3199 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
3200 unsigned Depth, Index;
3201 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
3202 if (Depth == 0 && !SawIndices[Index]) {
3203 SawIndices[Index] = true;
3204 PackIndices.push_back(Index);
3205 }
Douglas Gregore53060f2009-06-25 22:08:12 +00003206 }
3207 }
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003208 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003209
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003210 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003211 // expanded by this pack expansion (the outer index) and for each
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003212 // template argument (the inner SmallVectors).
Chris Lattner5f9e2722011-07-23 10:55:15 +00003213 SmallVector<SmallVector<DeducedTemplateArgument, 4>, 2>
Douglas Gregord3731192011-01-10 07:32:04 +00003214 NewlyDeducedPacks(PackIndices.size());
Chris Lattner5f9e2722011-07-23 10:55:15 +00003215 SmallVector<DeducedTemplateArgument, 2>
Douglas Gregord3731192011-01-10 07:32:04 +00003216 SavedPacks(PackIndices.size());
Douglas Gregor54293852011-01-10 17:35:05 +00003217 PrepareArgumentPackDeduction(*this, Deduced, PackIndices, SavedPacks,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003218 NewlyDeducedPacks);
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003219 bool HasAnyArguments = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003220 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003221 HasAnyArguments = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003222
Douglas Gregordbfb3712011-06-16 16:50:48 +00003223 QualType OrigParamType = ParamPattern;
3224 ParamType = OrigParamType;
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003225 Expr *Arg = Args[ArgIdx];
3226 QualType ArgType = Arg->getType();
Douglas Gregordbfb3712011-06-16 16:50:48 +00003227
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003228 unsigned TDF = 0;
3229 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3230 ParamType, ArgType, Arg,
3231 TDF)) {
3232 // We can't actually perform any deduction for this argument, so stop
3233 // deduction at this point.
3234 ++ArgIdx;
3235 break;
3236 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003237
Sebastian Redl84760e32012-01-17 22:49:58 +00003238 // As above, initializer lists need special handling.
3239 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3240 QualType X;
3241 if (!isStdInitializerList(ParamType, &X)) {
3242 ++ArgIdx;
3243 break;
3244 }
Douglas Gregordbfb3712011-06-16 16:50:48 +00003245
Sebastian Redl84760e32012-01-17 22:49:58 +00003246 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3247 if (TemplateDeductionResult Result =
3248 DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, X,
3249 ILE->getInit(i)->getType(),
3250 Info, Deduced, TDF))
3251 return Result;
3252 }
3253 } else {
3254
3255 // Keep track of the argument type and corresponding argument index,
3256 // so we can check for compatibility between the deduced A and A.
3257 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3258 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
3259 ArgType));
3260
3261 if (TemplateDeductionResult Result
3262 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3263 ParamType, ArgType, Info,
3264 Deduced, TDF))
3265 return Result;
3266 }
Mike Stump1eb44332009-09-09 15:08:12 +00003267
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003268 // Capture the deduced template arguments for each parameter pack expanded
3269 // by this pack expansion, add them to the list of arguments we've deduced
3270 // for that pack, then clear out the deduced argument.
3271 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
3272 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
3273 if (!DeducedArg.isNull()) {
3274 NewlyDeducedPacks[I].push_back(DeducedArg);
3275 DeducedArg = DeducedTemplateArgument();
3276 }
3277 }
3278 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003279
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003280 // Build argument packs for each of the parameter packs expanded by this
3281 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +00003282 if (Sema::TemplateDeductionResult Result
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003283 = FinishArgumentPackDeduction(*this, TemplateParams, HasAnyArguments,
Douglas Gregor0216f812011-01-10 17:53:52 +00003284 Deduced, PackIndices, SavedPacks,
3285 NewlyDeducedPacks, Info))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003286 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00003287
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003288 // After we've matching against a parameter pack, we're done.
3289 break;
Douglas Gregore53060f2009-06-25 22:08:12 +00003290 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003291
Mike Stump1eb44332009-09-09 15:08:12 +00003292 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00003293 NumExplicitlySpecified,
Douglas Gregordbfb3712011-06-16 16:50:48 +00003294 Specialization, Info, &OriginalCallArgs);
Douglas Gregore53060f2009-06-25 22:08:12 +00003295}
3296
Douglas Gregor83314aa2009-07-08 20:55:45 +00003297/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00003298/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3299/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003300///
3301/// \param FunctionTemplate the function template for which we are performing
3302/// template argument deduction.
3303///
James Dennett40ae6662012-06-22 08:52:37 +00003304/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor4b52e252009-12-21 23:17:24 +00003305/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003306///
3307/// \param ArgFunctionType the function type that will be used as the
3308/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00003309/// function template's function type. This type may be NULL, if there is no
3310/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003311///
3312/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00003313/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00003314/// template argument deduction.
3315///
3316/// \param Info the argument will be updated to provide additional information
3317/// about template argument deduction.
3318///
3319/// \returns the result of template argument deduction.
3320Sema::TemplateDeductionResult
3321Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor67714232011-03-03 02:41:12 +00003322 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00003323 QualType ArgFunctionType,
3324 FunctionDecl *&Specialization,
3325 TemplateDeductionInfo &Info) {
Douglas Gregorae19fbb2012-09-13 21:01:57 +00003326 if (FunctionTemplate->isInvalidDecl())
3327 return TDK_Invalid;
3328
Douglas Gregor83314aa2009-07-08 20:55:45 +00003329 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3330 TemplateParameterList *TemplateParams
3331 = FunctionTemplate->getTemplateParameters();
3332 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003333
Douglas Gregor83314aa2009-07-08 20:55:45 +00003334 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00003335 LocalInstantiationScope InstScope(*this);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003336 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor02024a92010-03-28 02:42:43 +00003337 unsigned NumExplicitlySpecified = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003338 SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00003339 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003340 if (TemplateDeductionResult Result
3341 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00003342 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00003343 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00003344 &FunctionType, Info))
3345 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00003346
3347 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00003348 }
3349
Eli Friedman59a839c2012-02-08 03:07:05 +00003350 // Unevaluated SFINAE context.
3351 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +00003352 SFINAETrap Trap(*this);
3353
John McCalleff92132010-02-02 02:21:27 +00003354 Deduced.resize(TemplateParams->size());
3355
Douglas Gregor4b52e252009-12-21 23:17:24 +00003356 if (!ArgFunctionType.isNull()) {
3357 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00003358 if (TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +00003359 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00003360 FunctionType, ArgFunctionType, Info,
Douglas Gregor73b3cf62011-01-25 17:19:08 +00003361 Deduced, TDF_TopLevelParameterTypeList))
Douglas Gregor4b52e252009-12-21 23:17:24 +00003362 return Result;
3363 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00003364
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003365 if (TemplateDeductionResult Result
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00003366 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3367 NumExplicitlySpecified,
3368 Specialization, Info))
3369 return Result;
3370
3371 // If the requested function type does not match the actual type of the
3372 // specialization, template argument deduction fails.
3373 if (!ArgFunctionType.isNull() &&
3374 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
3375 return TDK_NonDeducedMismatch;
3376
3377 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00003378}
3379
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003380/// \brief Deduce template arguments for a templated conversion
3381/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3382/// conversion function template specialization.
3383Sema::TemplateDeductionResult
3384Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
3385 QualType ToType,
3386 CXXConversionDecl *&Specialization,
3387 TemplateDeductionInfo &Info) {
Douglas Gregorae19fbb2012-09-13 21:01:57 +00003388 if (FunctionTemplate->isInvalidDecl())
3389 return TDK_Invalid;
3390
Mike Stump1eb44332009-09-09 15:08:12 +00003391 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003392 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
3393 QualType FromType = Conv->getConversionType();
3394
3395 // Canonicalize the types for deduction.
3396 QualType P = Context.getCanonicalType(FromType);
3397 QualType A = Context.getCanonicalType(ToType);
3398
Douglas Gregor5453d932011-03-06 09:03:20 +00003399 // C++0x [temp.deduct.conv]p2:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003400 // If P is a reference type, the type referred to by P is used for
3401 // type deduction.
3402 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3403 P = PRef->getPointeeType();
3404
Douglas Gregor5453d932011-03-06 09:03:20 +00003405 // C++0x [temp.deduct.conv]p4:
3406 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003407 // for type deduction.
3408 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregor5453d932011-03-06 09:03:20 +00003409 A = ARef->getPointeeType().getUnqualifiedType();
3410 // C++ [temp.deduct.conv]p3:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003411 //
Mike Stump1eb44332009-09-09 15:08:12 +00003412 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003413 else {
3414 assert(!A->isReferenceType() && "Reference types were handled above");
3415
3416 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00003417 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003418 // of P for type deduction; otherwise,
3419 if (P->isArrayType())
3420 P = Context.getArrayDecayedType(P);
3421 // - If P is a function type, the pointer type produced by the
3422 // function-to-pointer standard conversion (4.3) is used in
3423 // place of P for type deduction; otherwise,
3424 else if (P->isFunctionType())
3425 P = Context.getPointerType(P);
3426 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003427 // P's type are ignored for type deduction.
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003428 else
3429 P = P.getUnqualifiedType();
3430
Douglas Gregor5453d932011-03-06 09:03:20 +00003431 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003432 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor5453d932011-03-06 09:03:20 +00003433 // type are ignored for type deduction. If A is a reference type, the type
3434 // referred to by A is used for type deduction.
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003435 A = A.getUnqualifiedType();
3436 }
3437
Eli Friedman59a839c2012-02-08 03:07:05 +00003438 // Unevaluated SFINAE context.
3439 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +00003440 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003441
3442 // C++ [temp.deduct.conv]p1:
3443 // Template argument deduction is done by comparing the return
3444 // type of the template conversion function (call it P) with the
3445 // type that is required as the result of the conversion (call it
3446 // A) as described in 14.8.2.4.
3447 TemplateParameterList *TemplateParams
3448 = FunctionTemplate->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003449 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00003450 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003451
3452 // C++0x [temp.deduct.conv]p4:
3453 // In general, the deduction process attempts to find template
3454 // argument values that will make the deduced A identical to
3455 // A. However, there are two cases that allow a difference:
3456 unsigned TDF = 0;
3457 // - If the original A is a reference type, A can be more
3458 // cv-qualified than the deduced A (i.e., the type referred to
3459 // by the reference)
3460 if (ToType->isReferenceType())
3461 TDF |= TDF_ParamWithReferenceType;
3462 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003463 // type that can be converted to A via a qualification
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003464 // conversion.
3465 //
3466 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3467 // both P and A are pointers or member pointers. In this case, we
3468 // just ignore cv-qualifiers completely).
3469 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor2cae1e22011-08-30 00:37:54 +00003470 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003471 TDF |= TDF_IgnoreQualifiers;
3472 if (TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +00003473 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3474 P, A, Info, Deduced, TDF))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003475 return Result;
3476
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003477 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00003478 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003479 FunctionDecl *Spec = 0;
3480 TemplateDeductionResult Result
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003481 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
Douglas Gregor02024a92010-03-28 02:42:43 +00003482 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003483 Specialization = cast_or_null<CXXConversionDecl>(Spec);
3484 return Result;
3485}
3486
Douglas Gregor4b52e252009-12-21 23:17:24 +00003487/// \brief Deduce template arguments for a function template when there is
3488/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3489///
3490/// \param FunctionTemplate the function template for which we are performing
3491/// template argument deduction.
3492///
James Dennett40ae6662012-06-22 08:52:37 +00003493/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor4b52e252009-12-21 23:17:24 +00003494/// arguments.
3495///
3496/// \param Specialization if template argument deduction was successful,
3497/// this will be set to the function template specialization produced by
3498/// template argument deduction.
3499///
3500/// \param Info the argument will be updated to provide additional information
3501/// about template argument deduction.
3502///
3503/// \returns the result of template argument deduction.
3504Sema::TemplateDeductionResult
3505Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor67714232011-03-03 02:41:12 +00003506 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor4b52e252009-12-21 23:17:24 +00003507 FunctionDecl *&Specialization,
3508 TemplateDeductionInfo &Info) {
3509 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
3510 QualType(), Specialization, Info);
3511}
3512
Richard Smith34b41d92011-02-20 03:19:35 +00003513namespace {
3514 /// Substitute the 'auto' type specifier within a type for a given replacement
3515 /// type.
3516 class SubstituteAutoTransform :
3517 public TreeTransform<SubstituteAutoTransform> {
3518 QualType Replacement;
3519 public:
3520 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement) :
3521 TreeTransform<SubstituteAutoTransform>(SemaRef), Replacement(Replacement) {
3522 }
3523 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3524 // If we're building the type pattern to deduce against, don't wrap the
3525 // substituted type in an AutoType. Certain template deduction rules
3526 // apply only when a template type parameter appears directly (and not if
3527 // the parameter is found through desugaring). For instance:
3528 // auto &&lref = lvalue;
3529 // must transform into "rvalue reference to T" not "rvalue reference to
3530 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
3531 if (isa<TemplateTypeParmType>(Replacement)) {
3532 QualType Result = Replacement;
3533 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
3534 NewTL.setNameLoc(TL.getNameLoc());
3535 return Result;
3536 } else {
3537 QualType Result = RebuildAutoType(Replacement);
3538 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3539 NewTL.setNameLoc(TL.getNameLoc());
3540 return Result;
3541 }
3542 }
Douglas Gregordfca6f52012-02-13 22:00:16 +00003543
3544 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3545 // Lambdas never need to be transformed.
3546 return E;
3547 }
Richard Smith34b41d92011-02-20 03:19:35 +00003548 };
Richard Smith8ad6c862012-07-08 04:13:07 +00003549
3550 /// Determine whether the specified type (which contains an 'auto' type
3551 /// specifier) is dependent. This is not trivial, because the 'auto' specifier
3552 /// itself claims to be type-dependent.
3553 bool isDependentAutoType(QualType Ty) {
3554 while (1) {
3555 QualType Pointee = Ty->getPointeeType();
3556 if (!Pointee.isNull()) {
3557 Ty = Pointee;
3558 } else if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()){
3559 if (MPT->getClass()->isDependentType())
3560 return true;
3561 Ty = MPT->getPointeeType();
3562 } else if (const FunctionProtoType *FPT = Ty->getAs<FunctionProtoType>()){
3563 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
3564 E = FPT->arg_type_end();
3565 I != E; ++I)
3566 if ((*I)->isDependentType())
3567 return true;
3568 Ty = FPT->getResultType();
3569 } else if (Ty->isDependentSizedArrayType()) {
3570 return true;
3571 } else if (const ArrayType *AT = Ty->getAsArrayTypeUnsafe()) {
3572 Ty = AT->getElementType();
3573 } else if (Ty->getAs<DependentSizedExtVectorType>()) {
3574 return true;
3575 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3576 Ty = VT->getElementType();
3577 } else {
3578 break;
3579 }
3580 }
3581 assert(Ty->getAs<AutoType>() && "didn't find 'auto' in auto type");
3582 return false;
3583 }
Richard Smith34b41d92011-02-20 03:19:35 +00003584}
3585
3586/// \brief Deduce the type for an auto type-specifier (C++0x [dcl.spec.auto]p6)
3587///
3588/// \param Type the type pattern using the auto type-specifier.
3589///
3590/// \param Init the initializer for the variable whose type is to be deduced.
3591///
3592/// \param Result if type deduction was successful, this will be set to the
3593/// deduced type. This may still contain undeduced autos if the type is
Richard Smitha085da82011-03-17 16:11:59 +00003594/// dependent. This will be set to null if deduction succeeded, but auto
3595/// substitution failed; the appropriate diagnostic will already have been
3596/// produced in that case.
Sebastian Redlb832f6d2012-01-23 22:09:39 +00003597Sema::DeduceAutoResult
John McCall32509f12011-11-15 01:35:18 +00003598Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init,
Richard Smitha085da82011-03-17 16:11:59 +00003599 TypeSourceInfo *&Result) {
John McCall32509f12011-11-15 01:35:18 +00003600 if (Init->getType()->isNonOverloadPlaceholderType()) {
3601 ExprResult result = CheckPlaceholderExpr(Init);
Sebastian Redlb832f6d2012-01-23 22:09:39 +00003602 if (result.isInvalid()) return DAR_FailedAlreadyDiagnosed;
John McCall32509f12011-11-15 01:35:18 +00003603 Init = result.take();
3604 }
3605
Richard Smith8ad6c862012-07-08 04:13:07 +00003606 if (Init->isTypeDependent() || isDependentAutoType(Type->getType())) {
Richard Smith34b41d92011-02-20 03:19:35 +00003607 Result = Type;
Sebastian Redlb832f6d2012-01-23 22:09:39 +00003608 return DAR_Succeeded;
Richard Smith34b41d92011-02-20 03:19:35 +00003609 }
3610
3611 SourceLocation Loc = Init->getExprLoc();
3612
3613 LocalInstantiationScope InstScope(*this);
3614
3615 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003616 TemplateTypeParmDecl *TemplParam =
3617 TemplateTypeParmDecl::Create(Context, 0, SourceLocation(), Loc, 0, 0, 0,
3618 false, false);
3619 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
3620 NamedDecl *TemplParamPtr = TemplParam;
Richard Smith483b9f32011-02-21 20:05:19 +00003621 FixedSizeTemplateParameterList<1> TemplateParams(Loc, Loc, &TemplParamPtr,
3622 Loc);
3623
Richard Smitha085da82011-03-17 16:11:59 +00003624 TypeSourceInfo *FuncParamInfo =
Richard Smith34b41d92011-02-20 03:19:35 +00003625 SubstituteAutoTransform(*this, TemplArg).TransformType(Type);
Richard Smitha085da82011-03-17 16:11:59 +00003626 assert(FuncParamInfo && "substituting template parameter for 'auto' failed");
3627 QualType FuncParam = FuncParamInfo->getType();
Richard Smith34b41d92011-02-20 03:19:35 +00003628
3629 // Deduce type of TemplParam in Func(Init)
Chris Lattner5f9e2722011-07-23 10:55:15 +00003630 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith34b41d92011-02-20 03:19:35 +00003631 Deduced.resize(1);
3632 QualType InitType = Init->getType();
3633 unsigned TDF = 0;
Richard Smith34b41d92011-02-20 03:19:35 +00003634
Craig Topper93e45992012-09-19 02:26:47 +00003635 TemplateDeductionInfo Info(Loc);
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003636
Richard Smith8ad6c862012-07-08 04:13:07 +00003637 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003638 if (InitList) {
3639 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smith8ad6c862012-07-08 04:13:07 +00003640 if (DeduceTemplateArgumentByListElement(*this, &TemplateParams,
Douglas Gregord2803892012-04-04 05:10:53 +00003641 TemplArg,
3642 InitList->getInit(i),
3643 Info, Deduced, TDF))
Sebastian Redlb832f6d2012-01-23 22:09:39 +00003644 return DAR_Failed;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003645 }
3646 } else {
Douglas Gregord2803892012-04-04 05:10:53 +00003647 if (AdjustFunctionParmAndArgTypesForDeduction(*this, &TemplateParams,
3648 FuncParam, InitType, Init,
3649 TDF))
3650 return DAR_Failed;
Richard Smith8ad6c862012-07-08 04:13:07 +00003651
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003652 if (DeduceTemplateArgumentsByTypeMatch(*this, &TemplateParams, FuncParam,
3653 InitType, Info, Deduced, TDF))
Sebastian Redlb832f6d2012-01-23 22:09:39 +00003654 return DAR_Failed;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003655 }
Richard Smith34b41d92011-02-20 03:19:35 +00003656
Eli Friedman70a01892012-11-06 23:56:42 +00003657 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redlb832f6d2012-01-23 22:09:39 +00003658 return DAR_Failed;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003659
Eli Friedman70a01892012-11-06 23:56:42 +00003660 QualType DeducedType = Deduced[0].getAsType();
3661
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003662 if (InitList) {
3663 DeducedType = BuildStdInitializerList(DeducedType, Loc);
3664 if (DeducedType.isNull())
Sebastian Redlb832f6d2012-01-23 22:09:39 +00003665 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003666 }
3667
Richard Smith34b41d92011-02-20 03:19:35 +00003668 Result = SubstituteAutoTransform(*this, DeducedType).TransformType(Type);
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003669
Douglas Gregor9a636e82011-06-17 05:31:46 +00003670 // Check that the deduced argument type is compatible with the original
3671 // argument type per C++ [temp.deduct.call]p4.
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003672 if (!InitList && Result &&
Douglas Gregor9a636e82011-06-17 05:31:46 +00003673 CheckOriginalCallArgDeduction(*this,
3674 Sema::OriginalCallArg(FuncParam,0,InitType),
3675 Result->getType())) {
3676 Result = 0;
Sebastian Redlb832f6d2012-01-23 22:09:39 +00003677 return DAR_Failed;
Douglas Gregor9a636e82011-06-17 05:31:46 +00003678 }
3679
Sebastian Redlb832f6d2012-01-23 22:09:39 +00003680 return DAR_Succeeded;
Richard Smith34b41d92011-02-20 03:19:35 +00003681}
3682
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003683void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
3684 if (isa<InitListExpr>(Init))
3685 Diag(VDecl->getLocation(),
3686 diag::err_auto_var_deduction_failure_from_init_list)
3687 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
3688 else
3689 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
3690 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
3691 << Init->getSourceRange();
3692}
3693
Douglas Gregor8a514912009-09-14 18:39:43 +00003694static void
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00003695MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore73bb602009-09-14 21:25:05 +00003696 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003697 unsigned Level,
Benjamin Kramer013b3662012-01-30 16:17:39 +00003698 llvm::SmallBitVector &Deduced);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003699
3700/// \brief If this is a non-static member function,
Eli Friedman407c8472012-09-19 23:52:13 +00003701static void AddImplicitObjectParameterType(ASTContext &Context,
Douglas Gregor77bc5722010-11-12 23:44:13 +00003702 CXXMethodDecl *Method,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003703 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedman407c8472012-09-19 23:52:13 +00003704 // C++11 [temp.func.order]p3:
3705 // [...] The new parameter is of type "reference to cv A," where cv are
3706 // the cv-qualifiers of the function template (if any) and A is
3707 // the class of which the function template is a member.
Douglas Gregor77bc5722010-11-12 23:44:13 +00003708 //
Eli Friedman407c8472012-09-19 23:52:13 +00003709 // The standard doesn't say explicitly, but we pick the appropriate kind of
3710 // reference type based on [over.match.funcs]p4.
Douglas Gregor77bc5722010-11-12 23:44:13 +00003711 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
3712 ArgTy = Context.getQualifiedType(ArgTy,
3713 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedman407c8472012-09-19 23:52:13 +00003714 if (Method->getRefQualifier() == RQ_RValue)
3715 ArgTy = Context.getRValueReferenceType(ArgTy);
3716 else
3717 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor77bc5722010-11-12 23:44:13 +00003718 ArgTypes.push_back(ArgTy);
3719}
3720
Douglas Gregor8a514912009-09-14 18:39:43 +00003721/// \brief Determine whether the function template \p FT1 is at least as
3722/// specialized as \p FT2.
3723static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00003724 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00003725 FunctionTemplateDecl *FT1,
3726 FunctionTemplateDecl *FT2,
3727 TemplatePartialOrderingContext TPOC,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003728 unsigned NumCallArguments,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003729 SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) {
Douglas Gregor8a514912009-09-14 18:39:43 +00003730 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003731 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor8a514912009-09-14 18:39:43 +00003732 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
3733 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003734
Douglas Gregor8a514912009-09-14 18:39:43 +00003735 assert(Proto1 && Proto2 && "Function templates must have prototypes");
3736 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003737 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00003738 Deduced.resize(TemplateParams->size());
3739
3740 // C++0x [temp.deduct.partial]p3:
3741 // The types used to determine the ordering depend on the context in which
3742 // the partial ordering is done:
Craig Topper93e45992012-09-19 02:26:47 +00003743 TemplateDeductionInfo Info(Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003744 CXXMethodDecl *Method1 = 0;
3745 CXXMethodDecl *Method2 = 0;
3746 bool IsNonStatic2 = false;
3747 bool IsNonStatic1 = false;
3748 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00003749 switch (TPOC) {
3750 case TPOC_Call: {
3751 // - In the context of a function call, the function parameter types are
3752 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003753 Method1 = dyn_cast<CXXMethodDecl>(FD1);
3754 Method2 = dyn_cast<CXXMethodDecl>(FD2);
3755 IsNonStatic1 = Method1 && !Method1->isStatic();
3756 IsNonStatic2 = Method2 && !Method2->isStatic();
3757
Eli Friedman9cef0062012-09-19 23:27:04 +00003758 // C++11 [temp.func.order]p3:
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003759 // [...] If only one of the function templates is a non-static
3760 // member, that function template is considered to have a new
3761 // first parameter inserted in its function parameter list. The
3762 // new parameter is of type "reference to cv A," where cv are
3763 // the cv-qualifiers of the function template (if any) and A is
3764 // the class of which the function template is a member.
3765 //
Eli Friedman9cef0062012-09-19 23:27:04 +00003766 // Note that we interpret this to mean "if one of the function
3767 // templates is a non-static member and the other is a non-member";
3768 // otherwise, the ordering rules for static functions against non-static
3769 // functions don't make any sense.
3770 //
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003771 // C++98/03 doesn't have this provision, so instead we drop the
Eli Friedman9cef0062012-09-19 23:27:04 +00003772 // first argument of the free function, which seems to match
3773 // existing practice.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003774 SmallVector<QualType, 4> Args1;
Eli Friedman9cef0062012-09-19 23:27:04 +00003775 unsigned Skip1 = !S.getLangOpts().CPlusPlus0x && IsNonStatic2 && !Method1;
3776 if (S.getLangOpts().CPlusPlus0x && IsNonStatic1 && !Method2)
Eli Friedman407c8472012-09-19 23:52:13 +00003777 AddImplicitObjectParameterType(S.Context, Method1, Args1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003778 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003779 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00003780
Chris Lattner5f9e2722011-07-23 10:55:15 +00003781 SmallVector<QualType, 4> Args2;
Eli Friedman9cef0062012-09-19 23:27:04 +00003782 Skip2 = !S.getLangOpts().CPlusPlus0x && IsNonStatic1 && !Method2;
3783 if (S.getLangOpts().CPlusPlus0x && IsNonStatic2 && !Method1)
Eli Friedman407c8472012-09-19 23:52:13 +00003784 AddImplicitObjectParameterType(S.Context, Method2, Args2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003785 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003786 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003787
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003788 // C++ [temp.func.order]p5:
3789 // The presence of unused ellipsis and default arguments has no effect on
3790 // the partial ordering of function templates.
3791 if (Args1.size() > NumCallArguments)
3792 Args1.resize(NumCallArguments);
3793 if (Args2.size() > NumCallArguments)
3794 Args2.resize(NumCallArguments);
3795 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
3796 Args1.data(), Args1.size(), Info, Deduced,
3797 TDF_None, /*PartialOrdering=*/true,
Douglas Gregorb939a192011-01-21 17:29:42 +00003798 RefParamComparisons))
Douglas Gregor8a514912009-09-14 18:39:43 +00003799 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003800
Douglas Gregor8a514912009-09-14 18:39:43 +00003801 break;
3802 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003803
Douglas Gregor8a514912009-09-14 18:39:43 +00003804 case TPOC_Conversion:
3805 // - In the context of a call to a conversion operator, the return types
3806 // of the conversion function templates are used.
Sebastian Redlbb95e512012-01-17 22:49:52 +00003807 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
3808 Proto2->getResultType(),
3809 Proto1->getResultType(),
3810 Info, Deduced, TDF_None,
3811 /*PartialOrdering=*/true,
3812 RefParamComparisons))
Douglas Gregor8a514912009-09-14 18:39:43 +00003813 return false;
3814 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003815
Douglas Gregor8a514912009-09-14 18:39:43 +00003816 case TPOC_Other:
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003817 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor8a514912009-09-14 18:39:43 +00003818 // is used.
Sebastian Redlbb95e512012-01-17 22:49:52 +00003819 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
3820 FD2->getType(), FD1->getType(),
3821 Info, Deduced, TDF_None,
3822 /*PartialOrdering=*/true,
3823 RefParamComparisons))
Douglas Gregor8a514912009-09-14 18:39:43 +00003824 return false;
3825 break;
3826 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003827
Douglas Gregor8a514912009-09-14 18:39:43 +00003828 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003829 // In most cases, all template parameters must have values in order for
3830 // deduction to succeed, but for partial ordering purposes a template
3831 // parameter may remain without a value provided it is not used in the
Douglas Gregor8a514912009-09-14 18:39:43 +00003832 // types being used for partial ordering. [ Note: a template parameter used
3833 // in a non-deduced context is considered used. -end note]
3834 unsigned ArgIdx = 0, NumArgs = Deduced.size();
3835 for (; ArgIdx != NumArgs; ++ArgIdx)
3836 if (Deduced[ArgIdx].isNull())
3837 break;
3838
3839 if (ArgIdx == NumArgs) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003840 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor8a514912009-09-14 18:39:43 +00003841 // as FT2.
3842 return true;
3843 }
3844
Douglas Gregore73bb602009-09-14 21:25:05 +00003845 // Figure out which template parameters were used.
Benjamin Kramer013b3662012-01-30 16:17:39 +00003846 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor8a514912009-09-14 18:39:43 +00003847 switch (TPOC) {
3848 case TPOC_Call: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003849 unsigned NumParams = std::min(NumCallArguments,
3850 std::min(Proto1->getNumArgs(),
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003851 Proto2->getNumArgs()));
David Blaikie4e4d0842012-03-11 07:00:24 +00003852 if (S.getLangOpts().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00003853 ::MarkUsedTemplateParameters(S.Context, Method2->getThisType(S.Context),
3854 false,
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003855 TemplateParams->getDepth(), UsedParameters);
3856 for (unsigned I = Skip2; I < NumParams; ++I)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00003857 ::MarkUsedTemplateParameters(S.Context, Proto2->getArgType(I), false,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003858 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003859 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003860 break;
3861 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003862
Douglas Gregor8a514912009-09-14 18:39:43 +00003863 case TPOC_Conversion:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00003864 ::MarkUsedTemplateParameters(S.Context, Proto2->getResultType(), false,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003865 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003866 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003867 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003868
Douglas Gregor8a514912009-09-14 18:39:43 +00003869 case TPOC_Other:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00003870 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003871 TemplateParams->getDepth(),
3872 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003873 break;
3874 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003875
Douglas Gregor8a514912009-09-14 18:39:43 +00003876 for (; ArgIdx != NumArgs; ++ArgIdx)
3877 // If this argument had no value deduced but was used in one of the types
3878 // used for partial ordering, then deduction fails.
3879 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
3880 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003881
Douglas Gregor8a514912009-09-14 18:39:43 +00003882 return true;
3883}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003884
Douglas Gregor9da95e62011-01-16 16:03:23 +00003885/// \brief Determine whether this a function template whose parameter-type-list
3886/// ends with a function parameter pack.
3887static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
3888 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
3889 unsigned NumParams = Function->getNumParams();
3890 if (NumParams == 0)
3891 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003892
Douglas Gregor9da95e62011-01-16 16:03:23 +00003893 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
3894 if (!Last->isParameterPack())
3895 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003896
Douglas Gregor9da95e62011-01-16 16:03:23 +00003897 // Make sure that no previous parameter is a parameter pack.
3898 while (--NumParams > 0) {
3899 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
3900 return false;
3901 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003902
Douglas Gregor9da95e62011-01-16 16:03:23 +00003903 return true;
3904}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003905
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003906/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003907/// to the rules of function template partial ordering (C++ [temp.func.order]).
3908///
3909/// \param FT1 the first function template
3910///
3911/// \param FT2 the second function template
3912///
Douglas Gregor8a514912009-09-14 18:39:43 +00003913/// \param TPOC the context in which we are performing partial ordering of
3914/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00003915///
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003916/// \param NumCallArguments The number of arguments in a call, used only
3917/// when \c TPOC is \c TPOC_Call.
3918///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003919/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003920/// template is more specialized, returns NULL.
3921FunctionTemplateDecl *
3922Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
3923 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00003924 SourceLocation Loc,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003925 TemplatePartialOrderingContext TPOC,
3926 unsigned NumCallArguments) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003927 SmallVector<RefParamPartialOrderingComparison, 4> RefParamComparisons;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003928 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003929 NumCallArguments, 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003930 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003931 NumCallArguments,
Douglas Gregorb939a192011-01-21 17:29:42 +00003932 &RefParamComparisons);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003933
Douglas Gregor8a514912009-09-14 18:39:43 +00003934 if (Better1 != Better2) // We have a clear winner
3935 return Better1? FT1 : FT2;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003936
Douglas Gregor8a514912009-09-14 18:39:43 +00003937 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003938 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00003939
Douglas Gregor8a514912009-09-14 18:39:43 +00003940 // C++0x [temp.deduct.partial]p10:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003941 // If for each type being considered a given template is at least as
Douglas Gregor8a514912009-09-14 18:39:43 +00003942 // specialized for all types and more specialized for some set of types and
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003943 // the other template is not more specialized for any types or is not at
Douglas Gregor8a514912009-09-14 18:39:43 +00003944 // least as specialized for any types, then the given template is more
3945 // specialized than the other template. Otherwise, neither template is more
3946 // specialized than the other.
3947 Better1 = false;
3948 Better2 = false;
Douglas Gregorb939a192011-01-21 17:29:42 +00003949 for (unsigned I = 0, N = RefParamComparisons.size(); I != N; ++I) {
Douglas Gregor8a514912009-09-14 18:39:43 +00003950 // C++0x [temp.deduct.partial]p9:
3951 // If, for a given type, deduction succeeds in both directions (i.e., the
Douglas Gregorb939a192011-01-21 17:29:42 +00003952 // types are identical after the transformations above) and both P and A
3953 // were reference types (before being replaced with the type referred to
3954 // above):
3955
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003956 // -- if the type from the argument template was an lvalue reference
Douglas Gregorb939a192011-01-21 17:29:42 +00003957 // and the type from the parameter template was not, the argument
3958 // type is considered to be more specialized than the other;
3959 // otherwise,
3960 if (!RefParamComparisons[I].ArgIsRvalueRef &&
3961 RefParamComparisons[I].ParamIsRvalueRef) {
3962 Better2 = true;
3963 if (Better1)
3964 return 0;
3965 continue;
3966 } else if (!RefParamComparisons[I].ParamIsRvalueRef &&
3967 RefParamComparisons[I].ArgIsRvalueRef) {
3968 Better1 = true;
3969 if (Better2)
3970 return 0;
3971 continue;
Douglas Gregor8a514912009-09-14 18:39:43 +00003972 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003973
Douglas Gregorb939a192011-01-21 17:29:42 +00003974 // -- if the type from the argument template is more cv-qualified than
3975 // the type from the parameter template (as described above), the
3976 // argument type is considered to be more specialized than the
3977 // other; otherwise,
3978 switch (RefParamComparisons[I].Qualifiers) {
3979 case NeitherMoreQualified:
3980 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003981
Douglas Gregorb939a192011-01-21 17:29:42 +00003982 case ParamMoreQualified:
3983 Better1 = true;
3984 if (Better2)
3985 return 0;
3986 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003987
Douglas Gregorb939a192011-01-21 17:29:42 +00003988 case ArgMoreQualified:
3989 Better2 = true;
3990 if (Better1)
3991 return 0;
3992 continue;
3993 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003994
Douglas Gregorb939a192011-01-21 17:29:42 +00003995 // -- neither type is more specialized than the other.
Douglas Gregor8a514912009-09-14 18:39:43 +00003996 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003997
Douglas Gregor8a514912009-09-14 18:39:43 +00003998 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003999 if (Better1)
4000 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00004001 else if (Better2)
4002 return FT2;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004003
Douglas Gregor9da95e62011-01-16 16:03:23 +00004004 // FIXME: This mimics what GCC implements, but doesn't match up with the
4005 // proposed resolution for core issue 692. This area needs to be sorted out,
4006 // but for now we attempt to maintain compatibility.
4007 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4008 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4009 if (Variadic1 != Variadic2)
4010 return Variadic1? FT2 : FT1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004011
Douglas Gregor9da95e62011-01-16 16:03:23 +00004012 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004013}
Douglas Gregor83314aa2009-07-08 20:55:45 +00004014
Douglas Gregord5a423b2009-09-25 18:43:00 +00004015/// \brief Determine if the two templates are equivalent.
4016static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4017 if (T1 == T2)
4018 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004019
Douglas Gregord5a423b2009-09-25 18:43:00 +00004020 if (!T1 || !T2)
4021 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004022
Douglas Gregord5a423b2009-09-25 18:43:00 +00004023 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4024}
4025
4026/// \brief Retrieve the most specialized of the given function template
4027/// specializations.
4028///
John McCallc373d482010-01-27 01:50:18 +00004029/// \param SpecBegin the start iterator of the function template
4030/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00004031///
John McCallc373d482010-01-27 01:50:18 +00004032/// \param SpecEnd the end iterator of the function template
4033/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00004034///
4035/// \param TPOC the partial ordering context to use to compare the function
4036/// template specializations.
4037///
Douglas Gregor5c7bf422011-01-11 17:34:58 +00004038/// \param NumCallArguments The number of arguments in a call, used only
4039/// when \c TPOC is \c TPOC_Call.
4040///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004041/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregord5a423b2009-09-25 18:43:00 +00004042/// diagnostic should occur.
4043///
4044/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4045/// no matching candidates.
4046///
4047/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4048/// occurs.
4049///
4050/// \param CandidateDiag partial diagnostic used for each function template
4051/// specialization that is a candidate in the ambiguous ordering. One parameter
4052/// in this diagnostic should be unbound, which will correspond to the string
4053/// describing the template arguments for the function template specialization.
4054///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004055/// \param Index if non-NULL and the result of this function is non-nULL,
Douglas Gregord5a423b2009-09-25 18:43:00 +00004056/// receives the index corresponding to the resulting function template
4057/// specialization.
4058///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004059/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00004060/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00004061///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004062/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
Douglas Gregord5a423b2009-09-25 18:43:00 +00004063/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00004064UnresolvedSetIterator
4065Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00004066 UnresolvedSetIterator SpecEnd,
John McCallc373d482010-01-27 01:50:18 +00004067 TemplatePartialOrderingContext TPOC,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00004068 unsigned NumCallArguments,
John McCallc373d482010-01-27 01:50:18 +00004069 SourceLocation Loc,
4070 const PartialDiagnostic &NoneDiag,
4071 const PartialDiagnostic &AmbigDiag,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004072 const PartialDiagnostic &CandidateDiag,
Richard Trieu6efd4c52011-11-23 22:32:32 +00004073 bool Complain,
4074 QualType TargetType) {
John McCallc373d482010-01-27 01:50:18 +00004075 if (SpecBegin == SpecEnd) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004076 if (Complain)
4077 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00004078 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004079 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004080
4081 if (SpecBegin + 1 == SpecEnd)
John McCallc373d482010-01-27 01:50:18 +00004082 return SpecBegin;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004083
Douglas Gregord5a423b2009-09-25 18:43:00 +00004084 // Find the function template that is better than all of the templates it
4085 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00004086 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004087 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00004088 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004089 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00004090 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4091 FunctionTemplateDecl *Challenger
4092 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004093 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00004094 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00004095 Loc, TPOC, NumCallArguments),
Douglas Gregord5a423b2009-09-25 18:43:00 +00004096 Challenger)) {
4097 Best = I;
4098 BestTemplate = Challenger;
4099 }
4100 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004101
Douglas Gregord5a423b2009-09-25 18:43:00 +00004102 // Make sure that the "best" function template is more specialized than all
4103 // of the others.
4104 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00004105 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4106 FunctionTemplateDecl *Challenger
4107 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004108 if (I != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004109 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00004110 Loc, TPOC, NumCallArguments),
Douglas Gregord5a423b2009-09-25 18:43:00 +00004111 BestTemplate)) {
4112 Ambiguous = true;
4113 break;
4114 }
4115 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004116
Douglas Gregord5a423b2009-09-25 18:43:00 +00004117 if (!Ambiguous) {
4118 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00004119 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004120 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004121
Douglas Gregord5a423b2009-09-25 18:43:00 +00004122 // Diagnose the ambiguity.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004123 if (Complain)
4124 Diag(Loc, AmbigDiag);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004125
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004126 if (Complain)
Douglas Gregord5a423b2009-09-25 18:43:00 +00004127 // FIXME: Can we order the candidates in some sane way?
Richard Trieu6efd4c52011-11-23 22:32:32 +00004128 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4129 PartialDiagnostic PD = CandidateDiag;
4130 PD << getTemplateArgumentBindingsText(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004131 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
John McCallc373d482010-01-27 01:50:18 +00004132 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Richard Trieu6efd4c52011-11-23 22:32:32 +00004133 if (!TargetType.isNull())
4134 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4135 TargetType);
4136 Diag((*I)->getLocation(), PD);
4137 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004138
John McCallc373d482010-01-27 01:50:18 +00004139 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004140}
4141
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004142/// \brief Returns the more specialized class template partial specialization
4143/// according to the rules of partial ordering of class template partial
4144/// specializations (C++ [temp.class.order]).
4145///
4146/// \param PS1 the first class template partial specialization
4147///
4148/// \param PS2 the second class template partial specialization
4149///
4150/// \returns the more specialized class template partial specialization. If
4151/// neither partial specialization is more specialized, returns NULL.
4152ClassTemplatePartialSpecializationDecl *
4153Sema::getMoreSpecializedPartialSpecialization(
4154 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00004155 ClassTemplatePartialSpecializationDecl *PS2,
4156 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004157 // C++ [temp.class.order]p1:
4158 // For two class template partial specializations, the first is at least as
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004159 // specialized as the second if, given the following rewrite to two
4160 // function templates, the first function template is at least as
4161 // specialized as the second according to the ordering rules for function
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004162 // templates (14.6.6.2):
4163 // - the first function template has the same template parameters as the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004164 // first partial specialization and has a single function parameter
4165 // whose type is a class template specialization with the template
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004166 // arguments of the first partial specialization, and
4167 // - the second function template has the same template parameters as the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004168 // second partial specialization and has a single function parameter
4169 // whose type is a class template specialization with the template
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004170 // arguments of the second partial specialization.
4171 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00004172 // Rather than synthesize function templates, we merely perform the
4173 // equivalent partial ordering by performing deduction directly on
4174 // the template arguments of the class template partial
4175 // specializations. This computation is slightly simpler than the
4176 // general problem of function template partial ordering, because
4177 // class template partial specializations are more constrained. We
4178 // know that every template parameter is deducible from the class
4179 // template partial specialization's template arguments, for
4180 // example.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004181 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Topper93e45992012-09-19 02:26:47 +00004182 TemplateDeductionInfo Info(Loc);
John McCall31f17ec2010-04-27 00:57:59 +00004183
4184 QualType PT1 = PS1->getInjectedSpecializationType();
4185 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004186
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004187 // Determine whether PS1 is at least as specialized as PS2
4188 Deduced.resize(PS2->getTemplateParameters()->size());
Sebastian Redlbb95e512012-01-17 22:49:52 +00004189 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4190 PS2->getTemplateParameters(),
Douglas Gregor5c7bf422011-01-11 17:34:58 +00004191 PT2, PT1, Info, Deduced, TDF_None,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004192 /*PartialOrdering=*/true,
Douglas Gregorb939a192011-01-21 17:29:42 +00004193 /*RefParamComparisons=*/0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00004194 if (Better1) {
Richard Smith7e54fb52012-07-16 01:09:10 +00004195 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00004196 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
Richard Smith7e54fb52012-07-16 01:09:10 +00004197 DeducedArgs, Info);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004198 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4199 PS1->getTemplateArgs(),
Douglas Gregor516e6e02010-04-29 06:31:36 +00004200 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00004201 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004202
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004203 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00004204 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004205 Deduced.resize(PS1->getTemplateParameters()->size());
Sebastian Redlbb95e512012-01-17 22:49:52 +00004206 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4207 PS1->getTemplateParameters(),
Douglas Gregor5c7bf422011-01-11 17:34:58 +00004208 PT1, PT2, Info, Deduced, TDF_None,
4209 /*PartialOrdering=*/true,
Douglas Gregorb939a192011-01-21 17:29:42 +00004210 /*RefParamComparisons=*/0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00004211 if (Better2) {
Richard Smith7e54fb52012-07-16 01:09:10 +00004212 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00004213 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
Richard Smith7e54fb52012-07-16 01:09:10 +00004214 DeducedArgs, Info);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004215 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4216 PS2->getTemplateArgs(),
Douglas Gregor516e6e02010-04-29 06:31:36 +00004217 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00004218 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004219
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004220 if (Better1 == Better2)
4221 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004222
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004223 return Better1? PS1 : PS2;
4224}
4225
Mike Stump1eb44332009-09-09 15:08:12 +00004226static void
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004227MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004228 const TemplateArgument &TemplateArg,
4229 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004230 unsigned Depth,
Benjamin Kramer013b3662012-01-30 16:17:39 +00004231 llvm::SmallBitVector &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004232
Douglas Gregore73bb602009-09-14 21:25:05 +00004233/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00004234/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00004235static void
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004236MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004237 const Expr *E,
4238 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004239 unsigned Depth,
Benjamin Kramer013b3662012-01-30 16:17:39 +00004240 llvm::SmallBitVector &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00004241 // We can deduce from a pack expansion.
4242 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4243 E = Expansion->getPattern();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004244
Richard Smith60983812012-07-09 03:07:20 +00004245 // Skip through any implicit casts we added while type-checking, and any
4246 // substitutions performed by template alias expansion.
4247 while (1) {
4248 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4249 E = ICE->getSubExpr();
4250 else if (const SubstNonTypeTemplateParmExpr *Subst =
4251 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4252 E = Subst->getReplacement();
4253 else
4254 break;
4255 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004256
4257 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore73bb602009-09-14 21:25:05 +00004258 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00004259 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00004260 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00004261 return;
4262
Mike Stump1eb44332009-09-09 15:08:12 +00004263 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00004264 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4265 if (!NTTP)
4266 return;
4267
Douglas Gregored9c0f92009-10-29 00:04:11 +00004268 if (NTTP->getDepth() == Depth)
4269 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00004270}
4271
Douglas Gregore73bb602009-09-14 21:25:05 +00004272/// \brief Mark the template parameters that are used by the given
4273/// nested name specifier.
4274static void
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004275MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004276 NestedNameSpecifier *NNS,
4277 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004278 unsigned Depth,
Benjamin Kramer013b3662012-01-30 16:17:39 +00004279 llvm::SmallBitVector &Used) {
Douglas Gregore73bb602009-09-14 21:25:05 +00004280 if (!NNS)
4281 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004282
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004283 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004284 Used);
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004285 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00004286 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00004287}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004288
Douglas Gregore73bb602009-09-14 21:25:05 +00004289/// \brief Mark the template parameters that are used by the given
4290/// template name.
4291static void
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004292MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004293 TemplateName Name,
4294 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004295 unsigned Depth,
Benjamin Kramer013b3662012-01-30 16:17:39 +00004296 llvm::SmallBitVector &Used) {
Douglas Gregore73bb602009-09-14 21:25:05 +00004297 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4298 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00004299 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4300 if (TTP->getDepth() == Depth)
4301 Used[TTP->getIndex()] = true;
4302 }
Douglas Gregore73bb602009-09-14 21:25:05 +00004303 return;
4304 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004305
Douglas Gregor788cd062009-11-11 01:00:40 +00004306 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004307 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor788cd062009-11-11 01:00:40 +00004308 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00004309 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004310 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004311 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00004312}
4313
4314/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00004315/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00004316static void
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004317MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore73bb602009-09-14 21:25:05 +00004318 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004319 unsigned Depth,
Benjamin Kramer013b3662012-01-30 16:17:39 +00004320 llvm::SmallBitVector &Used) {
Douglas Gregore73bb602009-09-14 21:25:05 +00004321 if (T.isNull())
4322 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004323
Douglas Gregor031a5882009-06-13 00:26:55 +00004324 // Non-dependent types have nothing deducible
4325 if (!T->isDependentType())
4326 return;
4327
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004328 T = Ctx.getCanonicalType(T);
Douglas Gregor031a5882009-06-13 00:26:55 +00004329 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00004330 case Type::Pointer:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004331 MarkUsedTemplateParameters(Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004332 cast<PointerType>(T)->getPointeeType(),
4333 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004334 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00004335 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004336 break;
4337
4338 case Type::BlockPointer:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004339 MarkUsedTemplateParameters(Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004340 cast<BlockPointerType>(T)->getPointeeType(),
4341 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004342 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00004343 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004344 break;
4345
4346 case Type::LValueReference:
4347 case Type::RValueReference:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004348 MarkUsedTemplateParameters(Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004349 cast<ReferenceType>(T)->getPointeeType(),
4350 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004351 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00004352 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004353 break;
4354
4355 case Type::MemberPointer: {
4356 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004357 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004358 Depth, Used);
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004359 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00004360 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004361 break;
4362 }
4363
4364 case Type::DependentSizedArray:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004365 MarkUsedTemplateParameters(Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004366 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00004367 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004368 // Fall through to check the element type
4369
4370 case Type::ConstantArray:
4371 case Type::IncompleteArray:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004372 MarkUsedTemplateParameters(Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004373 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00004374 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004375 break;
4376
4377 case Type::Vector:
4378 case Type::ExtVector:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004379 MarkUsedTemplateParameters(Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004380 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00004381 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004382 break;
4383
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004384 case Type::DependentSizedExtVector: {
4385 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00004386 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004387 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004388 Depth, Used);
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004389 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004390 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004391 break;
4392 }
4393
Douglas Gregor031a5882009-06-13 00:26:55 +00004394 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00004395 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004396 MarkUsedTemplateParameters(Ctx, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004397 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004398 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004399 MarkUsedTemplateParameters(Ctx, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004400 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004401 break;
4402 }
4403
Douglas Gregored9c0f92009-10-29 00:04:11 +00004404 case Type::TemplateTypeParm: {
4405 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4406 if (TTP->getDepth() == Depth)
4407 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00004408 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00004409 }
Douglas Gregor031a5882009-06-13 00:26:55 +00004410
Douglas Gregor0bc15d92011-01-14 05:11:40 +00004411 case Type::SubstTemplateTypeParmPack: {
4412 const SubstTemplateTypeParmPackType *Subst
4413 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004414 MarkUsedTemplateParameters(Ctx,
Douglas Gregor0bc15d92011-01-14 05:11:40 +00004415 QualType(Subst->getReplacedParameter(), 0),
4416 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004417 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregor0bc15d92011-01-14 05:11:40 +00004418 OnlyDeduced, Depth, Used);
4419 break;
4420 }
4421
John McCall31f17ec2010-04-27 00:57:59 +00004422 case Type::InjectedClassName:
4423 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4424 // fall through
4425
Douglas Gregor031a5882009-06-13 00:26:55 +00004426 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00004427 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00004428 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004429 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004430 Depth, Used);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004431
Douglas Gregor7b976ec2010-12-23 01:24:45 +00004432 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004433 // If the template argument list of P contains a pack expansion that is not
4434 // the last template argument, the entire template argument list is a
Douglas Gregor7b976ec2010-12-23 01:24:45 +00004435 // non-deduced context.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004436 if (OnlyDeduced &&
Douglas Gregor7b976ec2010-12-23 01:24:45 +00004437 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4438 break;
4439
Douglas Gregore73bb602009-09-14 21:25:05 +00004440 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004441 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004442 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004443 break;
4444 }
4445
Douglas Gregore73bb602009-09-14 21:25:05 +00004446 case Type::Complex:
4447 if (!OnlyDeduced)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004448 MarkUsedTemplateParameters(Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004449 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00004450 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00004451 break;
4452
Eli Friedmanb001de72011-10-06 23:00:33 +00004453 case Type::Atomic:
4454 if (!OnlyDeduced)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004455 MarkUsedTemplateParameters(Ctx,
Eli Friedmanb001de72011-10-06 23:00:33 +00004456 cast<AtomicType>(T)->getValueType(),
4457 OnlyDeduced, Depth, Used);
4458 break;
4459
Douglas Gregor4714c122010-03-31 17:34:00 +00004460 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00004461 if (!OnlyDeduced)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004462 MarkUsedTemplateParameters(Ctx,
Douglas Gregor4714c122010-03-31 17:34:00 +00004463 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00004464 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00004465 break;
4466
John McCall33500952010-06-11 00:33:02 +00004467 case Type::DependentTemplateSpecialization: {
4468 const DependentTemplateSpecializationType *Spec
4469 = cast<DependentTemplateSpecializationType>(T);
4470 if (!OnlyDeduced)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004471 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
John McCall33500952010-06-11 00:33:02 +00004472 OnlyDeduced, Depth, Used);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004473
Douglas Gregor7b976ec2010-12-23 01:24:45 +00004474 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004475 // If the template argument list of P contains a pack expansion that is not
4476 // the last template argument, the entire template argument list is a
Douglas Gregor7b976ec2010-12-23 01:24:45 +00004477 // non-deduced context.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004478 if (OnlyDeduced &&
Douglas Gregor7b976ec2010-12-23 01:24:45 +00004479 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4480 break;
4481
John McCall33500952010-06-11 00:33:02 +00004482 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004483 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCall33500952010-06-11 00:33:02 +00004484 Used);
4485 break;
4486 }
4487
John McCallad5e7382010-03-01 23:49:17 +00004488 case Type::TypeOf:
4489 if (!OnlyDeduced)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004490 MarkUsedTemplateParameters(Ctx,
John McCallad5e7382010-03-01 23:49:17 +00004491 cast<TypeOfType>(T)->getUnderlyingType(),
4492 OnlyDeduced, Depth, Used);
4493 break;
4494
4495 case Type::TypeOfExpr:
4496 if (!OnlyDeduced)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004497 MarkUsedTemplateParameters(Ctx,
John McCallad5e7382010-03-01 23:49:17 +00004498 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4499 OnlyDeduced, Depth, Used);
4500 break;
4501
4502 case Type::Decltype:
4503 if (!OnlyDeduced)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004504 MarkUsedTemplateParameters(Ctx,
John McCallad5e7382010-03-01 23:49:17 +00004505 cast<DecltypeType>(T)->getUnderlyingExpr(),
4506 OnlyDeduced, Depth, Used);
4507 break;
4508
Sean Huntca63c202011-05-24 22:41:36 +00004509 case Type::UnaryTransform:
4510 if (!OnlyDeduced)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004511 MarkUsedTemplateParameters(Ctx,
Sean Huntca63c202011-05-24 22:41:36 +00004512 cast<UnaryTransformType>(T)->getUnderlyingType(),
4513 OnlyDeduced, Depth, Used);
4514 break;
4515
Douglas Gregor7536dd52010-12-20 02:24:11 +00004516 case Type::PackExpansion:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004517 MarkUsedTemplateParameters(Ctx,
Douglas Gregor7536dd52010-12-20 02:24:11 +00004518 cast<PackExpansionType>(T)->getPattern(),
4519 OnlyDeduced, Depth, Used);
4520 break;
4521
Richard Smith34b41d92011-02-20 03:19:35 +00004522 case Type::Auto:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004523 MarkUsedTemplateParameters(Ctx,
Richard Smith34b41d92011-02-20 03:19:35 +00004524 cast<AutoType>(T)->getDeducedType(),
4525 OnlyDeduced, Depth, Used);
4526
Douglas Gregore73bb602009-09-14 21:25:05 +00004527 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00004528 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00004529 case Type::VariableArray:
4530 case Type::FunctionNoProto:
4531 case Type::Record:
4532 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00004533 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00004534 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00004535 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00004536 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00004537#define TYPE(Class, Base)
4538#define ABSTRACT_TYPE(Class, Base)
4539#define DEPENDENT_TYPE(Class, Base)
4540#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4541#include "clang/AST/TypeNodes.def"
4542 break;
4543 }
4544}
4545
Douglas Gregore73bb602009-09-14 21:25:05 +00004546/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00004547/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00004548static void
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004549MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004550 const TemplateArgument &TemplateArg,
4551 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004552 unsigned Depth,
Benjamin Kramer013b3662012-01-30 16:17:39 +00004553 llvm::SmallBitVector &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00004554 switch (TemplateArg.getKind()) {
4555 case TemplateArgument::Null:
4556 case TemplateArgument::Integral:
Douglas Gregord2008e22012-04-06 22:40:38 +00004557 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00004558 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004559
Eli Friedmand7a6b162012-09-26 02:36:12 +00004560 case TemplateArgument::NullPtr:
4561 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
4562 Depth, Used);
4563 break;
4564
Douglas Gregor031a5882009-06-13 00:26:55 +00004565 case TemplateArgument::Type:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004566 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004567 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004568 break;
4569
Douglas Gregor788cd062009-11-11 01:00:40 +00004570 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00004571 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004572 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004573 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor788cd062009-11-11 01:00:40 +00004574 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004575 break;
4576
4577 case TemplateArgument::Expression:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004578 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004579 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004580 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004581
Anders Carlssond01b1da2009-06-15 17:04:53 +00004582 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00004583 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
4584 PEnd = TemplateArg.pack_end();
4585 P != PEnd; ++P)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004586 MarkUsedTemplateParameters(Ctx, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00004587 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00004588 }
4589}
4590
James Dennett16ae9de2012-06-22 10:16:05 +00004591/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor031a5882009-06-13 00:26:55 +00004592/// template argument list.
4593///
4594/// \param TemplateArgs the template argument list from which template
4595/// parameters will be deduced.
4596///
James Dennett16ae9de2012-06-22 10:16:05 +00004597/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor031a5882009-06-13 00:26:55 +00004598/// to indicate when the corresponding template parameter will be
4599/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00004600void
Douglas Gregore73bb602009-09-14 21:25:05 +00004601Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004602 bool OnlyDeduced, unsigned Depth,
Benjamin Kramer013b3662012-01-30 16:17:39 +00004603 llvm::SmallBitVector &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00004604 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004605 // If the template argument list of P contains a pack expansion that is not
4606 // the last template argument, the entire template argument list is a
Douglas Gregor7b976ec2010-12-23 01:24:45 +00004607 // non-deduced context.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004608 if (OnlyDeduced &&
Douglas Gregor7b976ec2010-12-23 01:24:45 +00004609 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
4610 return;
4611
Douglas Gregor031a5882009-06-13 00:26:55 +00004612 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004613 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004614 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004615}
Douglas Gregor63f07c52009-09-18 23:21:38 +00004616
4617/// \brief Marks all of the template parameters that will be deduced by a
4618/// call to the given function template.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004619void
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004620Sema::MarkDeducedTemplateParameters(ASTContext &Ctx,
4621 FunctionTemplateDecl *FunctionTemplate,
Benjamin Kramer013b3662012-01-30 16:17:39 +00004622 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004623 TemplateParameterList *TemplateParams
Douglas Gregor63f07c52009-09-18 23:21:38 +00004624 = FunctionTemplate->getTemplateParameters();
4625 Deduced.clear();
4626 Deduced.resize(TemplateParams->size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004627
Douglas Gregor63f07c52009-09-18 23:21:38 +00004628 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4629 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004630 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00004631 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00004632}
Douglas Gregordbfb3712011-06-16 16:50:48 +00004633
4634bool hasDeducibleTemplateParameters(Sema &S,
4635 FunctionTemplateDecl *FunctionTemplate,
4636 QualType T) {
4637 if (!T->isDependentType())
4638 return false;
4639
4640 TemplateParameterList *TemplateParams
4641 = FunctionTemplate->getTemplateParameters();
Benjamin Kramer013b3662012-01-30 16:17:39 +00004642 llvm::SmallBitVector Deduced(TemplateParams->size());
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004643 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregordbfb3712011-06-16 16:50:48 +00004644 Deduced);
4645
Benjamin Kramer013b3662012-01-30 16:17:39 +00004646 return Deduced.any();
Douglas Gregordbfb3712011-06-16 16:50:48 +00004647}